OSDN Git Service

[automerger] Clear the Parcel before writing an exception during a transaction am...
[android-x86/frameworks-base.git] / services / core / java / com / android / server / pm / PackageManagerService.java
1 /*
2  * Copyright (C) 2006 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.android.server.pm;
18
19 import static android.Manifest.permission.DELETE_PACKAGES;
20 import static android.Manifest.permission.INSTALL_PACKAGES;
21 import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
22 import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
23 import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
24 import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
25 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
26 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
27 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
28 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
29 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
30 import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
31 import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
32 import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
33 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
34 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
35 import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
36 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
37 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
38 import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
39 import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
40 import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
41 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
42 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
43 import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
44 import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
45 import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
46 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
47 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
48 import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
49 import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
50 import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
51 import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
52 import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
53 import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
54 import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
55 import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
56 import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
57 import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
58 import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59 import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60 import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
61 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66 import static android.content.pm.PackageManager.MATCH_ALL;
67 import static android.content.pm.PackageManager.MATCH_ANY_USER;
68 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71 import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72 import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73 import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76 import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77 import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78 import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79 import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80 import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
81 import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
82 import static android.content.pm.PackageManager.PERMISSION_DENIED;
83 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
84 import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
85 import static android.content.pm.PackageParser.isApkFile;
86 import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
87 import static android.system.OsConstants.O_CREAT;
88 import static android.system.OsConstants.O_RDWR;
89 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
90 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
91 import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
92 import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
93 import static com.android.internal.util.ArrayUtils.appendInt;
94 import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
95 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
96 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
97 import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
98 import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
99 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
100 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
101 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
102 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
103 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
104 import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
105
106 import android.Manifest;
107 import android.annotation.IntDef;
108 import android.annotation.NonNull;
109 import android.annotation.Nullable;
110 import android.app.ActivityManager;
111 import android.app.AppOpsManager;
112 import android.app.IActivityManager;
113 import android.app.ResourcesManager;
114 import android.app.admin.IDevicePolicyManager;
115 import android.app.admin.SecurityLog;
116 import android.app.backup.IBackupManager;
117 import android.content.BroadcastReceiver;
118 import android.content.ComponentName;
119 import android.content.ContentResolver;
120 import android.content.Context;
121 import android.content.IIntentReceiver;
122 import android.content.Intent;
123 import android.content.IntentFilter;
124 import android.content.IntentSender;
125 import android.content.IntentSender.SendIntentException;
126 import android.content.ServiceConnection;
127 import android.content.pm.ActivityInfo;
128 import android.content.pm.ApplicationInfo;
129 import android.content.pm.AppsQueryHelper;
130 import android.content.pm.AuxiliaryResolveInfo;
131 import android.content.pm.ChangedPackages;
132 import android.content.pm.FallbackCategoryProvider;
133 import android.content.pm.FeatureInfo;
134 import android.content.pm.IOnPermissionsChangeListener;
135 import android.content.pm.IPackageDataObserver;
136 import android.content.pm.IPackageDeleteObserver;
137 import android.content.pm.IPackageDeleteObserver2;
138 import android.content.pm.IPackageInstallObserver2;
139 import android.content.pm.IPackageInstaller;
140 import android.content.pm.IPackageManager;
141 import android.content.pm.IPackageMoveObserver;
142 import android.content.pm.IPackageStatsObserver;
143 import android.content.pm.InstantAppInfo;
144 import android.content.pm.InstantAppRequest;
145 import android.content.pm.InstantAppResolveInfo;
146 import android.content.pm.InstrumentationInfo;
147 import android.content.pm.IntentFilterVerificationInfo;
148 import android.content.pm.KeySet;
149 import android.content.pm.PackageCleanItem;
150 import android.content.pm.PackageInfo;
151 import android.content.pm.PackageInfoLite;
152 import android.content.pm.PackageInstaller;
153 import android.content.pm.PackageManager;
154 import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
155 import android.content.pm.PackageManagerInternal;
156 import android.content.pm.PackageParser;
157 import android.content.pm.PackageParser.ActivityIntentInfo;
158 import android.content.pm.PackageParser.PackageLite;
159 import android.content.pm.PackageParser.PackageParserException;
160 import android.content.pm.PackageStats;
161 import android.content.pm.PackageUserState;
162 import android.content.pm.ParceledListSlice;
163 import android.content.pm.PermissionGroupInfo;
164 import android.content.pm.PermissionInfo;
165 import android.content.pm.ProviderInfo;
166 import android.content.pm.ResolveInfo;
167 import android.content.pm.ServiceInfo;
168 import android.content.pm.SharedLibraryInfo;
169 import android.content.pm.Signature;
170 import android.content.pm.UserInfo;
171 import android.content.pm.VerifierDeviceIdentity;
172 import android.content.pm.VerifierInfo;
173 import android.content.pm.VersionedPackage;
174 import android.content.res.Resources;
175 import android.database.ContentObserver;
176 import android.graphics.Bitmap;
177 import android.hardware.display.DisplayManager;
178 import android.net.Uri;
179 import android.os.AsyncTask;
180 import android.os.Binder;
181 import android.os.Build;
182 import android.os.Bundle;
183 import android.os.Debug;
184 import android.os.Environment;
185 import android.os.Environment.UserEnvironment;
186 import android.os.FileUtils;
187 import android.os.Handler;
188 import android.os.IBinder;
189 import android.os.Looper;
190 import android.os.Message;
191 import android.os.Parcel;
192 import android.os.ParcelFileDescriptor;
193 import android.os.PatternMatcher;
194 import android.os.Process;
195 import android.os.RemoteCallbackList;
196 import android.os.RemoteException;
197 import android.os.ResultReceiver;
198 import android.os.SELinux;
199 import android.os.ServiceManager;
200 import android.os.ShellCallback;
201 import android.os.SystemClock;
202 import android.os.SystemProperties;
203 import android.os.Trace;
204 import android.os.UserHandle;
205 import android.os.UserManager;
206 import android.os.UserManagerInternal;
207 import android.os.storage.IStorageManager;
208 import android.os.storage.StorageEventListener;
209 import android.os.storage.StorageManager;
210 import android.os.storage.StorageManagerInternal;
211 import android.os.storage.VolumeInfo;
212 import android.os.storage.VolumeRecord;
213 import android.provider.Settings.Global;
214 import android.provider.Settings.Secure;
215 import android.security.KeyStore;
216 import android.security.SystemKeyStore;
217 import android.service.pm.PackageServiceDumpProto;
218 import android.system.ErrnoException;
219 import android.system.Os;
220 import android.text.TextUtils;
221 import android.text.format.DateUtils;
222 import android.util.ArrayMap;
223 import android.util.ArraySet;
224 import android.util.Base64;
225 import android.util.BootTimingsTraceLog;
226 import android.util.DisplayMetrics;
227 import android.util.EventLog;
228 import android.util.ExceptionUtils;
229 import android.util.Log;
230 import android.util.LogPrinter;
231 import android.util.MathUtils;
232 import android.util.PackageUtils;
233 import android.util.Pair;
234 import android.util.PrintStreamPrinter;
235 import android.util.Slog;
236 import android.util.SparseArray;
237 import android.util.SparseBooleanArray;
238 import android.util.SparseIntArray;
239 import android.util.Xml;
240 import android.util.jar.StrictJarFile;
241 import android.util.proto.ProtoOutputStream;
242 import android.view.Display;
243
244 import com.android.internal.R;
245 import com.android.internal.annotations.GuardedBy;
246 import com.android.internal.app.IMediaContainerService;
247 import com.android.internal.app.ResolverActivity;
248 import com.android.internal.content.NativeLibraryHelper;
249 import com.android.internal.content.PackageHelper;
250 import com.android.internal.logging.MetricsLogger;
251 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
252 import com.android.internal.os.IParcelFileDescriptorFactory;
253 import com.android.internal.os.RoSystemProperties;
254 import com.android.internal.os.SomeArgs;
255 import com.android.internal.os.Zygote;
256 import com.android.internal.telephony.CarrierAppUtils;
257 import com.android.internal.util.ArrayUtils;
258 import com.android.internal.util.ConcurrentUtils;
259 import com.android.internal.util.DumpUtils;
260 import com.android.internal.util.FastPrintWriter;
261 import com.android.internal.util.FastXmlSerializer;
262 import com.android.internal.util.IndentingPrintWriter;
263 import com.android.internal.util.Preconditions;
264 import com.android.internal.util.XmlUtils;
265 import com.android.server.AttributeCache;
266 import com.android.server.DeviceIdleController;
267 import com.android.server.EventLogTags;
268 import com.android.server.FgThread;
269 import com.android.server.IntentResolver;
270 import com.android.server.LocalServices;
271 import com.android.server.LockGuard;
272 import com.android.server.ServiceThread;
273 import com.android.server.SystemConfig;
274 import com.android.server.SystemServerInitThreadPool;
275 import com.android.server.Watchdog;
276 import com.android.server.net.NetworkPolicyManagerInternal;
277 import com.android.server.pm.Installer.InstallerException;
278 import com.android.server.pm.PermissionsState.PermissionState;
279 import com.android.server.pm.Settings.DatabaseVersion;
280 import com.android.server.pm.Settings.VersionInfo;
281 import com.android.server.pm.dex.DexManager;
282 import com.android.server.storage.DeviceStorageMonitorInternal;
283
284 import dalvik.system.CloseGuard;
285 import dalvik.system.DexFile;
286 import dalvik.system.VMRuntime;
287
288 import libcore.io.IoUtils;
289 import libcore.util.EmptyArray;
290
291 import org.xmlpull.v1.XmlPullParser;
292 import org.xmlpull.v1.XmlPullParserException;
293 import org.xmlpull.v1.XmlSerializer;
294
295 import java.io.BufferedOutputStream;
296 import java.io.BufferedReader;
297 import java.io.ByteArrayInputStream;
298 import java.io.ByteArrayOutputStream;
299 import java.io.File;
300 import java.io.FileDescriptor;
301 import java.io.FileInputStream;
302 import java.io.FileOutputStream;
303 import java.io.FileReader;
304 import java.io.FilenameFilter;
305 import java.io.IOException;
306 import java.io.PrintWriter;
307 import java.lang.annotation.Retention;
308 import java.lang.annotation.RetentionPolicy;
309 import java.nio.charset.StandardCharsets;
310 import java.security.DigestInputStream;
311 import java.security.MessageDigest;
312 import java.security.NoSuchAlgorithmException;
313 import java.security.PublicKey;
314 import java.security.SecureRandom;
315 import java.security.cert.Certificate;
316 import java.security.cert.CertificateEncodingException;
317 import java.security.cert.CertificateException;
318 import java.text.SimpleDateFormat;
319 import java.util.ArrayList;
320 import java.util.Arrays;
321 import java.util.Collection;
322 import java.util.Collections;
323 import java.util.Comparator;
324 import java.util.Date;
325 import java.util.HashMap;
326 import java.util.HashSet;
327 import java.util.Iterator;
328 import java.util.List;
329 import java.util.Map;
330 import java.util.Objects;
331 import java.util.Set;
332 import java.util.concurrent.CountDownLatch;
333 import java.util.concurrent.Future;
334 import java.util.concurrent.TimeUnit;
335 import java.util.concurrent.atomic.AtomicBoolean;
336 import java.util.concurrent.atomic.AtomicInteger;
337
338 /**
339  * Keep track of all those APKs everywhere.
340  * <p>
341  * Internally there are two important locks:
342  * <ul>
343  * <li>{@link #mPackages} is used to guard all in-memory parsed package details
344  * and other related state. It is a fine-grained lock that should only be held
345  * momentarily, as it's one of the most contended locks in the system.
346  * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
347  * operations typically involve heavy lifting of application data on disk. Since
348  * {@code installd} is single-threaded, and it's operations can often be slow,
349  * this lock should never be acquired while already holding {@link #mPackages}.
350  * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
351  * holding {@link #mInstallLock}.
352  * </ul>
353  * Many internal methods rely on the caller to hold the appropriate locks, and
354  * this contract is expressed through method name suffixes:
355  * <ul>
356  * <li>fooLI(): the caller must hold {@link #mInstallLock}
357  * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
358  * being modified must be frozen
359  * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
360  * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
361  * </ul>
362  * <p>
363  * Because this class is very central to the platform's security; please run all
364  * CTS and unit tests whenever making modifications:
365  *
366  * <pre>
367  * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
368  * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
369  * </pre>
370  */
371 public class PackageManagerService extends IPackageManager.Stub
372         implements PackageSender {
373     static final String TAG = "PackageManager";
374     static final boolean DEBUG_SETTINGS = false;
375     static final boolean DEBUG_PREFERRED = false;
376     static final boolean DEBUG_UPGRADE = false;
377     static final boolean DEBUG_DOMAIN_VERIFICATION = false;
378     private static final boolean DEBUG_BACKUP = false;
379     private static final boolean DEBUG_INSTALL = false;
380     private static final boolean DEBUG_REMOVE = false;
381     private static final boolean DEBUG_BROADCASTS = false;
382     private static final boolean DEBUG_SHOW_INFO = false;
383     private static final boolean DEBUG_PACKAGE_INFO = false;
384     private static final boolean DEBUG_INTENT_MATCHING = false;
385     private static final boolean DEBUG_PACKAGE_SCANNING = false;
386     private static final boolean DEBUG_VERIFY = false;
387     private static final boolean DEBUG_FILTERS = false;
388     private static final boolean DEBUG_PERMISSIONS = false;
389     private static final boolean DEBUG_SHARED_LIBRARIES = false;
390
391     // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
392     // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
393     // user, but by default initialize to this.
394     public static final boolean DEBUG_DEXOPT = false;
395
396     private static final boolean DEBUG_ABI_SELECTION = false;
397     private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
398     private static final boolean DEBUG_TRIAGED_MISSING = false;
399     private static final boolean DEBUG_APP_DATA = false;
400
401     /** REMOVE. According to Svet, this was only used to reset permissions during development. */
402     static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
403
404     private static final boolean HIDE_EPHEMERAL_APIS = false;
405
406     private static final boolean ENABLE_FREE_CACHE_V2 =
407             SystemProperties.getBoolean("fw.free_cache_v2", true);
408
409     private static final int RADIO_UID = Process.PHONE_UID;
410     private static final int LOG_UID = Process.LOG_UID;
411     private static final int NFC_UID = Process.NFC_UID;
412     private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
413     private static final int SHELL_UID = Process.SHELL_UID;
414
415     // Cap the size of permission trees that 3rd party apps can define
416     private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
417
418     // Suffix used during package installation when copying/moving
419     // package apks to install directory.
420     private static final String INSTALL_PACKAGE_SUFFIX = "-";
421
422     static final int SCAN_NO_DEX = 1<<1;
423     static final int SCAN_FORCE_DEX = 1<<2;
424     static final int SCAN_UPDATE_SIGNATURE = 1<<3;
425     static final int SCAN_NEW_INSTALL = 1<<4;
426     static final int SCAN_UPDATE_TIME = 1<<5;
427     static final int SCAN_BOOTING = 1<<6;
428     static final int SCAN_TRUSTED_OVERLAY = 1<<7;
429     static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
430     static final int SCAN_REPLACING = 1<<9;
431     static final int SCAN_REQUIRE_KNOWN = 1<<10;
432     static final int SCAN_MOVE = 1<<11;
433     static final int SCAN_INITIAL = 1<<12;
434     static final int SCAN_CHECK_ONLY = 1<<13;
435     static final int SCAN_DONT_KILL_APP = 1<<14;
436     static final int SCAN_IGNORE_FROZEN = 1<<15;
437     static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
438     static final int SCAN_AS_INSTANT_APP = 1<<17;
439     static final int SCAN_AS_FULL_APP = 1<<18;
440     /** Should not be with the scan flags */
441     static final int FLAGS_REMOVE_CHATTY = 1<<31;
442
443     private static final String STATIC_SHARED_LIB_DELIMITER = "_";
444
445     private static final int[] EMPTY_INT_ARRAY = new int[0];
446
447     private static final int TYPE_UNKNOWN = 0;
448     private static final int TYPE_ACTIVITY = 1;
449     private static final int TYPE_RECEIVER = 2;
450     private static final int TYPE_SERVICE = 3;
451     private static final int TYPE_PROVIDER = 4;
452     @IntDef(prefix = { "TYPE_" }, value = {
453             TYPE_UNKNOWN,
454             TYPE_ACTIVITY,
455             TYPE_RECEIVER,
456             TYPE_SERVICE,
457             TYPE_PROVIDER,
458     })
459     @Retention(RetentionPolicy.SOURCE)
460     public @interface ComponentType {}
461
462     /**
463      * Timeout (in milliseconds) after which the watchdog should declare that
464      * our handler thread is wedged.  The usual default for such things is one
465      * minute but we sometimes do very lengthy I/O operations on this thread,
466      * such as installing multi-gigabyte applications, so ours needs to be longer.
467      */
468     static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
469
470     /**
471      * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
472      * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
473      * settings entry if available, otherwise we use the hardcoded default.  If it's been
474      * more than this long since the last fstrim, we force one during the boot sequence.
475      *
476      * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
477      * one gets run at the next available charging+idle time.  This final mandatory
478      * no-fstrim check kicks in only of the other scheduling criteria is never met.
479      */
480     private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
481
482     /**
483      * Whether verification is enabled by default.
484      */
485     private static final boolean DEFAULT_VERIFY_ENABLE = true;
486
487     /**
488      * The default maximum time to wait for the verification agent to return in
489      * milliseconds.
490      */
491     private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
492
493     /**
494      * The default response for package verification timeout.
495      *
496      * This can be either PackageManager.VERIFICATION_ALLOW or
497      * PackageManager.VERIFICATION_REJECT.
498      */
499     private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
500
501     static final String PLATFORM_PACKAGE_NAME = "android";
502
503     static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
504
505     static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
506             DEFAULT_CONTAINER_PACKAGE,
507             "com.android.defcontainer.DefaultContainerService");
508
509     private static final String KILL_APP_REASON_GIDS_CHANGED =
510             "permission grant or revoke changed gids";
511
512     private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
513             "permissions revoked";
514
515     private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
516
517     private static final String PACKAGE_SCHEME = "package";
518
519     private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
520
521     /** Permission grant: not grant the permission. */
522     private static final int GRANT_DENIED = 1;
523
524     /** Permission grant: grant the permission as an install permission. */
525     private static final int GRANT_INSTALL = 2;
526
527     /** Permission grant: grant the permission as a runtime one. */
528     private static final int GRANT_RUNTIME = 3;
529
530     /** Permission grant: grant as runtime a permission that was granted as an install time one. */
531     private static final int GRANT_UPGRADE = 4;
532
533     /** Canonical intent used to identify what counts as a "web browser" app */
534     private static final Intent sBrowserIntent;
535     static {
536         sBrowserIntent = new Intent();
537         sBrowserIntent.setAction(Intent.ACTION_VIEW);
538         sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
539         sBrowserIntent.setData(Uri.parse("http:"));
540     }
541
542     /**
543      * The set of all protected actions [i.e. those actions for which a high priority
544      * intent filter is disallowed].
545      */
546     private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
547     static {
548         PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
549         PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
550         PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
551         PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
552     }
553
554     // Compilation reasons.
555     public static final int REASON_FIRST_BOOT = 0;
556     public static final int REASON_BOOT = 1;
557     public static final int REASON_INSTALL = 2;
558     public static final int REASON_BACKGROUND_DEXOPT = 3;
559     public static final int REASON_AB_OTA = 4;
560
561     public static final int REASON_LAST = REASON_AB_OTA;
562
563     /** All dangerous permission names in the same order as the events in MetricsEvent */
564     private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
565             Manifest.permission.READ_CALENDAR,
566             Manifest.permission.WRITE_CALENDAR,
567             Manifest.permission.CAMERA,
568             Manifest.permission.READ_CONTACTS,
569             Manifest.permission.WRITE_CONTACTS,
570             Manifest.permission.GET_ACCOUNTS,
571             Manifest.permission.ACCESS_FINE_LOCATION,
572             Manifest.permission.ACCESS_COARSE_LOCATION,
573             Manifest.permission.RECORD_AUDIO,
574             Manifest.permission.READ_PHONE_STATE,
575             Manifest.permission.CALL_PHONE,
576             Manifest.permission.READ_CALL_LOG,
577             Manifest.permission.WRITE_CALL_LOG,
578             Manifest.permission.ADD_VOICEMAIL,
579             Manifest.permission.USE_SIP,
580             Manifest.permission.PROCESS_OUTGOING_CALLS,
581             Manifest.permission.READ_CELL_BROADCASTS,
582             Manifest.permission.BODY_SENSORS,
583             Manifest.permission.SEND_SMS,
584             Manifest.permission.RECEIVE_SMS,
585             Manifest.permission.READ_SMS,
586             Manifest.permission.RECEIVE_WAP_PUSH,
587             Manifest.permission.RECEIVE_MMS,
588             Manifest.permission.READ_EXTERNAL_STORAGE,
589             Manifest.permission.WRITE_EXTERNAL_STORAGE,
590             Manifest.permission.READ_PHONE_NUMBERS,
591             Manifest.permission.ANSWER_PHONE_CALLS);
592
593
594     /**
595      * Version number for the package parser cache. Increment this whenever the format or
596      * extent of cached data changes. See {@code PackageParser#setCacheDir}.
597      */
598     private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
599
600     /**
601      * Whether the package parser cache is enabled.
602      */
603     private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
604
605     final ServiceThread mHandlerThread;
606
607     final PackageHandler mHandler;
608
609     private final ProcessLoggingHandler mProcessLoggingHandler;
610
611     /**
612      * Messages for {@link #mHandler} that need to wait for system ready before
613      * being dispatched.
614      */
615     private ArrayList<Message> mPostSystemReadyMessages;
616
617     final int mSdkVersion = Build.VERSION.SDK_INT;
618
619     final Context mContext;
620     final boolean mFactoryTest;
621     final boolean mOnlyCore;
622     final DisplayMetrics mMetrics;
623     final int mDefParseFlags;
624     final String[] mSeparateProcesses;
625     final boolean mIsUpgrade;
626     final boolean mIsPreNUpgrade;
627     final boolean mIsPreNMR1Upgrade;
628
629     // Have we told the Activity Manager to whitelist the default container service by uid yet?
630     @GuardedBy("mPackages")
631     boolean mDefaultContainerWhitelisted = false;
632
633     @GuardedBy("mPackages")
634     private boolean mDexOptDialogShown;
635
636     /** The location for ASEC container files on internal storage. */
637     final String mAsecInternalPath;
638
639     // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
640     // LOCK HELD.  Can be called with mInstallLock held.
641     @GuardedBy("mInstallLock")
642     final Installer mInstaller;
643
644     /** Directory where installed third-party apps stored */
645     final File mAppInstallDir;
646
647     /**
648      * Directory to which applications installed internally have their
649      * 32 bit native libraries copied.
650      */
651     private File mAppLib32InstallDir;
652
653     // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
654     // apps.
655     final File mDrmAppPrivateInstallDir;
656
657     // ----------------------------------------------------------------
658
659     // Lock for state used when installing and doing other long running
660     // operations.  Methods that must be called with this lock held have
661     // the suffix "LI".
662     final Object mInstallLock = new Object();
663
664     // ----------------------------------------------------------------
665
666     // Keys are String (package name), values are Package.  This also serves
667     // as the lock for the global state.  Methods that must be called with
668     // this lock held have the prefix "LP".
669     @GuardedBy("mPackages")
670     final ArrayMap<String, PackageParser.Package> mPackages =
671             new ArrayMap<String, PackageParser.Package>();
672
673     final ArrayMap<String, Set<String>> mKnownCodebase =
674             new ArrayMap<String, Set<String>>();
675
676     // Keys are isolated uids and values are the uid of the application
677     // that created the isolated proccess.
678     @GuardedBy("mPackages")
679     final SparseIntArray mIsolatedOwners = new SparseIntArray();
680
681     /**
682      * Tracks new system packages [received in an OTA] that we expect to
683      * find updated user-installed versions. Keys are package name, values
684      * are package location.
685      */
686     final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
687     /**
688      * Tracks high priority intent filters for protected actions. During boot, certain
689      * filter actions are protected and should never be allowed to have a high priority
690      * intent filter for them. However, there is one, and only one exception -- the
691      * setup wizard. It must be able to define a high priority intent filter for these
692      * actions to ensure there are no escapes from the wizard. We need to delay processing
693      * of these during boot as we need to look at all of the system packages in order
694      * to know which component is the setup wizard.
695      */
696     private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
697     /**
698      * Whether or not processing protected filters should be deferred.
699      */
700     private boolean mDeferProtectedFilters = true;
701
702     /**
703      * Tracks existing system packages prior to receiving an OTA. Keys are package name.
704      */
705     final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
706     /**
707      * Whether or not system app permissions should be promoted from install to runtime.
708      */
709     boolean mPromoteSystemApps;
710
711     @GuardedBy("mPackages")
712     final Settings mSettings;
713
714     /**
715      * Set of package names that are currently "frozen", which means active
716      * surgery is being done on the code/data for that package. The platform
717      * will refuse to launch frozen packages to avoid race conditions.
718      *
719      * @see PackageFreezer
720      */
721     @GuardedBy("mPackages")
722     final ArraySet<String> mFrozenPackages = new ArraySet<>();
723
724     final ProtectedPackages mProtectedPackages;
725
726     boolean mFirstBoot;
727
728     PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
729
730     // System configuration read by SystemConfig.
731     final int[] mGlobalGids;
732     final SparseArray<ArraySet<String>> mSystemPermissions;
733     @GuardedBy("mAvailableFeatures")
734     final ArrayMap<String, FeatureInfo> mAvailableFeatures;
735
736     // If mac_permissions.xml was found for seinfo labeling.
737     boolean mFoundPolicyFile;
738
739     private final InstantAppRegistry mInstantAppRegistry;
740
741     @GuardedBy("mPackages")
742     int mChangedPackagesSequenceNumber;
743     /**
744      * List of changed [installed, removed or updated] packages.
745      * mapping from user id -> sequence number -> package name
746      */
747     @GuardedBy("mPackages")
748     final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
749     /**
750      * The sequence number of the last change to a package.
751      * mapping from user id -> package name -> sequence number
752      */
753     @GuardedBy("mPackages")
754     final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
755
756     class PackageParserCallback implements PackageParser.Callback {
757         @Override public final boolean hasFeature(String feature) {
758             return PackageManagerService.this.hasSystemFeature(feature, 0);
759         }
760
761         final List<PackageParser.Package> getStaticOverlayPackagesLocked(
762                 Collection<PackageParser.Package> allPackages, String targetPackageName) {
763             List<PackageParser.Package> overlayPackages = null;
764             for (PackageParser.Package p : allPackages) {
765                 if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
766                     if (overlayPackages == null) {
767                         overlayPackages = new ArrayList<PackageParser.Package>();
768                     }
769                     overlayPackages.add(p);
770                 }
771             }
772             if (overlayPackages != null) {
773                 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
774                     public int compare(PackageParser.Package p1, PackageParser.Package p2) {
775                         return p1.mOverlayPriority - p2.mOverlayPriority;
776                     }
777                 };
778                 Collections.sort(overlayPackages, cmp);
779             }
780             return overlayPackages;
781         }
782
783         final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
784                 String targetPackageName, String targetPath) {
785             if ("android".equals(targetPackageName)) {
786                 // Static RROs targeting to "android", ie framework-res.apk, are already applied by
787                 // native AssetManager.
788                 return null;
789             }
790             List<PackageParser.Package> overlayPackages =
791                     getStaticOverlayPackagesLocked(allPackages, targetPackageName);
792             if (overlayPackages == null || overlayPackages.isEmpty()) {
793                 return null;
794             }
795             List<String> overlayPathList = null;
796             for (PackageParser.Package overlayPackage : overlayPackages) {
797                 if (targetPath == null) {
798                     if (overlayPathList == null) {
799                         overlayPathList = new ArrayList<String>();
800                     }
801                     overlayPathList.add(overlayPackage.baseCodePath);
802                     continue;
803                 }
804
805                 try {
806                     // Creates idmaps for system to parse correctly the Android manifest of the
807                     // target package.
808                     //
809                     // OverlayManagerService will update each of them with a correct gid from its
810                     // target package app id.
811                     mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
812                             UserHandle.getSharedAppGid(
813                                     UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
814                     if (overlayPathList == null) {
815                         overlayPathList = new ArrayList<String>();
816                     }
817                     overlayPathList.add(overlayPackage.baseCodePath);
818                 } catch (InstallerException e) {
819                     Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
820                             overlayPackage.baseCodePath);
821                 }
822             }
823             return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
824         }
825
826         String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
827             synchronized (mPackages) {
828                 return getStaticOverlayPathsLocked(
829                         mPackages.values(), targetPackageName, targetPath);
830             }
831         }
832
833         @Override public final String[] getOverlayApks(String targetPackageName) {
834             return getStaticOverlayPaths(targetPackageName, null);
835         }
836
837         @Override public final String[] getOverlayPaths(String targetPackageName,
838                 String targetPath) {
839             return getStaticOverlayPaths(targetPackageName, targetPath);
840         }
841     };
842
843     class ParallelPackageParserCallback extends PackageParserCallback {
844         List<PackageParser.Package> mOverlayPackages = null;
845
846         void findStaticOverlayPackages() {
847             synchronized (mPackages) {
848                 for (PackageParser.Package p : mPackages.values()) {
849                     if (p.mIsStaticOverlay) {
850                         if (mOverlayPackages == null) {
851                             mOverlayPackages = new ArrayList<PackageParser.Package>();
852                         }
853                         mOverlayPackages.add(p);
854                     }
855                 }
856             }
857         }
858
859         @Override
860         synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
861             // We can trust mOverlayPackages without holding mPackages because package uninstall
862             // can't happen while running parallel parsing.
863             // Moreover holding mPackages on each parsing thread causes dead-lock.
864             return mOverlayPackages == null ? null :
865                     getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
866         }
867     }
868
869     final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
870     final ParallelPackageParserCallback mParallelPackageParserCallback =
871             new ParallelPackageParserCallback();
872
873     public static final class SharedLibraryEntry {
874         public final @Nullable String path;
875         public final @Nullable String apk;
876         public final @NonNull SharedLibraryInfo info;
877
878         SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
879                 String declaringPackageName, int declaringPackageVersionCode) {
880             path = _path;
881             apk = _apk;
882             info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
883                     declaringPackageName, declaringPackageVersionCode), null);
884         }
885     }
886
887     // Currently known shared libraries.
888     final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
889     final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
890             new ArrayMap<>();
891
892     // All available activities, for your resolving pleasure.
893     final ActivityIntentResolver mActivities =
894             new ActivityIntentResolver();
895
896     // All available receivers, for your resolving pleasure.
897     final ActivityIntentResolver mReceivers =
898             new ActivityIntentResolver();
899
900     // All available services, for your resolving pleasure.
901     final ServiceIntentResolver mServices = new ServiceIntentResolver();
902
903     // All available providers, for your resolving pleasure.
904     final ProviderIntentResolver mProviders = new ProviderIntentResolver();
905
906     // Mapping from provider base names (first directory in content URI codePath)
907     // to the provider information.
908     final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
909             new ArrayMap<String, PackageParser.Provider>();
910
911     // Mapping from instrumentation class names to info about them.
912     final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
913             new ArrayMap<ComponentName, PackageParser.Instrumentation>();
914
915     // Mapping from permission names to info about them.
916     final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
917             new ArrayMap<String, PackageParser.PermissionGroup>();
918
919     // Packages whose data we have transfered into another package, thus
920     // should no longer exist.
921     final ArraySet<String> mTransferedPackages = new ArraySet<String>();
922
923     // Broadcast actions that are only available to the system.
924     final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
925
926     /** List of packages waiting for verification. */
927     final SparseArray<PackageVerificationState> mPendingVerification
928             = new SparseArray<PackageVerificationState>();
929
930     /** Set of packages associated with each app op permission. */
931     final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
932
933     final PackageInstallerService mInstallerService;
934
935     private final PackageDexOptimizer mPackageDexOptimizer;
936     // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
937     // is used by other apps).
938     private final DexManager mDexManager;
939
940     private AtomicInteger mNextMoveId = new AtomicInteger();
941     private final MoveCallbacks mMoveCallbacks;
942
943     private final OnPermissionChangeListeners mOnPermissionChangeListeners;
944
945     // Cache of users who need badging.
946     SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
947
948     /** Token for keys in mPendingVerification. */
949     private int mPendingVerificationToken = 0;
950
951     volatile boolean mSystemReady;
952     volatile boolean mSafeMode;
953     volatile boolean mHasSystemUidErrors;
954     private volatile boolean mEphemeralAppsDisabled;
955
956     ApplicationInfo mAndroidApplication;
957     final ActivityInfo mResolveActivity = new ActivityInfo();
958     final ResolveInfo mResolveInfo = new ResolveInfo();
959     ComponentName mResolveComponentName;
960     PackageParser.Package mPlatformPackage;
961     ComponentName mCustomResolverComponentName;
962
963     boolean mResolverReplaced = false;
964
965     private final @Nullable ComponentName mIntentFilterVerifierComponent;
966     private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
967
968     private int mIntentFilterVerificationToken = 0;
969
970     /** The service connection to the ephemeral resolver */
971     final EphemeralResolverConnection mInstantAppResolverConnection;
972     /** Component used to show resolver settings for Instant Apps */
973     final ComponentName mInstantAppResolverSettingsComponent;
974
975     /** Activity used to install instant applications */
976     ActivityInfo mInstantAppInstallerActivity;
977     final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
978
979     final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
980             = new SparseArray<IntentFilterVerificationState>();
981
982     final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
983
984     // List of packages names to keep cached, even if they are uninstalled for all users
985     private List<String> mKeepUninstalledPackages;
986
987     private UserManagerInternal mUserManagerInternal;
988
989     private DeviceIdleController.LocalService mDeviceIdleController;
990
991     private File mCacheDir;
992
993     private ArraySet<String> mPrivappPermissionsViolations;
994
995     private Future<?> mPrepareAppDataFuture;
996
997     private static class IFVerificationParams {
998         PackageParser.Package pkg;
999         boolean replacing;
1000         int userId;
1001         int verifierUid;
1002
1003         public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1004                 int _userId, int _verifierUid) {
1005             pkg = _pkg;
1006             replacing = _replacing;
1007             userId = _userId;
1008             replacing = _replacing;
1009             verifierUid = _verifierUid;
1010         }
1011     }
1012
1013     private interface IntentFilterVerifier<T extends IntentFilter> {
1014         boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1015                                                T filter, String packageName);
1016         void startVerifications(int userId);
1017         void receiveVerificationResponse(int verificationId);
1018     }
1019
1020     private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1021         private Context mContext;
1022         private ComponentName mIntentFilterVerifierComponent;
1023         private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1024
1025         public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1026             mContext = context;
1027             mIntentFilterVerifierComponent = verifierComponent;
1028         }
1029
1030         private String getDefaultScheme() {
1031             return IntentFilter.SCHEME_HTTPS;
1032         }
1033
1034         @Override
1035         public void startVerifications(int userId) {
1036             // Launch verifications requests
1037             int count = mCurrentIntentFilterVerifications.size();
1038             for (int n=0; n<count; n++) {
1039                 int verificationId = mCurrentIntentFilterVerifications.get(n);
1040                 final IntentFilterVerificationState ivs =
1041                         mIntentFilterVerificationStates.get(verificationId);
1042
1043                 String packageName = ivs.getPackageName();
1044
1045                 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1046                 final int filterCount = filters.size();
1047                 ArraySet<String> domainsSet = new ArraySet<>();
1048                 for (int m=0; m<filterCount; m++) {
1049                     PackageParser.ActivityIntentInfo filter = filters.get(m);
1050                     domainsSet.addAll(filter.getHostsList());
1051                 }
1052                 synchronized (mPackages) {
1053                     if (mSettings.createIntentFilterVerificationIfNeededLPw(
1054                             packageName, domainsSet) != null) {
1055                         scheduleWriteSettingsLocked();
1056                     }
1057                 }
1058                 sendVerificationRequest(userId, verificationId, ivs);
1059             }
1060             mCurrentIntentFilterVerifications.clear();
1061         }
1062
1063         private void sendVerificationRequest(int userId, int verificationId,
1064                 IntentFilterVerificationState ivs) {
1065
1066             Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1067             verificationIntent.putExtra(
1068                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1069                     verificationId);
1070             verificationIntent.putExtra(
1071                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1072                     getDefaultScheme());
1073             verificationIntent.putExtra(
1074                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1075                     ivs.getHostsString());
1076             verificationIntent.putExtra(
1077                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1078                     ivs.getPackageName());
1079             verificationIntent.setComponent(mIntentFilterVerifierComponent);
1080             verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1081
1082             DeviceIdleController.LocalService idleController = getDeviceIdleController();
1083             idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1084                     mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1085                     userId, false, "intent filter verifier");
1086
1087             UserHandle user = new UserHandle(userId);
1088             mContext.sendBroadcastAsUser(verificationIntent, user);
1089             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1090                     "Sending IntentFilter verification broadcast");
1091         }
1092
1093         public void receiveVerificationResponse(int verificationId) {
1094             IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1095
1096             final boolean verified = ivs.isVerified();
1097
1098             ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1099             final int count = filters.size();
1100             if (DEBUG_DOMAIN_VERIFICATION) {
1101                 Slog.i(TAG, "Received verification response " + verificationId
1102                         + " for " + count + " filters, verified=" + verified);
1103             }
1104             for (int n=0; n<count; n++) {
1105                 PackageParser.ActivityIntentInfo filter = filters.get(n);
1106                 filter.setVerified(verified);
1107
1108                 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1109                         + " verified with result:" + verified + " and hosts:"
1110                         + ivs.getHostsString());
1111             }
1112
1113             mIntentFilterVerificationStates.remove(verificationId);
1114
1115             final String packageName = ivs.getPackageName();
1116             IntentFilterVerificationInfo ivi = null;
1117
1118             synchronized (mPackages) {
1119                 ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1120             }
1121             if (ivi == null) {
1122                 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1123                         + verificationId + " packageName:" + packageName);
1124                 return;
1125             }
1126             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1127                     "Updating IntentFilterVerificationInfo for package " + packageName
1128                             +" verificationId:" + verificationId);
1129
1130             synchronized (mPackages) {
1131                 if (verified) {
1132                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1133                 } else {
1134                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1135                 }
1136                 scheduleWriteSettingsLocked();
1137
1138                 final int userId = ivs.getUserId();
1139                 if (userId != UserHandle.USER_ALL) {
1140                     final int userStatus =
1141                             mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1142
1143                     int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1144                     boolean needUpdate = false;
1145
1146                     // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1147                     // already been set by the User thru the Disambiguation dialog
1148                     switch (userStatus) {
1149                         case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1150                             if (verified) {
1151                                 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1152                             } else {
1153                                 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1154                             }
1155                             needUpdate = true;
1156                             break;
1157
1158                         case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1159                             if (verified) {
1160                                 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1161                                 needUpdate = true;
1162                             }
1163                             break;
1164
1165                         default:
1166                             // Nothing to do
1167                     }
1168
1169                     if (needUpdate) {
1170                         mSettings.updateIntentFilterVerificationStatusLPw(
1171                                 packageName, updatedStatus, userId);
1172                         scheduleWritePackageRestrictionsLocked(userId);
1173                     }
1174                 }
1175             }
1176         }
1177
1178         @Override
1179         public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1180                     ActivityIntentInfo filter, String packageName) {
1181             if (!hasValidDomains(filter)) {
1182                 return false;
1183             }
1184             IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1185             if (ivs == null) {
1186                 ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1187                         packageName);
1188             }
1189             if (DEBUG_DOMAIN_VERIFICATION) {
1190                 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1191             }
1192             ivs.addFilter(filter);
1193             return true;
1194         }
1195
1196         private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1197                 int userId, int verificationId, String packageName) {
1198             IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1199                     verifierUid, userId, packageName);
1200             ivs.setPendingState();
1201             synchronized (mPackages) {
1202                 mIntentFilterVerificationStates.append(verificationId, ivs);
1203                 mCurrentIntentFilterVerifications.add(verificationId);
1204             }
1205             return ivs;
1206         }
1207     }
1208
1209     private static boolean hasValidDomains(ActivityIntentInfo filter) {
1210         return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1211                 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1212                         filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1213     }
1214
1215     // Set of pending broadcasts for aggregating enable/disable of components.
1216     static class PendingPackageBroadcasts {
1217         // for each user id, a map of <package name -> components within that package>
1218         final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1219
1220         public PendingPackageBroadcasts() {
1221             mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1222         }
1223
1224         public ArrayList<String> get(int userId, String packageName) {
1225             ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1226             return packages.get(packageName);
1227         }
1228
1229         public void put(int userId, String packageName, ArrayList<String> components) {
1230             ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1231             packages.put(packageName, components);
1232         }
1233
1234         public void remove(int userId, String packageName) {
1235             ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1236             if (packages != null) {
1237                 packages.remove(packageName);
1238             }
1239         }
1240
1241         public void remove(int userId) {
1242             mUidMap.remove(userId);
1243         }
1244
1245         public int userIdCount() {
1246             return mUidMap.size();
1247         }
1248
1249         public int userIdAt(int n) {
1250             return mUidMap.keyAt(n);
1251         }
1252
1253         public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1254             return mUidMap.get(userId);
1255         }
1256
1257         public int size() {
1258             // total number of pending broadcast entries across all userIds
1259             int num = 0;
1260             for (int i = 0; i< mUidMap.size(); i++) {
1261                 num += mUidMap.valueAt(i).size();
1262             }
1263             return num;
1264         }
1265
1266         public void clear() {
1267             mUidMap.clear();
1268         }
1269
1270         private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1271             ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1272             if (map == null) {
1273                 map = new ArrayMap<String, ArrayList<String>>();
1274                 mUidMap.put(userId, map);
1275             }
1276             return map;
1277         }
1278     }
1279     final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1280
1281     // Service Connection to remote media container service to copy
1282     // package uri's from external media onto secure containers
1283     // or internal storage.
1284     private IMediaContainerService mContainerService = null;
1285
1286     static final int SEND_PENDING_BROADCAST = 1;
1287     static final int MCS_BOUND = 3;
1288     static final int END_COPY = 4;
1289     static final int INIT_COPY = 5;
1290     static final int MCS_UNBIND = 6;
1291     static final int START_CLEANING_PACKAGE = 7;
1292     static final int FIND_INSTALL_LOC = 8;
1293     static final int POST_INSTALL = 9;
1294     static final int MCS_RECONNECT = 10;
1295     static final int MCS_GIVE_UP = 11;
1296     static final int UPDATED_MEDIA_STATUS = 12;
1297     static final int WRITE_SETTINGS = 13;
1298     static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1299     static final int PACKAGE_VERIFIED = 15;
1300     static final int CHECK_PENDING_VERIFICATION = 16;
1301     static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1302     static final int INTENT_FILTER_VERIFIED = 18;
1303     static final int WRITE_PACKAGE_LIST = 19;
1304     static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1305
1306     static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1307
1308     // Delay time in millisecs
1309     static final int BROADCAST_DELAY = 10 * 1000;
1310
1311     private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1312             2 * 60 * 60 * 1000L; /* two hours */
1313
1314     static UserManagerService sUserManager;
1315
1316     // Stores a list of users whose package restrictions file needs to be updated
1317     private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1318
1319     final private DefaultContainerConnection mDefContainerConn =
1320             new DefaultContainerConnection();
1321     class DefaultContainerConnection implements ServiceConnection {
1322         public void onServiceConnected(ComponentName name, IBinder service) {
1323             if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1324             final IMediaContainerService imcs = IMediaContainerService.Stub
1325                     .asInterface(Binder.allowBlocking(service));
1326             mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1327         }
1328
1329         public void onServiceDisconnected(ComponentName name) {
1330             if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1331         }
1332     }
1333
1334     // Recordkeeping of restore-after-install operations that are currently in flight
1335     // between the Package Manager and the Backup Manager
1336     static class PostInstallData {
1337         public InstallArgs args;
1338         public PackageInstalledInfo res;
1339
1340         PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1341             args = _a;
1342             res = _r;
1343         }
1344     }
1345
1346     final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1347     int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1348
1349     // XML tags for backup/restore of various bits of state
1350     private static final String TAG_PREFERRED_BACKUP = "pa";
1351     private static final String TAG_DEFAULT_APPS = "da";
1352     private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1353
1354     private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1355     private static final String TAG_ALL_GRANTS = "rt-grants";
1356     private static final String TAG_GRANT = "grant";
1357     private static final String ATTR_PACKAGE_NAME = "pkg";
1358
1359     private static final String TAG_PERMISSION = "perm";
1360     private static final String ATTR_PERMISSION_NAME = "name";
1361     private static final String ATTR_IS_GRANTED = "g";
1362     private static final String ATTR_USER_SET = "set";
1363     private static final String ATTR_USER_FIXED = "fixed";
1364     private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1365
1366     // System/policy permission grants are not backed up
1367     private static final int SYSTEM_RUNTIME_GRANT_MASK =
1368             FLAG_PERMISSION_POLICY_FIXED
1369             | FLAG_PERMISSION_SYSTEM_FIXED
1370             | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1371
1372     // And we back up these user-adjusted states
1373     private static final int USER_RUNTIME_GRANT_MASK =
1374             FLAG_PERMISSION_USER_SET
1375             | FLAG_PERMISSION_USER_FIXED
1376             | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1377
1378     final @Nullable String mRequiredVerifierPackage;
1379     final @NonNull String mRequiredInstallerPackage;
1380     final @NonNull String mRequiredUninstallerPackage;
1381     final @Nullable String mSetupWizardPackage;
1382     final @Nullable String mStorageManagerPackage;
1383     final @NonNull String mServicesSystemSharedLibraryPackageName;
1384     final @NonNull String mSharedSystemSharedLibraryPackageName;
1385
1386     final boolean mPermissionReviewRequired;
1387
1388     private final PackageUsage mPackageUsage = new PackageUsage();
1389     private final CompilerStats mCompilerStats = new CompilerStats();
1390
1391     class PackageHandler extends Handler {
1392         private boolean mBound = false;
1393         final ArrayList<HandlerParams> mPendingInstalls =
1394             new ArrayList<HandlerParams>();
1395
1396         private boolean connectToService() {
1397             if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1398                     " DefaultContainerService");
1399             Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1400             Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1401             if (mContext.bindServiceAsUser(service, mDefContainerConn,
1402                     Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1403                 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1404                 mBound = true;
1405                 return true;
1406             }
1407             Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1408             return false;
1409         }
1410
1411         private void disconnectService() {
1412             mContainerService = null;
1413             mBound = false;
1414             Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1415             mContext.unbindService(mDefContainerConn);
1416             Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1417         }
1418
1419         PackageHandler(Looper looper) {
1420             super(looper);
1421         }
1422
1423         public void handleMessage(Message msg) {
1424             try {
1425                 doHandleMessage(msg);
1426             } finally {
1427                 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1428             }
1429         }
1430
1431         void doHandleMessage(Message msg) {
1432             switch (msg.what) {
1433                 case INIT_COPY: {
1434                     HandlerParams params = (HandlerParams) msg.obj;
1435                     int idx = mPendingInstalls.size();
1436                     if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1437                     // If a bind was already initiated we dont really
1438                     // need to do anything. The pending install
1439                     // will be processed later on.
1440                     if (!mBound) {
1441                         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1442                                 System.identityHashCode(mHandler));
1443                         // If this is the only one pending we might
1444                         // have to bind to the service again.
1445                         if (!connectToService()) {
1446                             Slog.e(TAG, "Failed to bind to media container service");
1447                             params.serviceError();
1448                             Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1449                                     System.identityHashCode(mHandler));
1450                             if (params.traceMethod != null) {
1451                                 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1452                                         params.traceCookie);
1453                             }
1454                             return;
1455                         } else {
1456                             // Once we bind to the service, the first
1457                             // pending request will be processed.
1458                             mPendingInstalls.add(idx, params);
1459                         }
1460                     } else {
1461                         mPendingInstalls.add(idx, params);
1462                         // Already bound to the service. Just make
1463                         // sure we trigger off processing the first request.
1464                         if (idx == 0) {
1465                             mHandler.sendEmptyMessage(MCS_BOUND);
1466                         }
1467                     }
1468                     break;
1469                 }
1470                 case MCS_BOUND: {
1471                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1472                     if (msg.obj != null) {
1473                         mContainerService = (IMediaContainerService) msg.obj;
1474                         Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1475                                 System.identityHashCode(mHandler));
1476                     }
1477                     if (mContainerService == null) {
1478                         if (!mBound) {
1479                             // Something seriously wrong since we are not bound and we are not
1480                             // waiting for connection. Bail out.
1481                             Slog.e(TAG, "Cannot bind to media container service");
1482                             for (HandlerParams params : mPendingInstalls) {
1483                                 // Indicate service bind error
1484                                 params.serviceError();
1485                                 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1486                                         System.identityHashCode(params));
1487                                 if (params.traceMethod != null) {
1488                                     Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1489                                             params.traceMethod, params.traceCookie);
1490                                 }
1491                                 return;
1492                             }
1493                             mPendingInstalls.clear();
1494                         } else {
1495                             Slog.w(TAG, "Waiting to connect to media container service");
1496                         }
1497                     } else if (mPendingInstalls.size() > 0) {
1498                         HandlerParams params = mPendingInstalls.get(0);
1499                         if (params != null) {
1500                             Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1501                                     System.identityHashCode(params));
1502                             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1503                             if (params.startCopy()) {
1504                                 // We are done...  look for more work or to
1505                                 // go idle.
1506                                 if (DEBUG_SD_INSTALL) Log.i(TAG,
1507                                         "Checking for more work or unbind...");
1508                                 // Delete pending install
1509                                 if (mPendingInstalls.size() > 0) {
1510                                     mPendingInstalls.remove(0);
1511                                 }
1512                                 if (mPendingInstalls.size() == 0) {
1513                                     if (mBound) {
1514                                         if (DEBUG_SD_INSTALL) Log.i(TAG,
1515                                                 "Posting delayed MCS_UNBIND");
1516                                         removeMessages(MCS_UNBIND);
1517                                         Message ubmsg = obtainMessage(MCS_UNBIND);
1518                                         // Unbind after a little delay, to avoid
1519                                         // continual thrashing.
1520                                         sendMessageDelayed(ubmsg, 10000);
1521                                     }
1522                                 } else {
1523                                     // There are more pending requests in queue.
1524                                     // Just post MCS_BOUND message to trigger processing
1525                                     // of next pending install.
1526                                     if (DEBUG_SD_INSTALL) Log.i(TAG,
1527                                             "Posting MCS_BOUND for next work");
1528                                     mHandler.sendEmptyMessage(MCS_BOUND);
1529                                 }
1530                             }
1531                             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1532                         }
1533                     } else {
1534                         // Should never happen ideally.
1535                         Slog.w(TAG, "Empty queue");
1536                     }
1537                     break;
1538                 }
1539                 case MCS_RECONNECT: {
1540                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1541                     if (mPendingInstalls.size() > 0) {
1542                         if (mBound) {
1543                             disconnectService();
1544                         }
1545                         if (!connectToService()) {
1546                             Slog.e(TAG, "Failed to bind to media container service");
1547                             for (HandlerParams params : mPendingInstalls) {
1548                                 // Indicate service bind error
1549                                 params.serviceError();
1550                                 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1551                                         System.identityHashCode(params));
1552                             }
1553                             mPendingInstalls.clear();
1554                         }
1555                     }
1556                     break;
1557                 }
1558                 case MCS_UNBIND: {
1559                     // If there is no actual work left, then time to unbind.
1560                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1561
1562                     if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1563                         if (mBound) {
1564                             if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1565
1566                             disconnectService();
1567                         }
1568                     } else if (mPendingInstalls.size() > 0) {
1569                         // There are more pending requests in queue.
1570                         // Just post MCS_BOUND message to trigger processing
1571                         // of next pending install.
1572                         mHandler.sendEmptyMessage(MCS_BOUND);
1573                     }
1574
1575                     break;
1576                 }
1577                 case MCS_GIVE_UP: {
1578                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1579                     HandlerParams params = mPendingInstalls.remove(0);
1580                     Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1581                             System.identityHashCode(params));
1582                     break;
1583                 }
1584                 case SEND_PENDING_BROADCAST: {
1585                     String packages[];
1586                     ArrayList<String> components[];
1587                     int size = 0;
1588                     int uids[];
1589                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1590                     synchronized (mPackages) {
1591                         if (mPendingBroadcasts == null) {
1592                             return;
1593                         }
1594                         size = mPendingBroadcasts.size();
1595                         if (size <= 0) {
1596                             // Nothing to be done. Just return
1597                             return;
1598                         }
1599                         packages = new String[size];
1600                         components = new ArrayList[size];
1601                         uids = new int[size];
1602                         int i = 0;  // filling out the above arrays
1603
1604                         for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1605                             int packageUserId = mPendingBroadcasts.userIdAt(n);
1606                             Iterator<Map.Entry<String, ArrayList<String>>> it
1607                                     = mPendingBroadcasts.packagesForUserId(packageUserId)
1608                                             .entrySet().iterator();
1609                             while (it.hasNext() && i < size) {
1610                                 Map.Entry<String, ArrayList<String>> ent = it.next();
1611                                 packages[i] = ent.getKey();
1612                                 components[i] = ent.getValue();
1613                                 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1614                                 uids[i] = (ps != null)
1615                                         ? UserHandle.getUid(packageUserId, ps.appId)
1616                                         : -1;
1617                                 i++;
1618                             }
1619                         }
1620                         size = i;
1621                         mPendingBroadcasts.clear();
1622                     }
1623                     // Send broadcasts
1624                     for (int i = 0; i < size; i++) {
1625                         sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1626                     }
1627                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1628                     break;
1629                 }
1630                 case START_CLEANING_PACKAGE: {
1631                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1632                     final String packageName = (String)msg.obj;
1633                     final int userId = msg.arg1;
1634                     final boolean andCode = msg.arg2 != 0;
1635                     synchronized (mPackages) {
1636                         if (userId == UserHandle.USER_ALL) {
1637                             int[] users = sUserManager.getUserIds();
1638                             for (int user : users) {
1639                                 mSettings.addPackageToCleanLPw(
1640                                         new PackageCleanItem(user, packageName, andCode));
1641                             }
1642                         } else {
1643                             mSettings.addPackageToCleanLPw(
1644                                     new PackageCleanItem(userId, packageName, andCode));
1645                         }
1646                     }
1647                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1648                     startCleaningPackages();
1649                 } break;
1650                 case POST_INSTALL: {
1651                     if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1652
1653                     PostInstallData data = mRunningInstalls.get(msg.arg1);
1654                     final boolean didRestore = (msg.arg2 != 0);
1655                     mRunningInstalls.delete(msg.arg1);
1656
1657                     if (data != null) {
1658                         InstallArgs args = data.args;
1659                         PackageInstalledInfo parentRes = data.res;
1660
1661                         final boolean grantPermissions = (args.installFlags
1662                                 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1663                         final boolean killApp = (args.installFlags
1664                                 & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1665                         final String[] grantedPermissions = args.installGrantPermissions;
1666
1667                         // Handle the parent package
1668                         handlePackagePostInstall(parentRes, grantPermissions, killApp,
1669                                 grantedPermissions, didRestore, args.installerPackageName,
1670                                 args.observer);
1671
1672                         // Handle the child packages
1673                         final int childCount = (parentRes.addedChildPackages != null)
1674                                 ? parentRes.addedChildPackages.size() : 0;
1675                         for (int i = 0; i < childCount; i++) {
1676                             PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1677                             handlePackagePostInstall(childRes, grantPermissions, killApp,
1678                                     grantedPermissions, false, args.installerPackageName,
1679                                     args.observer);
1680                         }
1681
1682                         // Log tracing if needed
1683                         if (args.traceMethod != null) {
1684                             Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1685                                     args.traceCookie);
1686                         }
1687                     } else {
1688                         Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1689                     }
1690
1691                     Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1692                 } break;
1693                 case UPDATED_MEDIA_STATUS: {
1694                     if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1695                     boolean reportStatus = msg.arg1 == 1;
1696                     boolean doGc = msg.arg2 == 1;
1697                     if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1698                     if (doGc) {
1699                         // Force a gc to clear up stale containers.
1700                         Runtime.getRuntime().gc();
1701                     }
1702                     if (msg.obj != null) {
1703                         @SuppressWarnings("unchecked")
1704                         Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1705                         if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1706                         // Unload containers
1707                         unloadAllContainers(args);
1708                     }
1709                     if (reportStatus) {
1710                         try {
1711                             if (DEBUG_SD_INSTALL) Log.i(TAG,
1712                                     "Invoking StorageManagerService call back");
1713                             PackageHelper.getStorageManager().finishMediaUpdate();
1714                         } catch (RemoteException e) {
1715                             Log.e(TAG, "StorageManagerService not running?");
1716                         }
1717                     }
1718                 } break;
1719                 case WRITE_SETTINGS: {
1720                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1721                     synchronized (mPackages) {
1722                         removeMessages(WRITE_SETTINGS);
1723                         removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1724                         mSettings.writeLPr();
1725                         mDirtyUsers.clear();
1726                     }
1727                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1728                 } break;
1729                 case WRITE_PACKAGE_RESTRICTIONS: {
1730                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1731                     synchronized (mPackages) {
1732                         removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1733                         for (int userId : mDirtyUsers) {
1734                             mSettings.writePackageRestrictionsLPr(userId);
1735                         }
1736                         mDirtyUsers.clear();
1737                     }
1738                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1739                 } break;
1740                 case WRITE_PACKAGE_LIST: {
1741                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1742                     synchronized (mPackages) {
1743                         removeMessages(WRITE_PACKAGE_LIST);
1744                         mSettings.writePackageListLPr(msg.arg1);
1745                     }
1746                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1747                 } break;
1748                 case CHECK_PENDING_VERIFICATION: {
1749                     final int verificationId = msg.arg1;
1750                     final PackageVerificationState state = mPendingVerification.get(verificationId);
1751
1752                     if ((state != null) && !state.timeoutExtended()) {
1753                         final InstallArgs args = state.getInstallArgs();
1754                         final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1755
1756                         Slog.i(TAG, "Verification timed out for " + originUri);
1757                         mPendingVerification.remove(verificationId);
1758
1759                         int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1760
1761                         final UserHandle user = args.getUser();
1762                         if (getDefaultVerificationResponse(user)
1763                                 == PackageManager.VERIFICATION_ALLOW) {
1764                             Slog.i(TAG, "Continuing with installation of " + originUri);
1765                             state.setVerifierResponse(Binder.getCallingUid(),
1766                                     PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1767                             broadcastPackageVerified(verificationId, originUri,
1768                                     PackageManager.VERIFICATION_ALLOW, user);
1769                             try {
1770                                 ret = args.copyApk(mContainerService, true);
1771                             } catch (RemoteException e) {
1772                                 Slog.e(TAG, "Could not contact the ContainerService");
1773                             }
1774                         } else {
1775                             broadcastPackageVerified(verificationId, originUri,
1776                                     PackageManager.VERIFICATION_REJECT, user);
1777                         }
1778
1779                         Trace.asyncTraceEnd(
1780                                 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1781
1782                         processPendingInstall(args, ret);
1783                         mHandler.sendEmptyMessage(MCS_UNBIND);
1784                     }
1785                     break;
1786                 }
1787                 case PACKAGE_VERIFIED: {
1788                     final int verificationId = msg.arg1;
1789
1790                     final PackageVerificationState state = mPendingVerification.get(verificationId);
1791                     if (state == null) {
1792                         Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1793                         break;
1794                     }
1795
1796                     final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1797
1798                     state.setVerifierResponse(response.callerUid, response.code);
1799
1800                     if (state.isVerificationComplete()) {
1801                         mPendingVerification.remove(verificationId);
1802
1803                         final InstallArgs args = state.getInstallArgs();
1804                         final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1805
1806                         int ret;
1807                         if (state.isInstallAllowed()) {
1808                             ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1809                             broadcastPackageVerified(verificationId, originUri,
1810                                     response.code, state.getInstallArgs().getUser());
1811                             try {
1812                                 ret = args.copyApk(mContainerService, true);
1813                             } catch (RemoteException e) {
1814                                 Slog.e(TAG, "Could not contact the ContainerService");
1815                             }
1816                         } else {
1817                             ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1818                         }
1819
1820                         Trace.asyncTraceEnd(
1821                                 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1822
1823                         processPendingInstall(args, ret);
1824                         mHandler.sendEmptyMessage(MCS_UNBIND);
1825                     }
1826
1827                     break;
1828                 }
1829                 case START_INTENT_FILTER_VERIFICATIONS: {
1830                     IFVerificationParams params = (IFVerificationParams) msg.obj;
1831                     verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1832                             params.replacing, params.pkg);
1833                     break;
1834                 }
1835                 case INTENT_FILTER_VERIFIED: {
1836                     final int verificationId = msg.arg1;
1837
1838                     final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1839                             verificationId);
1840                     if (state == null) {
1841                         Slog.w(TAG, "Invalid IntentFilter verification token "
1842                                 + verificationId + " received");
1843                         break;
1844                     }
1845
1846                     final int userId = state.getUserId();
1847
1848                     if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1849                             "Processing IntentFilter verification with token:"
1850                             + verificationId + " and userId:" + userId);
1851
1852                     final IntentFilterVerificationResponse response =
1853                             (IntentFilterVerificationResponse) msg.obj;
1854
1855                     state.setVerifierResponse(response.callerUid, response.code);
1856
1857                     if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1858                             "IntentFilter verification with token:" + verificationId
1859                             + " and userId:" + userId
1860                             + " is settings verifier response with response code:"
1861                             + response.code);
1862
1863                     if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1864                         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1865                                 + response.getFailedDomainsString());
1866                     }
1867
1868                     if (state.isVerificationComplete()) {
1869                         mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1870                     } else {
1871                         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1872                                 "IntentFilter verification with token:" + verificationId
1873                                 + " was not said to be complete");
1874                     }
1875
1876                     break;
1877                 }
1878                 case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1879                     InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1880                             mInstantAppResolverConnection,
1881                             (InstantAppRequest) msg.obj,
1882                             mInstantAppInstallerActivity,
1883                             mHandler);
1884                 }
1885             }
1886         }
1887     }
1888
1889     private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1890             boolean killApp, String[] grantedPermissions,
1891             boolean launchedForRestore, String installerPackage,
1892             IPackageInstallObserver2 installObserver) {
1893         if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1894             // Send the removed broadcasts
1895             if (res.removedInfo != null) {
1896                 res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1897             }
1898
1899             // Now that we successfully installed the package, grant runtime
1900             // permissions if requested before broadcasting the install. Also
1901             // for legacy apps in permission review mode we clear the permission
1902             // review flag which is used to emulate runtime permissions for
1903             // legacy apps.
1904             if (grantPermissions) {
1905                 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1906             }
1907
1908             final boolean update = res.removedInfo != null
1909                     && res.removedInfo.removedPackage != null;
1910             final String origInstallerPackageName = res.removedInfo != null
1911                     ? res.removedInfo.installerPackageName : null;
1912
1913             // If this is the first time we have child packages for a disabled privileged
1914             // app that had no children, we grant requested runtime permissions to the new
1915             // children if the parent on the system image had them already granted.
1916             if (res.pkg.parentPackage != null) {
1917                 synchronized (mPackages) {
1918                     grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1919                 }
1920             }
1921
1922             synchronized (mPackages) {
1923                 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1924             }
1925
1926             final String packageName = res.pkg.applicationInfo.packageName;
1927
1928             // Determine the set of users who are adding this package for
1929             // the first time vs. those who are seeing an update.
1930             int[] firstUsers = EMPTY_INT_ARRAY;
1931             int[] updateUsers = EMPTY_INT_ARRAY;
1932             final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1933             final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1934             for (int newUser : res.newUsers) {
1935                 if (ps.getInstantApp(newUser)) {
1936                     continue;
1937                 }
1938                 if (allNewUsers) {
1939                     firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1940                     continue;
1941                 }
1942                 boolean isNew = true;
1943                 for (int origUser : res.origUsers) {
1944                     if (origUser == newUser) {
1945                         isNew = false;
1946                         break;
1947                     }
1948                 }
1949                 if (isNew) {
1950                     firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1951                 } else {
1952                     updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1953                 }
1954             }
1955
1956             // Send installed broadcasts if the package is not a static shared lib.
1957             if (res.pkg.staticSharedLibName == null) {
1958                 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1959
1960                 // Send added for users that see the package for the first time
1961                 // sendPackageAddedForNewUsers also deals with system apps
1962                 int appId = UserHandle.getAppId(res.uid);
1963                 boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1964                 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1965
1966                 // Send added for users that don't see the package for the first time
1967                 Bundle extras = new Bundle(1);
1968                 extras.putInt(Intent.EXTRA_UID, res.uid);
1969                 if (update) {
1970                     extras.putBoolean(Intent.EXTRA_REPLACING, true);
1971                 }
1972                 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1973                         extras, 0 /*flags*/,
1974                         null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1975                 if (origInstallerPackageName != null) {
1976                     sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1977                             extras, 0 /*flags*/,
1978                             origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1979                 }
1980
1981                 // Send replaced for users that don't see the package for the first time
1982                 if (update) {
1983                     sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1984                             packageName, extras, 0 /*flags*/,
1985                             null /*targetPackage*/, null /*finishedReceiver*/,
1986                             updateUsers);
1987                     if (origInstallerPackageName != null) {
1988                         sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1989                                 extras, 0 /*flags*/,
1990                                 origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1991                     }
1992                     sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1993                             null /*package*/, null /*extras*/, 0 /*flags*/,
1994                             packageName /*targetPackage*/,
1995                             null /*finishedReceiver*/, updateUsers);
1996                 } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1997                     // First-install and we did a restore, so we're responsible for the
1998                     // first-launch broadcast.
1999                     if (DEBUG_BACKUP) {
2000                         Slog.i(TAG, "Post-restore of " + packageName
2001                                 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2002                     }
2003                     sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2004                 }
2005
2006                 // Send broadcast package appeared if forward locked/external for all users
2007                 // treat asec-hosted packages like removable media on upgrade
2008                 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2009                     if (DEBUG_INSTALL) {
2010                         Slog.i(TAG, "upgrading pkg " + res.pkg
2011                                 + " is ASEC-hosted -> AVAILABLE");
2012                     }
2013                     final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2014                     ArrayList<String> pkgList = new ArrayList<>(1);
2015                     pkgList.add(packageName);
2016                     sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2017                 }
2018             }
2019
2020             // Work that needs to happen on first install within each user
2021             if (firstUsers != null && firstUsers.length > 0) {
2022                 synchronized (mPackages) {
2023                     for (int userId : firstUsers) {
2024                         // If this app is a browser and it's newly-installed for some
2025                         // users, clear any default-browser state in those users. The
2026                         // app's nature doesn't depend on the user, so we can just check
2027                         // its browser nature in any user and generalize.
2028                         if (packageIsBrowser(packageName, userId)) {
2029                             mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2030                         }
2031
2032                         // We may also need to apply pending (restored) runtime
2033                         // permission grants within these users.
2034                         mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2035                     }
2036                 }
2037             }
2038
2039             // Log current value of "unknown sources" setting
2040             EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2041                     getUnknownSourcesSettings());
2042
2043             // Remove the replaced package's older resources safely now
2044             // We delete after a gc for applications  on sdcard.
2045             if (res.removedInfo != null && res.removedInfo.args != null) {
2046                 Runtime.getRuntime().gc();
2047                 synchronized (mInstallLock) {
2048                     res.removedInfo.args.doPostDeleteLI(true);
2049                 }
2050             } else {
2051                 // Force a gc to clear up things. Ask for a background one, it's fine to go on
2052                 // and not block here.
2053                 VMRuntime.getRuntime().requestConcurrentGC();
2054             }
2055
2056             // Notify DexManager that the package was installed for new users.
2057             // The updated users should already be indexed and the package code paths
2058             // should not change.
2059             // Don't notify the manager for ephemeral apps as they are not expected to
2060             // survive long enough to benefit of background optimizations.
2061             for (int userId : firstUsers) {
2062                 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2063                 // There's a race currently where some install events may interleave with an uninstall.
2064                 // This can lead to package info being null (b/36642664).
2065                 if (info != null) {
2066                     mDexManager.notifyPackageInstalled(info, userId);
2067                 }
2068             }
2069         }
2070
2071         // If someone is watching installs - notify them
2072         if (installObserver != null) {
2073             try {
2074                 Bundle extras = extrasForInstallResult(res);
2075                 installObserver.onPackageInstalled(res.name, res.returnCode,
2076                         res.returnMsg, extras);
2077             } catch (RemoteException e) {
2078                 Slog.i(TAG, "Observer no longer exists.");
2079             }
2080         }
2081     }
2082
2083     private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2084             PackageParser.Package pkg) {
2085         if (pkg.parentPackage == null) {
2086             return;
2087         }
2088         if (pkg.requestedPermissions == null) {
2089             return;
2090         }
2091         final PackageSetting disabledSysParentPs = mSettings
2092                 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2093         if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2094                 || !disabledSysParentPs.isPrivileged()
2095                 || (disabledSysParentPs.childPackageNames != null
2096                         && !disabledSysParentPs.childPackageNames.isEmpty())) {
2097             return;
2098         }
2099         final int[] allUserIds = sUserManager.getUserIds();
2100         final int permCount = pkg.requestedPermissions.size();
2101         for (int i = 0; i < permCount; i++) {
2102             String permission = pkg.requestedPermissions.get(i);
2103             BasePermission bp = mSettings.mPermissions.get(permission);
2104             if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2105                 continue;
2106             }
2107             for (int userId : allUserIds) {
2108                 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2109                         permission, userId)) {
2110                     grantRuntimePermission(pkg.packageName, permission, userId);
2111                 }
2112             }
2113         }
2114     }
2115
2116     private StorageEventListener mStorageListener = new StorageEventListener() {
2117         @Override
2118         public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2119             if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2120                 if (vol.state == VolumeInfo.STATE_MOUNTED) {
2121                     final String volumeUuid = vol.getFsUuid();
2122
2123                     // Clean up any users or apps that were removed or recreated
2124                     // while this volume was missing
2125                     sUserManager.reconcileUsers(volumeUuid);
2126                     reconcileApps(volumeUuid);
2127
2128                     // Clean up any install sessions that expired or were
2129                     // cancelled while this volume was missing
2130                     mInstallerService.onPrivateVolumeMounted(volumeUuid);
2131
2132                     loadPrivatePackages(vol);
2133
2134                 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2135                     unloadPrivatePackages(vol);
2136                 }
2137             }
2138
2139             if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2140                 if (vol.state == VolumeInfo.STATE_MOUNTED) {
2141                     updateExternalMediaStatus(true, false);
2142                 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2143                     updateExternalMediaStatus(false, false);
2144                 }
2145             }
2146         }
2147
2148         @Override
2149         public void onVolumeForgotten(String fsUuid) {
2150             if (TextUtils.isEmpty(fsUuid)) {
2151                 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2152                 return;
2153             }
2154
2155             // Remove any apps installed on the forgotten volume
2156             synchronized (mPackages) {
2157                 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2158                 for (PackageSetting ps : packages) {
2159                     Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2160                     deletePackageVersioned(new VersionedPackage(ps.name,
2161                             PackageManager.VERSION_CODE_HIGHEST),
2162                             new LegacyPackageDeleteObserver(null).getBinder(),
2163                             UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2164                     // Try very hard to release any references to this package
2165                     // so we don't risk the system server being killed due to
2166                     // open FDs
2167                     AttributeCache.instance().removePackage(ps.name);
2168                 }
2169
2170                 mSettings.onVolumeForgotten(fsUuid);
2171                 mSettings.writeLPr();
2172             }
2173         }
2174     };
2175
2176     private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2177             String[] grantedPermissions) {
2178         for (int userId : userIds) {
2179             grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2180         }
2181     }
2182
2183     private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2184             String[] grantedPermissions) {
2185         PackageSetting ps = (PackageSetting) pkg.mExtras;
2186         if (ps == null) {
2187             return;
2188         }
2189
2190         PermissionsState permissionsState = ps.getPermissionsState();
2191
2192         final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2193                 | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2194
2195         final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2196                 >= Build.VERSION_CODES.M;
2197
2198         final boolean instantApp = isInstantApp(pkg.packageName, userId);
2199
2200         for (String permission : pkg.requestedPermissions) {
2201             final BasePermission bp;
2202             synchronized (mPackages) {
2203                 bp = mSettings.mPermissions.get(permission);
2204             }
2205             if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2206                     && (!instantApp || bp.isInstant())
2207                     && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2208                     && (grantedPermissions == null
2209                            || ArrayUtils.contains(grantedPermissions, permission))) {
2210                 final int flags = permissionsState.getPermissionFlags(permission, userId);
2211                 if (supportsRuntimePermissions) {
2212                     // Installer cannot change immutable permissions.
2213                     if ((flags & immutableFlags) == 0) {
2214                         grantRuntimePermission(pkg.packageName, permission, userId);
2215                     }
2216                 } else if (mPermissionReviewRequired) {
2217                     // In permission review mode we clear the review flag when we
2218                     // are asked to install the app with all permissions granted.
2219                     if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2220                         updatePermissionFlags(permission, pkg.packageName,
2221                                 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2222                     }
2223                 }
2224             }
2225         }
2226     }
2227
2228     Bundle extrasForInstallResult(PackageInstalledInfo res) {
2229         Bundle extras = null;
2230         switch (res.returnCode) {
2231             case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2232                 extras = new Bundle();
2233                 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2234                         res.origPermission);
2235                 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2236                         res.origPackage);
2237                 break;
2238             }
2239             case PackageManager.INSTALL_SUCCEEDED: {
2240                 extras = new Bundle();
2241                 extras.putBoolean(Intent.EXTRA_REPLACING,
2242                         res.removedInfo != null && res.removedInfo.removedPackage != null);
2243                 break;
2244             }
2245         }
2246         return extras;
2247     }
2248
2249     void scheduleWriteSettingsLocked() {
2250         if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2251             mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2252         }
2253     }
2254
2255     void scheduleWritePackageListLocked(int userId) {
2256         if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2257             Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2258             msg.arg1 = userId;
2259             mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2260         }
2261     }
2262
2263     void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2264         final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2265         scheduleWritePackageRestrictionsLocked(userId);
2266     }
2267
2268     void scheduleWritePackageRestrictionsLocked(int userId) {
2269         final int[] userIds = (userId == UserHandle.USER_ALL)
2270                 ? sUserManager.getUserIds() : new int[]{userId};
2271         for (int nextUserId : userIds) {
2272             if (!sUserManager.exists(nextUserId)) return;
2273             mDirtyUsers.add(nextUserId);
2274             if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2275                 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2276             }
2277         }
2278     }
2279
2280     public static PackageManagerService main(Context context, Installer installer,
2281             boolean factoryTest, boolean onlyCore) {
2282         // Self-check for initial settings.
2283         PackageManagerServiceCompilerMapping.checkProperties();
2284
2285         PackageManagerService m = new PackageManagerService(context, installer,
2286                 factoryTest, onlyCore);
2287         m.enableSystemUserPackages();
2288         ServiceManager.addService("package", m);
2289         return m;
2290     }
2291
2292     private void enableSystemUserPackages() {
2293         if (!UserManager.isSplitSystemUser()) {
2294             return;
2295         }
2296         // For system user, enable apps based on the following conditions:
2297         // - app is whitelisted or belong to one of these groups:
2298         //   -- system app which has no launcher icons
2299         //   -- system app which has INTERACT_ACROSS_USERS permission
2300         //   -- system IME app
2301         // - app is not in the blacklist
2302         AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2303         Set<String> enableApps = new ArraySet<>();
2304         enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2305                 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2306                 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2307         ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2308         enableApps.addAll(wlApps);
2309         enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2310                 /* systemAppsOnly */ false, UserHandle.SYSTEM));
2311         ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2312         enableApps.removeAll(blApps);
2313         Log.i(TAG, "Applications installed for system user: " + enableApps);
2314         List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2315                 UserHandle.SYSTEM);
2316         final int allAppsSize = allAps.size();
2317         synchronized (mPackages) {
2318             for (int i = 0; i < allAppsSize; i++) {
2319                 String pName = allAps.get(i);
2320                 PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2321                 // Should not happen, but we shouldn't be failing if it does
2322                 if (pkgSetting == null) {
2323                     continue;
2324                 }
2325                 boolean install = enableApps.contains(pName);
2326                 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2327                     Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2328                             + " for system user");
2329                     pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2330                 }
2331             }
2332             scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2333         }
2334     }
2335
2336     private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2337         DisplayManager displayManager = (DisplayManager) context.getSystemService(
2338                 Context.DISPLAY_SERVICE);
2339         displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2340     }
2341
2342     /**
2343      * Requests that files preopted on a secondary system partition be copied to the data partition
2344      * if possible.  Note that the actual copying of the files is accomplished by init for security
2345      * reasons. This simply requests that the copy takes place and awaits confirmation of its
2346      * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2347      */
2348     private static void requestCopyPreoptedFiles() {
2349         final int WAIT_TIME_MS = 100;
2350         final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2351         if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2352             SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2353             // We will wait for up to 100 seconds.
2354             final long timeStart = SystemClock.uptimeMillis();
2355             final long timeEnd = timeStart + 100 * 1000;
2356             long timeNow = timeStart;
2357             while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2358                 try {
2359                     Thread.sleep(WAIT_TIME_MS);
2360                 } catch (InterruptedException e) {
2361                     // Do nothing
2362                 }
2363                 timeNow = SystemClock.uptimeMillis();
2364                 if (timeNow > timeEnd) {
2365                     SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2366                     Slog.wtf(TAG, "cppreopt did not finish!");
2367                     break;
2368                 }
2369             }
2370
2371             Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2372         }
2373     }
2374
2375     public PackageManagerService(Context context, Installer installer,
2376             boolean factoryTest, boolean onlyCore) {
2377         LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2378         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2379         EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2380                 SystemClock.uptimeMillis());
2381
2382         if (mSdkVersion <= 0) {
2383             Slog.w(TAG, "**** ro.build.version.sdk not set!");
2384         }
2385
2386         mContext = context;
2387
2388         mPermissionReviewRequired = context.getResources().getBoolean(
2389                 R.bool.config_permissionReviewRequired);
2390
2391         mFactoryTest = factoryTest;
2392         mOnlyCore = onlyCore;
2393         mMetrics = new DisplayMetrics();
2394         mSettings = new Settings(mPackages);
2395         mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2396                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2397         mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2398                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2399         mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2400                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2401         mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2402                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2403         mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2404                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2405         mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2406                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2407
2408         String separateProcesses = SystemProperties.get("debug.separate_processes");
2409         if (separateProcesses != null && separateProcesses.length() > 0) {
2410             if ("*".equals(separateProcesses)) {
2411                 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2412                 mSeparateProcesses = null;
2413                 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2414             } else {
2415                 mDefParseFlags = 0;
2416                 mSeparateProcesses = separateProcesses.split(",");
2417                 Slog.w(TAG, "Running with debug.separate_processes: "
2418                         + separateProcesses);
2419             }
2420         } else {
2421             mDefParseFlags = 0;
2422             mSeparateProcesses = null;
2423         }
2424
2425         mInstaller = installer;
2426         mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2427                 "*dexopt*");
2428         mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2429         mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2430
2431         mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2432                 FgThread.get().getLooper());
2433
2434         getDefaultDisplayMetrics(context, mMetrics);
2435
2436         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2437         SystemConfig systemConfig = SystemConfig.getInstance();
2438         mGlobalGids = systemConfig.getGlobalGids();
2439         mSystemPermissions = systemConfig.getSystemPermissions();
2440         mAvailableFeatures = systemConfig.getAvailableFeatures();
2441         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2442
2443         mProtectedPackages = new ProtectedPackages(mContext);
2444
2445         synchronized (mInstallLock) {
2446         // writer
2447         synchronized (mPackages) {
2448             mHandlerThread = new ServiceThread(TAG,
2449                     Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2450             mHandlerThread.start();
2451             mHandler = new PackageHandler(mHandlerThread.getLooper());
2452             mProcessLoggingHandler = new ProcessLoggingHandler();
2453             Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2454
2455             mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2456             mInstantAppRegistry = new InstantAppRegistry(this);
2457
2458             File dataDir = Environment.getDataDirectory();
2459             mAppInstallDir = new File(dataDir, "app");
2460             mAppLib32InstallDir = new File(dataDir, "app-lib");
2461             mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2462             mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2463             sUserManager = new UserManagerService(context, this,
2464                     new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2465
2466             // Propagate permission configuration in to package manager.
2467             ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2468                     = systemConfig.getPermissions();
2469             for (int i=0; i<permConfig.size(); i++) {
2470                 SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2471                 BasePermission bp = mSettings.mPermissions.get(perm.name);
2472                 if (bp == null) {
2473                     bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2474                     mSettings.mPermissions.put(perm.name, bp);
2475                 }
2476                 if (perm.gids != null) {
2477                     bp.setGids(perm.gids, perm.perUser);
2478                 }
2479             }
2480
2481             ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2482             final int builtInLibCount = libConfig.size();
2483             for (int i = 0; i < builtInLibCount; i++) {
2484                 String name = libConfig.keyAt(i);
2485                 String path = libConfig.valueAt(i);
2486                 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2487                         SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2488             }
2489
2490             mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2491
2492             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2493             mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2494             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2495
2496             // Clean up orphaned packages for which the code path doesn't exist
2497             // and they are an update to a system app - caused by bug/32321269
2498             final int packageSettingCount = mSettings.mPackages.size();
2499             for (int i = packageSettingCount - 1; i >= 0; i--) {
2500                 PackageSetting ps = mSettings.mPackages.valueAt(i);
2501                 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2502                         && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2503                     mSettings.mPackages.removeAt(i);
2504                     mSettings.enableSystemPackageLPw(ps.name);
2505                 }
2506             }
2507
2508             if (mFirstBoot) {
2509                 requestCopyPreoptedFiles();
2510             }
2511
2512             String customResolverActivity = Resources.getSystem().getString(
2513                     R.string.config_customResolverActivity);
2514             if (TextUtils.isEmpty(customResolverActivity)) {
2515                 customResolverActivity = null;
2516             } else {
2517                 mCustomResolverComponentName = ComponentName.unflattenFromString(
2518                         customResolverActivity);
2519             }
2520
2521             long startTime = SystemClock.uptimeMillis();
2522
2523             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2524                     startTime);
2525
2526             final String bootClassPath = System.getenv("BOOTCLASSPATH");
2527             final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2528
2529             if (bootClassPath == null) {
2530                 Slog.w(TAG, "No BOOTCLASSPATH found!");
2531             }
2532
2533             if (systemServerClassPath == null) {
2534                 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2535             }
2536
2537             File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2538
2539             final VersionInfo ver = mSettings.getInternalVersion();
2540             mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2541             if (mIsUpgrade) {
2542                 logCriticalInfo(Log.INFO,
2543                         "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2544             }
2545
2546             // when upgrading from pre-M, promote system app permissions from install to runtime
2547             mPromoteSystemApps =
2548                     mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2549
2550             // When upgrading from pre-N, we need to handle package extraction like first boot,
2551             // as there is no profiling data available.
2552             mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2553
2554             mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2555
2556             // save off the names of pre-existing system packages prior to scanning; we don't
2557             // want to automatically grant runtime permissions for new system apps
2558             if (mPromoteSystemApps) {
2559                 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2560                 while (pkgSettingIter.hasNext()) {
2561                     PackageSetting ps = pkgSettingIter.next();
2562                     if (isSystemApp(ps)) {
2563                         mExistingSystemPackages.add(ps.name);
2564                     }
2565                 }
2566             }
2567
2568             mCacheDir = preparePackageParserCache(mIsUpgrade);
2569
2570             // Set flag to monitor and not change apk file paths when
2571             // scanning install directories.
2572             int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2573
2574             if (mIsUpgrade || mFirstBoot) {
2575                 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2576             }
2577
2578             // Collect vendor overlay packages. (Do this before scanning any apps.)
2579             // For security and version matching reason, only consider
2580             // overlay packages if they reside in the right directory.
2581             scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2582                     | PackageParser.PARSE_IS_SYSTEM
2583                     | PackageParser.PARSE_IS_SYSTEM_DIR
2584                     | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2585
2586             mParallelPackageParserCallback.findStaticOverlayPackages();
2587
2588             // Find base frameworks (resource packages without code).
2589             scanDirTracedLI(frameworkDir, mDefParseFlags
2590                     | PackageParser.PARSE_IS_SYSTEM
2591                     | PackageParser.PARSE_IS_SYSTEM_DIR
2592                     | PackageParser.PARSE_IS_PRIVILEGED,
2593                     scanFlags | SCAN_NO_DEX, 0);
2594
2595             // Collected privileged system packages.
2596             final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2597             scanDirTracedLI(privilegedAppDir, mDefParseFlags
2598                     | PackageParser.PARSE_IS_SYSTEM
2599                     | PackageParser.PARSE_IS_SYSTEM_DIR
2600                     | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2601
2602             // Collect ordinary system packages.
2603             final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2604             scanDirTracedLI(systemAppDir, mDefParseFlags
2605                     | PackageParser.PARSE_IS_SYSTEM
2606                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2607
2608             // Collect all vendor packages.
2609             File vendorAppDir = new File("/vendor/app");
2610             try {
2611                 vendorAppDir = vendorAppDir.getCanonicalFile();
2612             } catch (IOException e) {
2613                 // failed to look up canonical path, continue with original one
2614             }
2615             scanDirTracedLI(vendorAppDir, mDefParseFlags
2616                     | PackageParser.PARSE_IS_SYSTEM
2617                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2618
2619             // Collect all OEM packages.
2620             final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2621             scanDirTracedLI(oemAppDir, mDefParseFlags
2622                     | PackageParser.PARSE_IS_SYSTEM
2623                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2624
2625             // Prune any system packages that no longer exist.
2626             final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2627             if (!mOnlyCore) {
2628                 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2629                 while (psit.hasNext()) {
2630                     PackageSetting ps = psit.next();
2631
2632                     /*
2633                      * If this is not a system app, it can't be a
2634                      * disable system app.
2635                      */
2636                     if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2637                         continue;
2638                     }
2639
2640                     /*
2641                      * If the package is scanned, it's not erased.
2642                      */
2643                     final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2644                     if (scannedPkg != null) {
2645                         /*
2646                          * If the system app is both scanned and in the
2647                          * disabled packages list, then it must have been
2648                          * added via OTA. Remove it from the currently
2649                          * scanned package so the previously user-installed
2650                          * application can be scanned.
2651                          */
2652                         if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2653                             logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2654                                     + ps.name + "; removing system app.  Last known codePath="
2655                                     + ps.codePathString + ", installStatus=" + ps.installStatus
2656                                     + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2657                                     + scannedPkg.mVersionCode);
2658                             removePackageLI(scannedPkg, true);
2659                             mExpectingBetter.put(ps.name, ps.codePath);
2660                         }
2661
2662                         continue;
2663                     }
2664
2665                     if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2666                         psit.remove();
2667                         logCriticalInfo(Log.WARN, "System package " + ps.name
2668                                 + " no longer exists; it's data will be wiped");
2669                         // Actual deletion of code and data will be handled by later
2670                         // reconciliation step
2671                     } else {
2672                         final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2673                         if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2674                             possiblyDeletedUpdatedSystemApps.add(ps.name);
2675                         }
2676                     }
2677                 }
2678             }
2679
2680             //look for any incomplete package installations
2681             ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2682             for (int i = 0; i < deletePkgsList.size(); i++) {
2683                 // Actual deletion of code and data will be handled by later
2684                 // reconciliation step
2685                 final String packageName = deletePkgsList.get(i).name;
2686                 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2687                 synchronized (mPackages) {
2688                     mSettings.removePackageLPw(packageName);
2689                 }
2690             }
2691
2692             //delete tmp files
2693             deleteTempPackageFiles();
2694
2695             // Remove any shared userIDs that have no associated packages
2696             mSettings.pruneSharedUsersLPw();
2697
2698             if (!mOnlyCore) {
2699                 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2700                         SystemClock.uptimeMillis());
2701                 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2702
2703                 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2704                         | PackageParser.PARSE_FORWARD_LOCK,
2705                         scanFlags | SCAN_REQUIRE_KNOWN, 0);
2706
2707                 /**
2708                  * Remove disable package settings for any updated system
2709                  * apps that were removed via an OTA. If they're not a
2710                  * previously-updated app, remove them completely.
2711                  * Otherwise, just revoke their system-level permissions.
2712                  */
2713                 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2714                     PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2715                     mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2716
2717                     String msg;
2718                     if (deletedPkg == null) {
2719                         msg = "Updated system package " + deletedAppName
2720                                 + " no longer exists; it's data will be wiped";
2721                         // Actual deletion of code and data will be handled by later
2722                         // reconciliation step
2723                     } else {
2724                         msg = "Updated system app + " + deletedAppName
2725                                 + " no longer present; removing system privileges for "
2726                                 + deletedAppName;
2727
2728                         deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2729
2730                         PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2731                         deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2732                     }
2733                     logCriticalInfo(Log.WARN, msg);
2734                 }
2735
2736                 /**
2737                  * Make sure all system apps that we expected to appear on
2738                  * the userdata partition actually showed up. If they never
2739                  * appeared, crawl back and revive the system version.
2740                  */
2741                 for (int i = 0; i < mExpectingBetter.size(); i++) {
2742                     final String packageName = mExpectingBetter.keyAt(i);
2743                     if (!mPackages.containsKey(packageName)) {
2744                         final File scanFile = mExpectingBetter.valueAt(i);
2745
2746                         logCriticalInfo(Log.WARN, "Expected better " + packageName
2747                                 + " but never showed up; reverting to system");
2748
2749                         int reparseFlags = mDefParseFlags;
2750                         if (FileUtils.contains(privilegedAppDir, scanFile)) {
2751                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2752                                     | PackageParser.PARSE_IS_SYSTEM_DIR
2753                                     | PackageParser.PARSE_IS_PRIVILEGED;
2754                         } else if (FileUtils.contains(systemAppDir, scanFile)) {
2755                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2756                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
2757                         } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2758                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2759                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
2760                         } else if (FileUtils.contains(oemAppDir, scanFile)) {
2761                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2762                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
2763                         } else {
2764                             Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2765                             continue;
2766                         }
2767
2768                         mSettings.enableSystemPackageLPw(packageName);
2769
2770                         try {
2771                             scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2772                         } catch (PackageManagerException e) {
2773                             Slog.e(TAG, "Failed to parse original system package: "
2774                                     + e.getMessage());
2775                         }
2776                     }
2777                 }
2778             }
2779             mExpectingBetter.clear();
2780
2781             // Resolve the storage manager.
2782             mStorageManagerPackage = getStorageManagerPackageName();
2783
2784             // Resolve protected action filters. Only the setup wizard is allowed to
2785             // have a high priority filter for these actions.
2786             mSetupWizardPackage = getSetupWizardPackageName();
2787             if (mProtectedFilters.size() > 0) {
2788                 if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2789                     Slog.i(TAG, "No setup wizard;"
2790                         + " All protected intents capped to priority 0");
2791                 }
2792                 for (ActivityIntentInfo filter : mProtectedFilters) {
2793                     if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2794                         if (DEBUG_FILTERS) {
2795                             Slog.i(TAG, "Found setup wizard;"
2796                                 + " allow priority " + filter.getPriority() + ";"
2797                                 + " package: " + filter.activity.info.packageName
2798                                 + " activity: " + filter.activity.className
2799                                 + " priority: " + filter.getPriority());
2800                         }
2801                         // skip setup wizard; allow it to keep the high priority filter
2802                         continue;
2803                     }
2804                     if (DEBUG_FILTERS) {
2805                         Slog.i(TAG, "Protected action; cap priority to 0;"
2806                                 + " package: " + filter.activity.info.packageName
2807                                 + " activity: " + filter.activity.className
2808                                 + " origPrio: " + filter.getPriority());
2809                     }
2810                     filter.setPriority(0);
2811                 }
2812             }
2813             mDeferProtectedFilters = false;
2814             mProtectedFilters.clear();
2815
2816             // Now that we know all of the shared libraries, update all clients to have
2817             // the correct library paths.
2818             updateAllSharedLibrariesLPw(null);
2819
2820             for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2821                 // NOTE: We ignore potential failures here during a system scan (like
2822                 // the rest of the commands above) because there's precious little we
2823                 // can do about it. A settings error is reported, though.
2824                 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2825             }
2826
2827             // Now that we know all the packages we are keeping,
2828             // read and update their last usage times.
2829             mPackageUsage.read(mPackages);
2830             mCompilerStats.read();
2831
2832             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2833                     SystemClock.uptimeMillis());
2834             Slog.i(TAG, "Time to scan packages: "
2835                     + ((SystemClock.uptimeMillis()-startTime)/1000f)
2836                     + " seconds");
2837
2838             // If the platform SDK has changed since the last time we booted,
2839             // we need to re-grant app permission to catch any new ones that
2840             // appear.  This is really a hack, and means that apps can in some
2841             // cases get permissions that the user didn't initially explicitly
2842             // allow...  it would be nice to have some better way to handle
2843             // this situation.
2844             int updateFlags = UPDATE_PERMISSIONS_ALL;
2845             if (ver.sdkVersion != mSdkVersion) {
2846                 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2847                         + mSdkVersion + "; regranting permissions for internal storage");
2848                 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2849             }
2850             updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2851             ver.sdkVersion = mSdkVersion;
2852
2853             // If this is the first boot or an update from pre-M, and it is a normal
2854             // boot, then we need to initialize the default preferred apps across
2855             // all defined users.
2856             if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2857                 for (UserInfo user : sUserManager.getUsers(true)) {
2858                     mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2859                     applyFactoryDefaultBrowserLPw(user.id);
2860                     primeDomainVerificationsLPw(user.id);
2861                 }
2862             }
2863
2864             // Prepare storage for system user really early during boot,
2865             // since core system apps like SettingsProvider and SystemUI
2866             // can't wait for user to start
2867             final int storageFlags;
2868             if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2869                 storageFlags = StorageManager.FLAG_STORAGE_DE;
2870             } else {
2871                 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2872             }
2873             List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2874                     UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2875                     true /* onlyCoreApps */);
2876             mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2877                 BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2878                         Trace.TRACE_TAG_PACKAGE_MANAGER);
2879                 traceLog.traceBegin("AppDataFixup");
2880                 try {
2881                     mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2882                             StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2883                 } catch (InstallerException e) {
2884                     Slog.w(TAG, "Trouble fixing GIDs", e);
2885                 }
2886                 traceLog.traceEnd();
2887
2888                 traceLog.traceBegin("AppDataPrepare");
2889                 if (deferPackages == null || deferPackages.isEmpty()) {
2890                     return;
2891                 }
2892                 int count = 0;
2893                 for (String pkgName : deferPackages) {
2894                     PackageParser.Package pkg = null;
2895                     synchronized (mPackages) {
2896                         PackageSetting ps = mSettings.getPackageLPr(pkgName);
2897                         if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2898                             pkg = ps.pkg;
2899                         }
2900                     }
2901                     if (pkg != null) {
2902                         synchronized (mInstallLock) {
2903                             prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2904                                     true /* maybeMigrateAppData */);
2905                         }
2906                         count++;
2907                     }
2908                 }
2909                 traceLog.traceEnd();
2910                 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2911             }, "prepareAppData");
2912
2913             // If this is first boot after an OTA, and a normal boot, then
2914             // we need to clear code cache directories.
2915             // Note that we do *not* clear the application profiles. These remain valid
2916             // across OTAs and are used to drive profile verification (post OTA) and
2917             // profile compilation (without waiting to collect a fresh set of profiles).
2918             if (mIsUpgrade && !onlyCore) {
2919                 Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2920                 for (int i = 0; i < mSettings.mPackages.size(); i++) {
2921                     final PackageSetting ps = mSettings.mPackages.valueAt(i);
2922                     if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2923                         // No apps are running this early, so no need to freeze
2924                         clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2925                                 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2926                                         | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2927                     }
2928                 }
2929                 ver.fingerprint = Build.FINGERPRINT;
2930             }
2931
2932             checkDefaultBrowser();
2933
2934             // clear only after permissions and other defaults have been updated
2935             mExistingSystemPackages.clear();
2936             mPromoteSystemApps = false;
2937
2938             // All the changes are done during package scanning.
2939             ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2940
2941             // can downgrade to reader
2942             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2943             mSettings.writeLPr();
2944             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2945
2946             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2947                     SystemClock.uptimeMillis());
2948
2949             if (!mOnlyCore) {
2950                 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2951                 mRequiredInstallerPackage = getRequiredInstallerLPr();
2952                 mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2953                 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2954                 if (mIntentFilterVerifierComponent != null) {
2955                     mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2956                             mIntentFilterVerifierComponent);
2957                 } else {
2958                     mIntentFilterVerifier = null;
2959                 }
2960                 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2961                         PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2962                         SharedLibraryInfo.VERSION_UNDEFINED);
2963                 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2964                         PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2965                         SharedLibraryInfo.VERSION_UNDEFINED);
2966             } else {
2967                 mRequiredVerifierPackage = null;
2968                 mRequiredInstallerPackage = null;
2969                 mRequiredUninstallerPackage = null;
2970                 mIntentFilterVerifierComponent = null;
2971                 mIntentFilterVerifier = null;
2972                 mServicesSystemSharedLibraryPackageName = null;
2973                 mSharedSystemSharedLibraryPackageName = null;
2974             }
2975
2976             mInstallerService = new PackageInstallerService(context, this);
2977             final Pair<ComponentName, String> instantAppResolverComponent =
2978                     getInstantAppResolverLPr();
2979             if (instantAppResolverComponent != null) {
2980                 if (DEBUG_EPHEMERAL) {
2981                     Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2982                 }
2983                 mInstantAppResolverConnection = new EphemeralResolverConnection(
2984                         mContext, instantAppResolverComponent.first,
2985                         instantAppResolverComponent.second);
2986                 mInstantAppResolverSettingsComponent =
2987                         getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2988             } else {
2989                 mInstantAppResolverConnection = null;
2990                 mInstantAppResolverSettingsComponent = null;
2991             }
2992             updateInstantAppInstallerLocked(null);
2993
2994             // Read and update the usage of dex files.
2995             // Do this at the end of PM init so that all the packages have their
2996             // data directory reconciled.
2997             // At this point we know the code paths of the packages, so we can validate
2998             // the disk file and build the internal cache.
2999             // The usage file is expected to be small so loading and verifying it
3000             // should take a fairly small time compare to the other activities (e.g. package
3001             // scanning).
3002             final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3003             final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3004             for (int userId : currentUserIds) {
3005                 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3006             }
3007             mDexManager.load(userPackages);
3008         } // synchronized (mPackages)
3009         } // synchronized (mInstallLock)
3010
3011         // Now after opening every single application zip, make sure they
3012         // are all flushed.  Not really needed, but keeps things nice and
3013         // tidy.
3014         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3015         Runtime.getRuntime().gc();
3016         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3017
3018         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3019         FallbackCategoryProvider.loadFallbacks();
3020         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3021
3022         // The initial scanning above does many calls into installd while
3023         // holding the mPackages lock, but we're mostly interested in yelling
3024         // once we have a booted system.
3025         mInstaller.setWarnIfHeld(mPackages);
3026
3027         // Expose private service for system components to use.
3028         LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3029         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3030     }
3031
3032     private void updateInstantAppInstallerLocked(String modifiedPackage) {
3033         // we're only interested in updating the installer appliction when 1) it's not
3034         // already set or 2) the modified package is the installer
3035         if (mInstantAppInstallerActivity != null
3036                 && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3037                         .equals(modifiedPackage)) {
3038             return;
3039         }
3040         setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3041     }
3042
3043     private static File preparePackageParserCache(boolean isUpgrade) {
3044         if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3045             return null;
3046         }
3047
3048         // Disable package parsing on eng builds to allow for faster incremental development.
3049         if ("eng".equals(Build.TYPE)) {
3050             return null;
3051         }
3052
3053         if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3054             Slog.i(TAG, "Disabling package parser cache due to system property.");
3055             return null;
3056         }
3057
3058         // The base directory for the package parser cache lives under /data/system/.
3059         final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3060                 "package_cache");
3061         if (cacheBaseDir == null) {
3062             return null;
3063         }
3064
3065         // If this is a system upgrade scenario, delete the contents of the package cache dir.
3066         // This also serves to "GC" unused entries when the package cache version changes (which
3067         // can only happen during upgrades).
3068         if (isUpgrade) {
3069             FileUtils.deleteContents(cacheBaseDir);
3070         }
3071
3072
3073         // Return the versioned package cache directory. This is something like
3074         // "/data/system/package_cache/1"
3075         File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3076
3077         // The following is a workaround to aid development on non-numbered userdebug
3078         // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3079         // the system partition is newer.
3080         //
3081         // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3082         // that starts with "eng." to signify that this is an engineering build and not
3083         // destined for release.
3084         if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3085             Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3086
3087             // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3088             // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3089             // in general and should not be used for production changes. In this specific case,
3090             // we know that they will work.
3091             File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3092             if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3093                 FileUtils.deleteContents(cacheBaseDir);
3094                 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3095             }
3096         }
3097
3098         return cacheDir;
3099     }
3100
3101     @Override
3102     public boolean isFirstBoot() {
3103         // allow instant applications
3104         return mFirstBoot;
3105     }
3106
3107     @Override
3108     public boolean isOnlyCoreApps() {
3109         // allow instant applications
3110         return mOnlyCore;
3111     }
3112
3113     @Override
3114     public boolean isUpgrade() {
3115         // allow instant applications
3116         return mIsUpgrade;
3117     }
3118
3119     private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3120         final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3121
3122         final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3123                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3124                 UserHandle.USER_SYSTEM);
3125         if (matches.size() == 1) {
3126             return matches.get(0).getComponentInfo().packageName;
3127         } else if (matches.size() == 0) {
3128             Log.e(TAG, "There should probably be a verifier, but, none were found");
3129             return null;
3130         }
3131         throw new RuntimeException("There must be exactly one verifier; found " + matches);
3132     }
3133
3134     private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3135         synchronized (mPackages) {
3136             SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3137             if (libraryEntry == null) {
3138                 throw new IllegalStateException("Missing required shared library:" + name);
3139             }
3140             return libraryEntry.apk;
3141         }
3142     }
3143
3144     private @NonNull String getRequiredInstallerLPr() {
3145         final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3146         intent.addCategory(Intent.CATEGORY_DEFAULT);
3147         intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3148
3149         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3150                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3151                 UserHandle.USER_SYSTEM);
3152         if (matches.size() == 1) {
3153             ResolveInfo resolveInfo = matches.get(0);
3154             if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3155                 throw new RuntimeException("The installer must be a privileged app");
3156             }
3157             return matches.get(0).getComponentInfo().packageName;
3158         } else {
3159             throw new RuntimeException("There must be exactly one installer; found " + matches);
3160         }
3161     }
3162
3163     private @NonNull String getRequiredUninstallerLPr() {
3164         final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3165         intent.addCategory(Intent.CATEGORY_DEFAULT);
3166         intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3167
3168         final ResolveInfo resolveInfo = resolveIntent(intent, null,
3169                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3170                 UserHandle.USER_SYSTEM);
3171         if (resolveInfo == null ||
3172                 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3173             throw new RuntimeException("There must be exactly one uninstaller; found "
3174                     + resolveInfo);
3175         }
3176         return resolveInfo.getComponentInfo().packageName;
3177     }
3178
3179     private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3180         final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3181
3182         final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3183                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3184                 UserHandle.USER_SYSTEM);
3185         ResolveInfo best = null;
3186         final int N = matches.size();
3187         for (int i = 0; i < N; i++) {
3188             final ResolveInfo cur = matches.get(i);
3189             final String packageName = cur.getComponentInfo().packageName;
3190             if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3191                     packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3192                 continue;
3193             }
3194
3195             if (best == null || cur.priority > best.priority) {
3196                 best = cur;
3197             }
3198         }
3199
3200         if (best != null) {
3201             return best.getComponentInfo().getComponentName();
3202         }
3203         Slog.w(TAG, "Intent filter verifier not found");
3204         return null;
3205     }
3206
3207     @Override
3208     public @Nullable ComponentName getInstantAppResolverComponent() {
3209         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3210             return null;
3211         }
3212         synchronized (mPackages) {
3213             final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3214             if (instantAppResolver == null) {
3215                 return null;
3216             }
3217             return instantAppResolver.first;
3218         }
3219     }
3220
3221     private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3222         final String[] packageArray =
3223                 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3224         if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3225             if (DEBUG_EPHEMERAL) {
3226                 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3227             }
3228             return null;
3229         }
3230
3231         final int callingUid = Binder.getCallingUid();
3232         final int resolveFlags =
3233                 MATCH_DIRECT_BOOT_AWARE
3234                 | MATCH_DIRECT_BOOT_UNAWARE
3235                 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3236         String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3237         final Intent resolverIntent = new Intent(actionName);
3238         List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3239                 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3240         // temporarily look for the old action
3241         if (resolvers.size() == 0) {
3242             if (DEBUG_EPHEMERAL) {
3243                 Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3244             }
3245             actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3246             resolverIntent.setAction(actionName);
3247             resolvers = queryIntentServicesInternal(resolverIntent, null,
3248                     resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3249         }
3250         final int N = resolvers.size();
3251         if (N == 0) {
3252             if (DEBUG_EPHEMERAL) {
3253                 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3254             }
3255             return null;
3256         }
3257
3258         final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3259         for (int i = 0; i < N; i++) {
3260             final ResolveInfo info = resolvers.get(i);
3261
3262             if (info.serviceInfo == null) {
3263                 continue;
3264             }
3265
3266             final String packageName = info.serviceInfo.packageName;
3267             if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3268                 if (DEBUG_EPHEMERAL) {
3269                     Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3270                             + " pkg: " + packageName + ", info:" + info);
3271                 }
3272                 continue;
3273             }
3274
3275             if (DEBUG_EPHEMERAL) {
3276                 Slog.v(TAG, "Ephemeral resolver found;"
3277                         + " pkg: " + packageName + ", info:" + info);
3278             }
3279             return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3280         }
3281         if (DEBUG_EPHEMERAL) {
3282             Slog.v(TAG, "Ephemeral resolver NOT found");
3283         }
3284         return null;
3285     }
3286
3287     private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3288         final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3289         intent.addCategory(Intent.CATEGORY_DEFAULT);
3290         intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3291
3292         final int resolveFlags =
3293                 MATCH_DIRECT_BOOT_AWARE
3294                 | MATCH_DIRECT_BOOT_UNAWARE
3295                 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3296         List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3297                 resolveFlags, UserHandle.USER_SYSTEM);
3298         // temporarily look for the old action
3299         if (matches.isEmpty()) {
3300             if (DEBUG_EPHEMERAL) {
3301                 Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3302             }
3303             intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3304             matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3305                     resolveFlags, UserHandle.USER_SYSTEM);
3306         }
3307         Iterator<ResolveInfo> iter = matches.iterator();
3308         while (iter.hasNext()) {
3309             final ResolveInfo rInfo = iter.next();
3310             final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3311             if (ps != null) {
3312                 final PermissionsState permissionsState = ps.getPermissionsState();
3313                 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3314                     continue;
3315                 }
3316             }
3317             iter.remove();
3318         }
3319         if (matches.size() == 0) {
3320             return null;
3321         } else if (matches.size() == 1) {
3322             return (ActivityInfo) matches.get(0).getComponentInfo();
3323         } else {
3324             throw new RuntimeException(
3325                     "There must be at most one ephemeral installer; found " + matches);
3326         }
3327     }
3328
3329     private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3330             @NonNull ComponentName resolver) {
3331         final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3332                 .addCategory(Intent.CATEGORY_DEFAULT)
3333                 .setPackage(resolver.getPackageName());
3334         final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3335         List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3336                 UserHandle.USER_SYSTEM);
3337         // temporarily look for the old action
3338         if (matches.isEmpty()) {
3339             if (DEBUG_EPHEMERAL) {
3340                 Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3341             }
3342             intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3343             matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3344                     UserHandle.USER_SYSTEM);
3345         }
3346         if (matches.isEmpty()) {
3347             return null;
3348         }
3349         return matches.get(0).getComponentInfo().getComponentName();
3350     }
3351
3352     private void primeDomainVerificationsLPw(int userId) {
3353         if (DEBUG_DOMAIN_VERIFICATION) {
3354             Slog.d(TAG, "Priming domain verifications in user " + userId);
3355         }
3356
3357         SystemConfig systemConfig = SystemConfig.getInstance();
3358         ArraySet<String> packages = systemConfig.getLinkedApps();
3359
3360         for (String packageName : packages) {
3361             PackageParser.Package pkg = mPackages.get(packageName);
3362             if (pkg != null) {
3363                 if (!pkg.isSystemApp()) {
3364                     Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3365                     continue;
3366                 }
3367
3368                 ArraySet<String> domains = null;
3369                 for (PackageParser.Activity a : pkg.activities) {
3370                     for (ActivityIntentInfo filter : a.intents) {
3371                         if (hasValidDomains(filter)) {
3372                             if (domains == null) {
3373                                 domains = new ArraySet<String>();
3374                             }
3375                             domains.addAll(filter.getHostsList());
3376                         }
3377                     }
3378                 }
3379
3380                 if (domains != null && domains.size() > 0) {
3381                     if (DEBUG_DOMAIN_VERIFICATION) {
3382                         Slog.v(TAG, "      + " + packageName);
3383                     }
3384                     // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3385                     // state w.r.t. the formal app-linkage "no verification attempted" state;
3386                     // and then 'always' in the per-user state actually used for intent resolution.
3387                     final IntentFilterVerificationInfo ivi;
3388                     ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3389                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3390                     mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3391                             INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3392                 } else {
3393                     Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3394                             + "' does not handle web links");
3395                 }
3396             } else {
3397                 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3398             }
3399         }
3400
3401         scheduleWritePackageRestrictionsLocked(userId);
3402         scheduleWriteSettingsLocked();
3403     }
3404
3405     private void applyFactoryDefaultBrowserLPw(int userId) {
3406         // The default browser app's package name is stored in a string resource,
3407         // with a product-specific overlay used for vendor customization.
3408         String browserPkg = mContext.getResources().getString(
3409                 com.android.internal.R.string.default_browser);
3410         if (!TextUtils.isEmpty(browserPkg)) {
3411             // non-empty string => required to be a known package
3412             PackageSetting ps = mSettings.mPackages.get(browserPkg);
3413             if (ps == null) {
3414                 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3415                 browserPkg = null;
3416             } else {
3417                 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3418             }
3419         }
3420
3421         // Nothing valid explicitly set? Make the factory-installed browser the explicit
3422         // default.  If there's more than one, just leave everything alone.
3423         if (browserPkg == null) {
3424             calculateDefaultBrowserLPw(userId);
3425         }
3426     }
3427
3428     private void calculateDefaultBrowserLPw(int userId) {
3429         List<String> allBrowsers = resolveAllBrowserApps(userId);
3430         final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3431         mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3432     }
3433
3434     private List<String> resolveAllBrowserApps(int userId) {
3435         // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3436         List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3437                 PackageManager.MATCH_ALL, userId);
3438
3439         final int count = list.size();
3440         List<String> result = new ArrayList<String>(count);
3441         for (int i=0; i<count; i++) {
3442             ResolveInfo info = list.get(i);
3443             if (info.activityInfo == null
3444                     || !info.handleAllWebDataURI
3445                     || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3446                     || result.contains(info.activityInfo.packageName)) {
3447                 continue;
3448             }
3449             result.add(info.activityInfo.packageName);
3450         }
3451
3452         return result;
3453     }
3454
3455     private boolean packageIsBrowser(String packageName, int userId) {
3456         List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3457                 PackageManager.MATCH_ALL, userId);
3458         final int N = list.size();
3459         for (int i = 0; i < N; i++) {
3460             ResolveInfo info = list.get(i);
3461             if (packageName.equals(info.activityInfo.packageName)) {
3462                 return true;
3463             }
3464         }
3465         return false;
3466     }
3467
3468     private void checkDefaultBrowser() {
3469         final int myUserId = UserHandle.myUserId();
3470         final String packageName = getDefaultBrowserPackageName(myUserId);
3471         if (packageName != null) {
3472             PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3473             if (info == null) {
3474                 Slog.w(TAG, "Default browser no longer installed: " + packageName);
3475                 synchronized (mPackages) {
3476                     applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3477                 }
3478             }
3479         }
3480     }
3481
3482     @Override
3483     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3484             throws RemoteException {
3485         try {
3486             return super.onTransact(code, data, reply, flags);
3487         } catch (RuntimeException e) {
3488             if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3489                 Slog.wtf(TAG, "Package Manager Crash", e);
3490             }
3491             throw e;
3492         }
3493     }
3494
3495     static int[] appendInts(int[] cur, int[] add) {
3496         if (add == null) return cur;
3497         if (cur == null) return add;
3498         final int N = add.length;
3499         for (int i=0; i<N; i++) {
3500             cur = appendInt(cur, add[i]);
3501         }
3502         return cur;
3503     }
3504
3505     /**
3506      * Returns whether or not a full application can see an instant application.
3507      * <p>
3508      * Currently, there are three cases in which this can occur:
3509      * <ol>
3510      * <li>The calling application is a "special" process. The special
3511      *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3512      *     and {@code 0}</li>
3513      * <li>The calling application has the permission
3514      *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3515      * <li>The calling application is the default launcher on the
3516      *     system partition.</li>
3517      * </ol>
3518      */
3519     private boolean canViewInstantApps(int callingUid, int userId) {
3520         if (callingUid == Process.SYSTEM_UID
3521                 || callingUid == Process.SHELL_UID
3522                 || callingUid == Process.ROOT_UID) {
3523             return true;
3524         }
3525         if (mContext.checkCallingOrSelfPermission(
3526                 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3527             return true;
3528         }
3529         if (mContext.checkCallingOrSelfPermission(
3530                 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3531             final ComponentName homeComponent = getDefaultHomeActivity(userId);
3532             if (homeComponent != null
3533                     && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3534                 return true;
3535             }
3536         }
3537         return false;
3538     }
3539
3540     private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3541         if (!sUserManager.exists(userId)) return null;
3542         if (ps == null) {
3543             return null;
3544         }
3545         PackageParser.Package p = ps.pkg;
3546         if (p == null) {
3547             return null;
3548         }
3549         final int callingUid = Binder.getCallingUid();
3550         // Filter out ephemeral app metadata:
3551         //   * The system/shell/root can see metadata for any app
3552         //   * An installed app can see metadata for 1) other installed apps
3553         //     and 2) ephemeral apps that have explicitly interacted with it
3554         //   * Ephemeral apps can only see their own data and exposed installed apps
3555         //   * Holding a signature permission allows seeing instant apps
3556         if (filterAppAccessLPr(ps, callingUid, userId)) {
3557             return null;
3558         }
3559
3560         final PermissionsState permissionsState = ps.getPermissionsState();
3561
3562         // Compute GIDs only if requested
3563         final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3564                 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3565         // Compute granted permissions only if package has requested permissions
3566         final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3567                 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3568         final PackageUserState state = ps.readUserState(userId);
3569
3570         if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3571                 && ps.isSystem()) {
3572             flags |= MATCH_ANY_USER;
3573         }
3574
3575         PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3576                 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3577
3578         if (packageInfo == null) {
3579             return null;
3580         }
3581
3582         packageInfo.packageName = packageInfo.applicationInfo.packageName =
3583                 resolveExternalPackageNameLPr(p);
3584
3585         return packageInfo;
3586     }
3587
3588     @Override
3589     public void checkPackageStartable(String packageName, int userId) {
3590         final int callingUid = Binder.getCallingUid();
3591         if (getInstantAppPackageName(callingUid) != null) {
3592             throw new SecurityException("Instant applications don't have access to this method");
3593         }
3594         final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3595         synchronized (mPackages) {
3596             final PackageSetting ps = mSettings.mPackages.get(packageName);
3597             if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3598                 throw new SecurityException("Package " + packageName + " was not found!");
3599             }
3600
3601             if (!ps.getInstalled(userId)) {
3602                 throw new SecurityException(
3603                         "Package " + packageName + " was not installed for user " + userId + "!");
3604             }
3605
3606             if (mSafeMode && !ps.isSystem()) {
3607                 throw new SecurityException("Package " + packageName + " not a system app!");
3608             }
3609
3610             if (mFrozenPackages.contains(packageName)) {
3611                 throw new SecurityException("Package " + packageName + " is currently frozen!");
3612             }
3613
3614             if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3615                     || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3616                 throw new SecurityException("Package " + packageName + " is not encryption aware!");
3617             }
3618         }
3619     }
3620
3621     @Override
3622     public boolean isPackageAvailable(String packageName, int userId) {
3623         if (!sUserManager.exists(userId)) return false;
3624         final int callingUid = Binder.getCallingUid();
3625         enforceCrossUserPermission(callingUid, userId,
3626                 false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3627         synchronized (mPackages) {
3628             PackageParser.Package p = mPackages.get(packageName);
3629             if (p != null) {
3630                 final PackageSetting ps = (PackageSetting) p.mExtras;
3631                 if (filterAppAccessLPr(ps, callingUid, userId)) {
3632                     return false;
3633                 }
3634                 if (ps != null) {
3635                     final PackageUserState state = ps.readUserState(userId);
3636                     if (state != null) {
3637                         return PackageParser.isAvailable(state);
3638                     }
3639                 }
3640             }
3641         }
3642         return false;
3643     }
3644
3645     @Override
3646     public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3647         return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3648                 flags, Binder.getCallingUid(), userId);
3649     }
3650
3651     @Override
3652     public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3653             int flags, int userId) {
3654         return getPackageInfoInternal(versionedPackage.getPackageName(),
3655                 versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3656     }
3657
3658     /**
3659      * Important: The provided filterCallingUid is used exclusively to filter out packages
3660      * that can be seen based on user state. It's typically the original caller uid prior
3661      * to clearing. Because it can only be provided by trusted code, it's value can be
3662      * trusted and will be used as-is; unlike userId which will be validated by this method.
3663      */
3664     private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3665             int flags, int filterCallingUid, int userId) {
3666         if (!sUserManager.exists(userId)) return null;
3667         flags = updateFlagsForPackage(flags, userId, packageName);
3668         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3669                 false /* requireFullPermission */, false /* checkShell */, "get package info");
3670
3671         // reader
3672         synchronized (mPackages) {
3673             // Normalize package name to handle renamed packages and static libs
3674             packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3675
3676             final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3677             if (matchFactoryOnly) {
3678                 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3679                 if (ps != null) {
3680                     if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3681                         return null;
3682                     }
3683                     if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3684                         return null;
3685                     }
3686                     return generatePackageInfo(ps, flags, userId);
3687                 }
3688             }
3689
3690             PackageParser.Package p = mPackages.get(packageName);
3691             if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3692                 return null;
3693             }
3694             if (DEBUG_PACKAGE_INFO)
3695                 Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3696             if (p != null) {
3697                 final PackageSetting ps = (PackageSetting) p.mExtras;
3698                 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3699                     return null;
3700                 }
3701                 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3702                     return null;
3703                 }
3704                 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3705             }
3706             if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3707                 final PackageSetting ps = mSettings.mPackages.get(packageName);
3708                 if (ps == null) return null;
3709                 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3710                     return null;
3711                 }
3712                 if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3713                     return null;
3714                 }
3715                 return generatePackageInfo(ps, flags, userId);
3716             }
3717         }
3718         return null;
3719     }
3720
3721     private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3722         if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3723             return true;
3724         }
3725         if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3726             return true;
3727         }
3728         if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3729             return true;
3730         }
3731         return false;
3732     }
3733
3734     private boolean isComponentVisibleToInstantApp(
3735             @Nullable ComponentName component, @ComponentType int type) {
3736         if (type == TYPE_ACTIVITY) {
3737             final PackageParser.Activity activity = mActivities.mActivities.get(component);
3738             return activity != null
3739                     ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3740                     : false;
3741         } else if (type == TYPE_RECEIVER) {
3742             final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3743             return activity != null
3744                     ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3745                     : false;
3746         } else if (type == TYPE_SERVICE) {
3747             final PackageParser.Service service = mServices.mServices.get(component);
3748             return service != null
3749                     ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3750                     : false;
3751         } else if (type == TYPE_PROVIDER) {
3752             final PackageParser.Provider provider = mProviders.mProviders.get(component);
3753             return provider != null
3754                     ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3755                     : false;
3756         } else if (type == TYPE_UNKNOWN) {
3757             return isComponentVisibleToInstantApp(component);
3758         }
3759         return false;
3760     }
3761
3762     /**
3763      * Returns whether or not access to the application should be filtered.
3764      * <p>
3765      * Access may be limited based upon whether the calling or target applications
3766      * are instant applications.
3767      *
3768      * @see #canAccessInstantApps(int)
3769      */
3770     private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3771             @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3772         // if we're in an isolated process, get the real calling UID
3773         if (Process.isIsolated(callingUid)) {
3774             callingUid = mIsolatedOwners.get(callingUid);
3775         }
3776         final String instantAppPkgName = getInstantAppPackageName(callingUid);
3777         final boolean callerIsInstantApp = instantAppPkgName != null;
3778         if (ps == null) {
3779             if (callerIsInstantApp) {
3780                 // pretend the application exists, but, needs to be filtered
3781                 return true;
3782             }
3783             return false;
3784         }
3785         // if the target and caller are the same application, don't filter
3786         if (isCallerSameApp(ps.name, callingUid)) {
3787             return false;
3788         }
3789         if (callerIsInstantApp) {
3790             // request for a specific component; if it hasn't been explicitly exposed, filter
3791             if (component != null) {
3792                 return !isComponentVisibleToInstantApp(component, componentType);
3793             }
3794             // request for application; if no components have been explicitly exposed, filter
3795             return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3796         }
3797         if (ps.getInstantApp(userId)) {
3798             // caller can see all components of all instant applications, don't filter
3799             if (canViewInstantApps(callingUid, userId)) {
3800                 return false;
3801             }
3802             // request for a specific instant application component, filter
3803             if (component != null) {
3804                 return true;
3805             }
3806             // request for an instant application; if the caller hasn't been granted access, filter
3807             return !mInstantAppRegistry.isInstantAccessGranted(
3808                     userId, UserHandle.getAppId(callingUid), ps.appId);
3809         }
3810         return false;
3811     }
3812
3813     /**
3814      * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3815      */
3816     private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3817         return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3818     }
3819
3820     private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3821             int flags) {
3822         // Callers can access only the libs they depend on, otherwise they need to explicitly
3823         // ask for the shared libraries given the caller is allowed to access all static libs.
3824         if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3825             // System/shell/root get to see all static libs
3826             final int appId = UserHandle.getAppId(uid);
3827             if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3828                     || appId == Process.ROOT_UID) {
3829                 return false;
3830             }
3831         }
3832
3833         // No package means no static lib as it is always on internal storage
3834         if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3835             return false;
3836         }
3837
3838         final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3839                 ps.pkg.staticSharedLibVersion);
3840         if (libEntry == null) {
3841             return false;
3842         }
3843
3844         final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3845         final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3846         if (uidPackageNames == null) {
3847             return true;
3848         }
3849
3850         for (String uidPackageName : uidPackageNames) {
3851             if (ps.name.equals(uidPackageName)) {
3852                 return false;
3853             }
3854             PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3855             if (uidPs != null) {
3856                 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3857                         libEntry.info.getName());
3858                 if (index < 0) {
3859                     continue;
3860                 }
3861                 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3862                     return false;
3863                 }
3864             }
3865         }
3866         return true;
3867     }
3868
3869     @Override
3870     public String[] currentToCanonicalPackageNames(String[] names) {
3871         final int callingUid = Binder.getCallingUid();
3872         if (getInstantAppPackageName(callingUid) != null) {
3873             return names;
3874         }
3875         final String[] out = new String[names.length];
3876         // reader
3877         synchronized (mPackages) {
3878             final int callingUserId = UserHandle.getUserId(callingUid);
3879             final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3880             for (int i=names.length-1; i>=0; i--) {
3881                 final PackageSetting ps = mSettings.mPackages.get(names[i]);
3882                 boolean translateName = false;
3883                 if (ps != null && ps.realName != null) {
3884                     final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3885                     translateName = !targetIsInstantApp
3886                             || canViewInstantApps
3887                             || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3888                                     UserHandle.getAppId(callingUid), ps.appId);
3889                 }
3890                 out[i] = translateName ? ps.realName : names[i];
3891             }
3892         }
3893         return out;
3894     }
3895
3896     @Override
3897     public String[] canonicalToCurrentPackageNames(String[] names) {
3898         final int callingUid = Binder.getCallingUid();
3899         if (getInstantAppPackageName(callingUid) != null) {
3900             return names;
3901         }
3902         final String[] out = new String[names.length];
3903         // reader
3904         synchronized (mPackages) {
3905             final int callingUserId = UserHandle.getUserId(callingUid);
3906             final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3907             for (int i=names.length-1; i>=0; i--) {
3908                 final String cur = mSettings.getRenamedPackageLPr(names[i]);
3909                 boolean translateName = false;
3910                 if (cur != null) {
3911                     final PackageSetting ps = mSettings.mPackages.get(names[i]);
3912                     final boolean targetIsInstantApp =
3913                             ps != null && ps.getInstantApp(callingUserId);
3914                     translateName = !targetIsInstantApp
3915                             || canViewInstantApps
3916                             || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3917                                     UserHandle.getAppId(callingUid), ps.appId);
3918                 }
3919                 out[i] = translateName ? cur : names[i];
3920             }
3921         }
3922         return out;
3923     }
3924
3925     @Override
3926     public int getPackageUid(String packageName, int flags, int userId) {
3927         if (!sUserManager.exists(userId)) return -1;
3928         final int callingUid = Binder.getCallingUid();
3929         flags = updateFlagsForPackage(flags, userId, packageName);
3930         enforceCrossUserPermission(callingUid, userId,
3931                 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3932
3933         // reader
3934         synchronized (mPackages) {
3935             final PackageParser.Package p = mPackages.get(packageName);
3936             if (p != null && p.isMatch(flags)) {
3937                 PackageSetting ps = (PackageSetting) p.mExtras;
3938                 if (filterAppAccessLPr(ps, callingUid, userId)) {
3939                     return -1;
3940                 }
3941                 return UserHandle.getUid(userId, p.applicationInfo.uid);
3942             }
3943             if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3944                 final PackageSetting ps = mSettings.mPackages.get(packageName);
3945                 if (ps != null && ps.isMatch(flags)
3946                         && !filterAppAccessLPr(ps, callingUid, userId)) {
3947                     return UserHandle.getUid(userId, ps.appId);
3948                 }
3949             }
3950         }
3951
3952         return -1;
3953     }
3954
3955     @Override
3956     public int[] getPackageGids(String packageName, int flags, int userId) {
3957         if (!sUserManager.exists(userId)) return null;
3958         final int callingUid = Binder.getCallingUid();
3959         flags = updateFlagsForPackage(flags, userId, packageName);
3960         enforceCrossUserPermission(callingUid, userId,
3961                 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3962
3963         // reader
3964         synchronized (mPackages) {
3965             final PackageParser.Package p = mPackages.get(packageName);
3966             if (p != null && p.isMatch(flags)) {
3967                 PackageSetting ps = (PackageSetting) p.mExtras;
3968                 if (filterAppAccessLPr(ps, callingUid, userId)) {
3969                     return null;
3970                 }
3971                 // TODO: Shouldn't this be checking for package installed state for userId and
3972                 // return null?
3973                 return ps.getPermissionsState().computeGids(userId);
3974             }
3975             if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3976                 final PackageSetting ps = mSettings.mPackages.get(packageName);
3977                 if (ps != null && ps.isMatch(flags)
3978                         && !filterAppAccessLPr(ps, callingUid, userId)) {
3979                     return ps.getPermissionsState().computeGids(userId);
3980                 }
3981             }
3982         }
3983
3984         return null;
3985     }
3986
3987     static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3988         if (bp.perm != null) {
3989             return PackageParser.generatePermissionInfo(bp.perm, flags);
3990         }
3991         PermissionInfo pi = new PermissionInfo();
3992         pi.name = bp.name;
3993         pi.packageName = bp.sourcePackage;
3994         pi.nonLocalizedLabel = bp.name;
3995         pi.protectionLevel = bp.protectionLevel;
3996         return pi;
3997     }
3998
3999     @Override
4000     public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4001         final int callingUid = Binder.getCallingUid();
4002         if (getInstantAppPackageName(callingUid) != null) {
4003             return null;
4004         }
4005         // reader
4006         synchronized (mPackages) {
4007             final BasePermission p = mSettings.mPermissions.get(name);
4008             if (p == null) {
4009                 return null;
4010             }
4011             // If the caller is an app that targets pre 26 SDK drop protection flags.
4012             final PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4013             if (permissionInfo != null) {
4014                 permissionInfo.protectionLevel = adjustPermissionProtectionFlagsLPr(
4015                         permissionInfo.protectionLevel, packageName, callingUid);
4016             }
4017             return permissionInfo;
4018         }
4019     }
4020
4021     private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4022             String packageName, int uid) {
4023         // Signature permission flags area always reported
4024         final int protectionLevelMasked = protectionLevel
4025                 & (PermissionInfo.PROTECTION_NORMAL
4026                 | PermissionInfo.PROTECTION_DANGEROUS
4027                 | PermissionInfo.PROTECTION_SIGNATURE);
4028         if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4029             return protectionLevel;
4030         }
4031
4032         // System sees all flags.
4033         final int appId = UserHandle.getAppId(uid);
4034         if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4035                 || appId == Process.SHELL_UID) {
4036             return protectionLevel;
4037         }
4038
4039         // Normalize package name to handle renamed packages and static libs
4040         packageName = resolveInternalPackageNameLPr(packageName,
4041                 PackageManager.VERSION_CODE_HIGHEST);
4042
4043         // Apps that target O see flags for all protection levels.
4044         final PackageSetting ps = mSettings.mPackages.get(packageName);
4045         if (ps == null) {
4046             return protectionLevel;
4047         }
4048         if (ps.appId != appId) {
4049             return protectionLevel;
4050         }
4051
4052         final PackageParser.Package pkg = mPackages.get(packageName);
4053         if (pkg == null) {
4054             return protectionLevel;
4055         }
4056         if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4057             return protectionLevelMasked;
4058         }
4059
4060         return protectionLevel;
4061     }
4062
4063     @Override
4064     public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4065             int flags) {
4066         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4067             return null;
4068         }
4069         // reader
4070         synchronized (mPackages) {
4071             if (group != null && !mPermissionGroups.containsKey(group)) {
4072                 // This is thrown as NameNotFoundException
4073                 return null;
4074             }
4075
4076             ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4077             for (BasePermission p : mSettings.mPermissions.values()) {
4078                 if (group == null) {
4079                     if (p.perm == null || p.perm.info.group == null) {
4080                         out.add(generatePermissionInfo(p, flags));
4081                     }
4082                 } else {
4083                     if (p.perm != null && group.equals(p.perm.info.group)) {
4084                         out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4085                     }
4086                 }
4087             }
4088             return new ParceledListSlice<>(out);
4089         }
4090     }
4091
4092     @Override
4093     public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4094         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4095             return null;
4096         }
4097         // reader
4098         synchronized (mPackages) {
4099             return PackageParser.generatePermissionGroupInfo(
4100                     mPermissionGroups.get(name), flags);
4101         }
4102     }
4103
4104     @Override
4105     public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4106         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4107             return ParceledListSlice.emptyList();
4108         }
4109         // reader
4110         synchronized (mPackages) {
4111             final int N = mPermissionGroups.size();
4112             ArrayList<PermissionGroupInfo> out
4113                     = new ArrayList<PermissionGroupInfo>(N);
4114             for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4115                 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4116             }
4117             return new ParceledListSlice<>(out);
4118         }
4119     }
4120
4121     private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4122             int filterCallingUid, int userId) {
4123         if (!sUserManager.exists(userId)) return null;
4124         PackageSetting ps = mSettings.mPackages.get(packageName);
4125         if (ps != null) {
4126             if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4127                 return null;
4128             }
4129             if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4130                 return null;
4131             }
4132             if (ps.pkg == null) {
4133                 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4134                 if (pInfo != null) {
4135                     return pInfo.applicationInfo;
4136                 }
4137                 return null;
4138             }
4139             ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4140                     ps.readUserState(userId), userId);
4141             if (ai != null) {
4142                 ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4143             }
4144             return ai;
4145         }
4146         return null;
4147     }
4148
4149     @Override
4150     public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4151         return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4152     }
4153
4154     /**
4155      * Important: The provided filterCallingUid is used exclusively to filter out applications
4156      * that can be seen based on user state. It's typically the original caller uid prior
4157      * to clearing. Because it can only be provided by trusted code, it's value can be
4158      * trusted and will be used as-is; unlike userId which will be validated by this method.
4159      */
4160     private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4161             int filterCallingUid, int userId) {
4162         if (!sUserManager.exists(userId)) return null;
4163         flags = updateFlagsForApplication(flags, userId, packageName);
4164         enforceCrossUserPermission(Binder.getCallingUid(), userId,
4165                 false /* requireFullPermission */, false /* checkShell */, "get application info");
4166
4167         // writer
4168         synchronized (mPackages) {
4169             // Normalize package name to handle renamed packages and static libs
4170             packageName = resolveInternalPackageNameLPr(packageName,
4171                     PackageManager.VERSION_CODE_HIGHEST);
4172
4173             PackageParser.Package p = mPackages.get(packageName);
4174             if (DEBUG_PACKAGE_INFO) Log.v(
4175                     TAG, "getApplicationInfo " + packageName
4176                     + ": " + p);
4177             if (p != null) {
4178                 PackageSetting ps = mSettings.mPackages.get(packageName);
4179                 if (ps == null) return null;
4180                 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4181                     return null;
4182                 }
4183                 if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4184                     return null;
4185                 }
4186                 // Note: isEnabledLP() does not apply here - always return info
4187                 ApplicationInfo ai = PackageParser.generateApplicationInfo(
4188                         p, flags, ps.readUserState(userId), userId);
4189                 if (ai != null) {
4190                     ai.packageName = resolveExternalPackageNameLPr(p);
4191                 }
4192                 return ai;
4193             }
4194             if ("android".equals(packageName)||"system".equals(packageName)) {
4195                 return mAndroidApplication;
4196             }
4197             if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4198                 // Already generates the external package name
4199                 return generateApplicationInfoFromSettingsLPw(packageName,
4200                         flags, filterCallingUid, userId);
4201             }
4202         }
4203         return null;
4204     }
4205
4206     private String normalizePackageNameLPr(String packageName) {
4207         String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4208         return normalizedPackageName != null ? normalizedPackageName : packageName;
4209     }
4210
4211     @Override
4212     public void deletePreloadsFileCache() {
4213         if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4214             throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4215         }
4216         File dir = Environment.getDataPreloadsFileCacheDirectory();
4217         Slog.i(TAG, "Deleting preloaded file cache " + dir);
4218         FileUtils.deleteContents(dir);
4219     }
4220
4221     @Override
4222     public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4223             final int storageFlags, final IPackageDataObserver observer) {
4224         mContext.enforceCallingOrSelfPermission(
4225                 android.Manifest.permission.CLEAR_APP_CACHE, null);
4226         mHandler.post(() -> {
4227             boolean success = false;
4228             try {
4229                 freeStorage(volumeUuid, freeStorageSize, storageFlags);
4230                 success = true;
4231             } catch (IOException e) {
4232                 Slog.w(TAG, e);
4233             }
4234             if (observer != null) {
4235                 try {
4236                     observer.onRemoveCompleted(null, success);
4237                 } catch (RemoteException e) {
4238                     Slog.w(TAG, e);
4239                 }
4240             }
4241         });
4242     }
4243
4244     @Override
4245     public void freeStorage(final String volumeUuid, final long freeStorageSize,
4246             final int storageFlags, final IntentSender pi) {
4247         mContext.enforceCallingOrSelfPermission(
4248                 android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4249         mHandler.post(() -> {
4250             boolean success = false;
4251             try {
4252                 freeStorage(volumeUuid, freeStorageSize, storageFlags);
4253                 success = true;
4254             } catch (IOException e) {
4255                 Slog.w(TAG, e);
4256             }
4257             if (pi != null) {
4258                 try {
4259                     pi.sendIntent(null, success ? 1 : 0, null, null, null);
4260                 } catch (SendIntentException e) {
4261                     Slog.w(TAG, e);
4262                 }
4263             }
4264         });
4265     }
4266
4267     /**
4268      * Blocking call to clear various types of cached data across the system
4269      * until the requested bytes are available.
4270      */
4271     public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4272         final StorageManager storage = mContext.getSystemService(StorageManager.class);
4273         final File file = storage.findPathForUuid(volumeUuid);
4274         if (file.getUsableSpace() >= bytes) return;
4275
4276         if (ENABLE_FREE_CACHE_V2) {
4277             final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4278                     volumeUuid);
4279             final boolean aggressive = (storageFlags
4280                     & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4281             final boolean defyReserved = (storageFlags
4282                     & StorageManager.FLAG_ALLOCATE_DEFY_RESERVED) != 0;
4283             final long reservedBytes = (aggressive || defyReserved) ? 0
4284                     : storage.getStorageCacheBytes(file);
4285
4286             // 1. Pre-flight to determine if we have any chance to succeed
4287             // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4288             if (internalVolume && (aggressive || SystemProperties
4289                     .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4290                 deletePreloadsFileCache();
4291                 if (file.getUsableSpace() >= bytes) return;
4292             }
4293
4294             // 3. Consider parsed APK data (aggressive only)
4295             if (internalVolume && aggressive) {
4296                 FileUtils.deleteContents(mCacheDir);
4297                 if (file.getUsableSpace() >= bytes) return;
4298             }
4299
4300             // 4. Consider cached app data (above quotas)
4301             try {
4302                 mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4303                         Installer.FLAG_FREE_CACHE_V2);
4304             } catch (InstallerException ignored) {
4305             }
4306             if (file.getUsableSpace() >= bytes) return;
4307
4308             // 5. Consider shared libraries with refcount=0 and age>min cache period
4309             if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4310                     android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4311                             Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4312                             DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4313                 return;
4314             }
4315
4316             // 6. Consider dexopt output (aggressive only)
4317             // TODO: Implement
4318
4319             // 7. Consider installed instant apps unused longer than min cache period
4320             if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4321                     android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4322                             Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4323                             InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4324                 return;
4325             }
4326
4327             // 8. Consider cached app data (below quotas)
4328             try {
4329                 mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4330                         Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4331             } catch (InstallerException ignored) {
4332             }
4333             if (file.getUsableSpace() >= bytes) return;
4334
4335             // 9. Consider DropBox entries
4336             // TODO: Implement
4337
4338             // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4339             if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4340                     android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4341                             Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4342                             InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4343                 return;
4344             }
4345         } else {
4346             try {
4347                 mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4348             } catch (InstallerException ignored) {
4349             }
4350             if (file.getUsableSpace() >= bytes) return;
4351         }
4352
4353         throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4354     }
4355
4356     private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4357             throws IOException {
4358         final StorageManager storage = mContext.getSystemService(StorageManager.class);
4359         final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4360
4361         List<VersionedPackage> packagesToDelete = null;
4362         final long now = System.currentTimeMillis();
4363
4364         synchronized (mPackages) {
4365             final int[] allUsers = sUserManager.getUserIds();
4366             final int libCount = mSharedLibraries.size();
4367             for (int i = 0; i < libCount; i++) {
4368                 final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4369                 if (versionedLib == null) {
4370                     continue;
4371                 }
4372                 final int versionCount = versionedLib.size();
4373                 for (int j = 0; j < versionCount; j++) {
4374                     SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4375                     // Skip packages that are not static shared libs.
4376                     if (!libInfo.isStatic()) {
4377                         break;
4378                     }
4379                     // Important: We skip static shared libs used for some user since
4380                     // in such a case we need to keep the APK on the device. The check for
4381                     // a lib being used for any user is performed by the uninstall call.
4382                     final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4383                     // Resolve the package name - we use synthetic package names internally
4384                     final String internalPackageName = resolveInternalPackageNameLPr(
4385                             declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4386                     final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4387                     // Skip unused static shared libs cached less than the min period
4388                     // to prevent pruning a lib needed by a subsequently installed package.
4389                     if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4390                         continue;
4391                     }
4392                     if (packagesToDelete == null) {
4393                         packagesToDelete = new ArrayList<>();
4394                     }
4395                     packagesToDelete.add(new VersionedPackage(internalPackageName,
4396                             declaringPackage.getVersionCode()));
4397                 }
4398             }
4399         }
4400
4401         if (packagesToDelete != null) {
4402             final int packageCount = packagesToDelete.size();
4403             for (int i = 0; i < packageCount; i++) {
4404                 final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4405                 // Delete the package synchronously (will fail of the lib used for any user).
4406                 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4407                         UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4408                                 == PackageManager.DELETE_SUCCEEDED) {
4409                     if (volume.getUsableSpace() >= neededSpace) {
4410                         return true;
4411                     }
4412                 }
4413             }
4414         }
4415
4416         return false;
4417     }
4418
4419     /**
4420      * Update given flags based on encryption status of current user.
4421      */
4422     private int updateFlags(int flags, int userId) {
4423         if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4424                 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4425             // Caller expressed an explicit opinion about what encryption
4426             // aware/unaware components they want to see, so fall through and
4427             // give them what they want
4428         } else {
4429             // Caller expressed no opinion, so match based on user state
4430             if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4431                 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4432             } else {
4433                 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4434             }
4435         }
4436         return flags;
4437     }
4438
4439     private UserManagerInternal getUserManagerInternal() {
4440         if (mUserManagerInternal == null) {
4441             mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4442         }
4443         return mUserManagerInternal;
4444     }
4445
4446     private DeviceIdleController.LocalService getDeviceIdleController() {
4447         if (mDeviceIdleController == null) {
4448             mDeviceIdleController =
4449                     LocalServices.getService(DeviceIdleController.LocalService.class);
4450         }
4451         return mDeviceIdleController;
4452     }
4453
4454     /**
4455      * Update given flags when being used to request {@link PackageInfo}.
4456      */
4457     private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4458         final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4459         boolean triaged = true;
4460         if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4461                 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4462             // Caller is asking for component details, so they'd better be
4463             // asking for specific encryption matching behavior, or be triaged
4464             if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4465                     | PackageManager.MATCH_DIRECT_BOOT_AWARE
4466                     | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4467                 triaged = false;
4468             }
4469         }
4470         if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4471                 | PackageManager.MATCH_SYSTEM_ONLY
4472                 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4473             triaged = false;
4474         }
4475         if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4476             // require the permission to be held; the calling uid and given user id referring
4477             // to the same user is not sufficient
4478             try {
4479                 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, true,
4480                         "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4481                         + Debug.getCallers(5));
4482             } catch (SecurityException se) {
4483                 // For compatibility reasons, we can't throw a security exception here if we're
4484                 // looking for applications in our own user id. Instead, unset the MATCH_ANY_USER
4485                 // flag and move on.
4486                 if (userId != UserHandle.getCallingUserId()) {
4487                     throw se;
4488                 }
4489                 flags &= ~PackageManager.MATCH_ANY_USER;
4490             }
4491         } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4492                 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4493             // If the caller wants all packages and has a restricted profile associated with it,
4494             // then match all users. This is to make sure that launchers that need to access work
4495             // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4496             // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4497             flags |= PackageManager.MATCH_ANY_USER;
4498         }
4499         if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4500             Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4501                     + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4502         }
4503         return updateFlags(flags, userId);
4504     }
4505
4506     /**
4507      * Update given flags when being used to request {@link ApplicationInfo}.
4508      */
4509     private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4510         return updateFlagsForPackage(flags, userId, cookie);
4511     }
4512
4513     /**
4514      * Update given flags when being used to request {@link ComponentInfo}.
4515      */
4516     private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4517         if (cookie instanceof Intent) {
4518             if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4519                 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4520             }
4521         }
4522
4523         boolean triaged = true;
4524         // Caller is asking for component details, so they'd better be
4525         // asking for specific encryption matching behavior, or be triaged
4526         if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4527                 | PackageManager.MATCH_DIRECT_BOOT_AWARE
4528                 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4529             triaged = false;
4530         }
4531         if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4532             Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4533                     + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4534         }
4535
4536         return updateFlags(flags, userId);
4537     }
4538
4539     /**
4540      * Update given intent when being used to request {@link ResolveInfo}.
4541      */
4542     private Intent updateIntentForResolve(Intent intent) {
4543         if (intent.getSelector() != null) {
4544             intent = intent.getSelector();
4545         }
4546         if (DEBUG_PREFERRED) {
4547             intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4548         }
4549         return intent;
4550     }
4551
4552     /**
4553      * Update given flags when being used to request {@link ResolveInfo}.
4554      * <p>Instant apps are resolved specially, depending upon context. Minimally,
4555      * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4556      * flag set. However, this flag is only honoured in three circumstances:
4557      * <ul>
4558      * <li>when called from a system process</li>
4559      * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4560      * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4561      * action and a {@code android.intent.category.BROWSABLE} category</li>
4562      * </ul>
4563      */
4564     int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4565         return updateFlagsForResolve(flags, userId, intent, callingUid,
4566                 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4567     }
4568     int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4569             boolean wantInstantApps) {
4570         return updateFlagsForResolve(flags, userId, intent, callingUid,
4571                 wantInstantApps, false /*onlyExposedExplicitly*/);
4572     }
4573     int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4574             boolean wantInstantApps, boolean onlyExposedExplicitly) {
4575         // Safe mode means we shouldn't match any third-party components
4576         if (mSafeMode) {
4577             flags |= PackageManager.MATCH_SYSTEM_ONLY;
4578         }
4579         if (getInstantAppPackageName(callingUid) != null) {
4580             // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4581             if (onlyExposedExplicitly) {
4582                 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4583             }
4584             flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4585             flags |= PackageManager.MATCH_INSTANT;
4586         } else {
4587             final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4588             final boolean allowMatchInstant =
4589                     (wantInstantApps
4590                             && Intent.ACTION_VIEW.equals(intent.getAction())
4591                             && hasWebURI(intent))
4592                     || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4593             flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4594                     | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4595             if (!allowMatchInstant) {
4596                 flags &= ~PackageManager.MATCH_INSTANT;
4597             }
4598         }
4599         return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4600     }
4601
4602     @Override
4603     public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4604         return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4605     }
4606
4607     /**
4608      * Important: The provided filterCallingUid is used exclusively to filter out activities
4609      * that can be seen based on user state. It's typically the original caller uid prior
4610      * to clearing. Because it can only be provided by trusted code, it's value can be
4611      * trusted and will be used as-is; unlike userId which will be validated by this method.
4612      */
4613     private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4614             int filterCallingUid, int userId) {
4615         if (!sUserManager.exists(userId)) return null;
4616         flags = updateFlagsForComponent(flags, userId, component);
4617         enforceCrossUserPermission(Binder.getCallingUid(), userId,
4618                 false /* requireFullPermission */, false /* checkShell */, "get activity info");
4619         synchronized (mPackages) {
4620             PackageParser.Activity a = mActivities.mActivities.get(component);
4621
4622             if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4623             if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4624                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4625                 if (ps == null) return null;
4626                 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4627                     return null;
4628                 }
4629                 return PackageParser.generateActivityInfo(
4630                         a, flags, ps.readUserState(userId), userId);
4631             }
4632             if (mResolveComponentName.equals(component)) {
4633                 return PackageParser.generateActivityInfo(
4634                         mResolveActivity, flags, new PackageUserState(), userId);
4635             }
4636         }
4637         return null;
4638     }
4639
4640     @Override
4641     public boolean activitySupportsIntent(ComponentName component, Intent intent,
4642             String resolvedType) {
4643         synchronized (mPackages) {
4644             if (component.equals(mResolveComponentName)) {
4645                 // The resolver supports EVERYTHING!
4646                 return true;
4647             }
4648             final int callingUid = Binder.getCallingUid();
4649             final int callingUserId = UserHandle.getUserId(callingUid);
4650             PackageParser.Activity a = mActivities.mActivities.get(component);
4651             if (a == null) {
4652                 return false;
4653             }
4654             PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4655             if (ps == null) {
4656                 return false;
4657             }
4658             if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4659                 return false;
4660             }
4661             for (int i=0; i<a.intents.size(); i++) {
4662                 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4663                         intent.getData(), intent.getCategories(), TAG) >= 0) {
4664                     return true;
4665                 }
4666             }
4667             return false;
4668         }
4669     }
4670
4671     @Override
4672     public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4673         if (!sUserManager.exists(userId)) return null;
4674         final int callingUid = Binder.getCallingUid();
4675         flags = updateFlagsForComponent(flags, userId, component);
4676         enforceCrossUserPermission(callingUid, userId,
4677                 false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4678         synchronized (mPackages) {
4679             PackageParser.Activity a = mReceivers.mActivities.get(component);
4680             if (DEBUG_PACKAGE_INFO) Log.v(
4681                 TAG, "getReceiverInfo " + component + ": " + a);
4682             if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4683                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4684                 if (ps == null) return null;
4685                 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4686                     return null;
4687                 }
4688                 return PackageParser.generateActivityInfo(
4689                         a, flags, ps.readUserState(userId), userId);
4690             }
4691         }
4692         return null;
4693     }
4694
4695     @Override
4696     public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4697             int flags, int userId) {
4698         if (!sUserManager.exists(userId)) return null;
4699         Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4700         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4701             return null;
4702         }
4703
4704         flags = updateFlagsForPackage(flags, userId, null);
4705
4706         final boolean canSeeStaticLibraries =
4707                 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4708                         == PERMISSION_GRANTED
4709                 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4710                         == PERMISSION_GRANTED
4711                 || canRequestPackageInstallsInternal(packageName,
4712                         PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4713                         false  /* throwIfPermNotDeclared*/)
4714                 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4715                         == PERMISSION_GRANTED;
4716
4717         synchronized (mPackages) {
4718             List<SharedLibraryInfo> result = null;
4719
4720             final int libCount = mSharedLibraries.size();
4721             for (int i = 0; i < libCount; i++) {
4722                 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4723                 if (versionedLib == null) {
4724                     continue;
4725                 }
4726
4727                 final int versionCount = versionedLib.size();
4728                 for (int j = 0; j < versionCount; j++) {
4729                     SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4730                     if (!canSeeStaticLibraries && libInfo.isStatic()) {
4731                         break;
4732                     }
4733                     final long identity = Binder.clearCallingIdentity();
4734                     try {
4735                         PackageInfo packageInfo = getPackageInfoVersioned(
4736                                 libInfo.getDeclaringPackage(), flags
4737                                         | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4738                         if (packageInfo == null) {
4739                             continue;
4740                         }
4741                     } finally {
4742                         Binder.restoreCallingIdentity(identity);
4743                     }
4744
4745                     SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4746                             libInfo.getVersion(), libInfo.getType(),
4747                             libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4748                             flags, userId));
4749
4750                     if (result == null) {
4751                         result = new ArrayList<>();
4752                     }
4753                     result.add(resLibInfo);
4754                 }
4755             }
4756
4757             return result != null ? new ParceledListSlice<>(result) : null;
4758         }
4759     }
4760
4761     private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4762             SharedLibraryInfo libInfo, int flags, int userId) {
4763         List<VersionedPackage> versionedPackages = null;
4764         final int packageCount = mSettings.mPackages.size();
4765         for (int i = 0; i < packageCount; i++) {
4766             PackageSetting ps = mSettings.mPackages.valueAt(i);
4767
4768             if (ps == null) {
4769                 continue;
4770             }
4771
4772             if (!ps.getUserState().get(userId).isAvailable(flags)) {
4773                 continue;
4774             }
4775
4776             final String libName = libInfo.getName();
4777             if (libInfo.isStatic()) {
4778                 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4779                 if (libIdx < 0) {
4780                     continue;
4781                 }
4782                 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4783                     continue;
4784                 }
4785                 if (versionedPackages == null) {
4786                     versionedPackages = new ArrayList<>();
4787                 }
4788                 // If the dependent is a static shared lib, use the public package name
4789                 String dependentPackageName = ps.name;
4790                 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4791                     dependentPackageName = ps.pkg.manifestPackageName;
4792                 }
4793                 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4794             } else if (ps.pkg != null) {
4795                 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4796                         || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4797                     if (versionedPackages == null) {
4798                         versionedPackages = new ArrayList<>();
4799                     }
4800                     versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4801                 }
4802             }
4803         }
4804
4805         return versionedPackages;
4806     }
4807
4808     @Override
4809     public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4810         if (!sUserManager.exists(userId)) return null;
4811         final int callingUid = Binder.getCallingUid();
4812         flags = updateFlagsForComponent(flags, userId, component);
4813         enforceCrossUserPermission(callingUid, userId,
4814                 false /* requireFullPermission */, false /* checkShell */, "get service info");
4815         synchronized (mPackages) {
4816             PackageParser.Service s = mServices.mServices.get(component);
4817             if (DEBUG_PACKAGE_INFO) Log.v(
4818                 TAG, "getServiceInfo " + component + ": " + s);
4819             if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4820                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4821                 if (ps == null) return null;
4822                 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4823                     return null;
4824                 }
4825                 return PackageParser.generateServiceInfo(
4826                         s, flags, ps.readUserState(userId), userId);
4827             }
4828         }
4829         return null;
4830     }
4831
4832     @Override
4833     public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4834         if (!sUserManager.exists(userId)) return null;
4835         final int callingUid = Binder.getCallingUid();
4836         flags = updateFlagsForComponent(flags, userId, component);
4837         enforceCrossUserPermission(callingUid, userId,
4838                 false /* requireFullPermission */, false /* checkShell */, "get provider info");
4839         synchronized (mPackages) {
4840             PackageParser.Provider p = mProviders.mProviders.get(component);
4841             if (DEBUG_PACKAGE_INFO) Log.v(
4842                 TAG, "getProviderInfo " + component + ": " + p);
4843             if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4844                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4845                 if (ps == null) return null;
4846                 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4847                     return null;
4848                 }
4849                 return PackageParser.generateProviderInfo(
4850                         p, flags, ps.readUserState(userId), userId);
4851             }
4852         }
4853         return null;
4854     }
4855
4856     @Override
4857     public String[] getSystemSharedLibraryNames() {
4858         // allow instant applications
4859         synchronized (mPackages) {
4860             Set<String> libs = null;
4861             final int libCount = mSharedLibraries.size();
4862             for (int i = 0; i < libCount; i++) {
4863                 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4864                 if (versionedLib == null) {
4865                     continue;
4866                 }
4867                 final int versionCount = versionedLib.size();
4868                 for (int j = 0; j < versionCount; j++) {
4869                     SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4870                     if (!libEntry.info.isStatic()) {
4871                         if (libs == null) {
4872                             libs = new ArraySet<>();
4873                         }
4874                         libs.add(libEntry.info.getName());
4875                         break;
4876                     }
4877                     PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4878                     if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4879                             UserHandle.getUserId(Binder.getCallingUid()),
4880                             PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4881                         if (libs == null) {
4882                             libs = new ArraySet<>();
4883                         }
4884                         libs.add(libEntry.info.getName());
4885                         break;
4886                     }
4887                 }
4888             }
4889
4890             if (libs != null) {
4891                 String[] libsArray = new String[libs.size()];
4892                 libs.toArray(libsArray);
4893                 return libsArray;
4894             }
4895
4896             return null;
4897         }
4898     }
4899
4900     @Override
4901     public @NonNull String getServicesSystemSharedLibraryPackageName() {
4902         // allow instant applications
4903         synchronized (mPackages) {
4904             return mServicesSystemSharedLibraryPackageName;
4905         }
4906     }
4907
4908     @Override
4909     public @NonNull String getSharedSystemSharedLibraryPackageName() {
4910         // allow instant applications
4911         synchronized (mPackages) {
4912             return mSharedSystemSharedLibraryPackageName;
4913         }
4914     }
4915
4916     private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4917         for (int i = userList.length - 1; i >= 0; --i) {
4918             final int userId = userList[i];
4919             // don't add instant app to the list of updates
4920             if (pkgSetting.getInstantApp(userId)) {
4921                 continue;
4922             }
4923             SparseArray<String> changedPackages = mChangedPackages.get(userId);
4924             if (changedPackages == null) {
4925                 changedPackages = new SparseArray<>();
4926                 mChangedPackages.put(userId, changedPackages);
4927             }
4928             Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4929             if (sequenceNumbers == null) {
4930                 sequenceNumbers = new HashMap<>();
4931                 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4932             }
4933             final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4934             if (sequenceNumber != null) {
4935                 changedPackages.remove(sequenceNumber);
4936             }
4937             changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4938             sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4939         }
4940         mChangedPackagesSequenceNumber++;
4941     }
4942
4943     @Override
4944     public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4945         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4946             return null;
4947         }
4948         synchronized (mPackages) {
4949             if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4950                 return null;
4951             }
4952             final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4953             if (changedPackages == null) {
4954                 return null;
4955             }
4956             final List<String> packageNames =
4957                     new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4958             for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4959                 final String packageName = changedPackages.get(i);
4960                 if (packageName != null) {
4961                     packageNames.add(packageName);
4962                 }
4963             }
4964             return packageNames.isEmpty()
4965                     ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4966         }
4967     }
4968
4969     @Override
4970     public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4971         // allow instant applications
4972         ArrayList<FeatureInfo> res;
4973         synchronized (mAvailableFeatures) {
4974             res = new ArrayList<>(mAvailableFeatures.size() + 1);
4975             res.addAll(mAvailableFeatures.values());
4976         }
4977         final FeatureInfo fi = new FeatureInfo();
4978         fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4979                 FeatureInfo.GL_ES_VERSION_UNDEFINED);
4980         res.add(fi);
4981
4982         return new ParceledListSlice<>(res);
4983     }
4984
4985     @Override
4986     public boolean hasSystemFeature(String name, int version) {
4987         // allow instant applications
4988         synchronized (mAvailableFeatures) {
4989             final FeatureInfo feat = mAvailableFeatures.get(name);
4990             if (feat == null) {
4991                 return false;
4992             } else {
4993                 return feat.version >= version;
4994             }
4995         }
4996     }
4997
4998     @Override
4999     public int checkPermission(String permName, String pkgName, int userId) {
5000         if (!sUserManager.exists(userId)) {
5001             return PackageManager.PERMISSION_DENIED;
5002         }
5003         final int callingUid = Binder.getCallingUid();
5004
5005         synchronized (mPackages) {
5006             final PackageParser.Package p = mPackages.get(pkgName);
5007             if (p != null && p.mExtras != null) {
5008                 final PackageSetting ps = (PackageSetting) p.mExtras;
5009                 if (filterAppAccessLPr(ps, callingUid, userId)) {
5010                     return PackageManager.PERMISSION_DENIED;
5011                 }
5012                 final boolean instantApp = ps.getInstantApp(userId);
5013                 final PermissionsState permissionsState = ps.getPermissionsState();
5014                 if (permissionsState.hasPermission(permName, userId)) {
5015                     if (instantApp) {
5016                         BasePermission bp = mSettings.mPermissions.get(permName);
5017                         if (bp != null && bp.isInstant()) {
5018                             return PackageManager.PERMISSION_GRANTED;
5019                         }
5020                     } else {
5021                         return PackageManager.PERMISSION_GRANTED;
5022                     }
5023                 }
5024                 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5025                 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5026                         .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5027                     return PackageManager.PERMISSION_GRANTED;
5028                 }
5029             }
5030         }
5031
5032         return PackageManager.PERMISSION_DENIED;
5033     }
5034
5035     @Override
5036     public int checkUidPermission(String permName, int uid) {
5037         final int callingUid = Binder.getCallingUid();
5038         final int callingUserId = UserHandle.getUserId(callingUid);
5039         final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5040         final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5041         final int userId = UserHandle.getUserId(uid);
5042         if (!sUserManager.exists(userId)) {
5043             return PackageManager.PERMISSION_DENIED;
5044         }
5045
5046         synchronized (mPackages) {
5047             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5048             if (obj != null) {
5049                 if (obj instanceof SharedUserSetting) {
5050                     if (isCallerInstantApp) {
5051                         return PackageManager.PERMISSION_DENIED;
5052                     }
5053                 } else if (obj instanceof PackageSetting) {
5054                     final PackageSetting ps = (PackageSetting) obj;
5055                     if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5056                         return PackageManager.PERMISSION_DENIED;
5057                     }
5058                 }
5059                 final SettingBase settingBase = (SettingBase) obj;
5060                 final PermissionsState permissionsState = settingBase.getPermissionsState();
5061                 if (permissionsState.hasPermission(permName, userId)) {
5062                     if (isUidInstantApp) {
5063                         BasePermission bp = mSettings.mPermissions.get(permName);
5064                         if (bp != null && bp.isInstant()) {
5065                             return PackageManager.PERMISSION_GRANTED;
5066                         }
5067                     } else {
5068                         return PackageManager.PERMISSION_GRANTED;
5069                     }
5070                 }
5071                 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5072                 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5073                         .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5074                     return PackageManager.PERMISSION_GRANTED;
5075                 }
5076             } else {
5077                 ArraySet<String> perms = mSystemPermissions.get(uid);
5078                 if (perms != null) {
5079                     if (perms.contains(permName)) {
5080                         return PackageManager.PERMISSION_GRANTED;
5081                     }
5082                     if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5083                             .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5084                         return PackageManager.PERMISSION_GRANTED;
5085                     }
5086                 }
5087             }
5088         }
5089
5090         return PackageManager.PERMISSION_DENIED;
5091     }
5092
5093     @Override
5094     public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5095         if (UserHandle.getCallingUserId() != userId) {
5096             mContext.enforceCallingPermission(
5097                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5098                     "isPermissionRevokedByPolicy for user " + userId);
5099         }
5100
5101         if (checkPermission(permission, packageName, userId)
5102                 == PackageManager.PERMISSION_GRANTED) {
5103             return false;
5104         }
5105
5106         final int callingUid = Binder.getCallingUid();
5107         if (getInstantAppPackageName(callingUid) != null) {
5108             if (!isCallerSameApp(packageName, callingUid)) {
5109                 return false;
5110             }
5111         } else {
5112             if (isInstantApp(packageName, userId)) {
5113                 return false;
5114             }
5115         }
5116
5117         final long identity = Binder.clearCallingIdentity();
5118         try {
5119             final int flags = getPermissionFlags(permission, packageName, userId);
5120             return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5121         } finally {
5122             Binder.restoreCallingIdentity(identity);
5123         }
5124     }
5125
5126     @Override
5127     public String getPermissionControllerPackageName() {
5128         synchronized (mPackages) {
5129             return mRequiredInstallerPackage;
5130         }
5131     }
5132
5133     /**
5134      * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5135      * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5136      * @param checkShell whether to prevent shell from access if there's a debugging restriction
5137      * @param message the message to log on security exception
5138      */
5139     void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5140             boolean checkShell, String message) {
5141         enforceCrossUserPermission(
5142               callingUid,
5143               userId,
5144               requireFullPermission,
5145               checkShell,
5146               false,
5147               message);
5148     }
5149
5150     private void enforceCrossUserPermission(int callingUid, int userId,
5151             boolean requireFullPermission, boolean checkShell,
5152             boolean requirePermissionWhenSameUser, String message) {
5153         if (userId < 0) {
5154             throw new IllegalArgumentException("Invalid userId " + userId);
5155         }
5156         if (checkShell) {
5157             enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5158         }
5159         if (!requirePermissionWhenSameUser && userId == UserHandle.getUserId(callingUid)) return;
5160         if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5161             if (requireFullPermission) {
5162                 mContext.enforceCallingOrSelfPermission(
5163                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5164             } else {
5165                 try {
5166                     mContext.enforceCallingOrSelfPermission(
5167                             android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5168                 } catch (SecurityException se) {
5169                     mContext.enforceCallingOrSelfPermission(
5170                             android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5171                 }
5172             }
5173         }
5174     }
5175
5176     void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5177         if (callingUid == Process.SHELL_UID) {
5178             if (userHandle >= 0
5179                     && sUserManager.hasUserRestriction(restriction, userHandle)) {
5180                 throw new SecurityException("Shell does not have permission to access user "
5181                         + userHandle);
5182             } else if (userHandle < 0) {
5183                 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5184                         + Debug.getCallers(3));
5185             }
5186         }
5187     }
5188
5189     private BasePermission findPermissionTreeLP(String permName) {
5190         for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5191             if (permName.startsWith(bp.name) &&
5192                     permName.length() > bp.name.length() &&
5193                     permName.charAt(bp.name.length()) == '.') {
5194                 return bp;
5195             }
5196         }
5197         return null;
5198     }
5199
5200     private BasePermission checkPermissionTreeLP(String permName) {
5201         if (permName != null) {
5202             BasePermission bp = findPermissionTreeLP(permName);
5203             if (bp != null) {
5204                 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5205                     return bp;
5206                 }
5207                 throw new SecurityException("Calling uid "
5208                         + Binder.getCallingUid()
5209                         + " is not allowed to add to permission tree "
5210                         + bp.name + " owned by uid " + bp.uid);
5211             }
5212         }
5213         throw new SecurityException("No permission tree found for " + permName);
5214     }
5215
5216     static boolean compareStrings(CharSequence s1, CharSequence s2) {
5217         if (s1 == null) {
5218             return s2 == null;
5219         }
5220         if (s2 == null) {
5221             return false;
5222         }
5223         if (s1.getClass() != s2.getClass()) {
5224             return false;
5225         }
5226         return s1.equals(s2);
5227     }
5228
5229     static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5230         if (pi1.icon != pi2.icon) return false;
5231         if (pi1.logo != pi2.logo) return false;
5232         if (pi1.protectionLevel != pi2.protectionLevel) return false;
5233         if (!compareStrings(pi1.name, pi2.name)) return false;
5234         if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5235         // We'll take care of setting this one.
5236         if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5237         // These are not currently stored in settings.
5238         //if (!compareStrings(pi1.group, pi2.group)) return false;
5239         //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5240         //if (pi1.labelRes != pi2.labelRes) return false;
5241         //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5242         return true;
5243     }
5244
5245     int permissionInfoFootprint(PermissionInfo info) {
5246         int size = info.name.length();
5247         if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5248         if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5249         return size;
5250     }
5251
5252     int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5253         int size = 0;
5254         for (BasePermission perm : mSettings.mPermissions.values()) {
5255             if (perm.uid == tree.uid) {
5256                 size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5257             }
5258         }
5259         return size;
5260     }
5261
5262     void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5263         // We calculate the max size of permissions defined by this uid and throw
5264         // if that plus the size of 'info' would exceed our stated maximum.
5265         if (tree.uid != Process.SYSTEM_UID) {
5266             final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5267             if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5268                 throw new SecurityException("Permission tree size cap exceeded");
5269             }
5270         }
5271     }
5272
5273     boolean addPermissionLocked(PermissionInfo info, boolean async) {
5274         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5275             throw new SecurityException("Instant apps can't add permissions");
5276         }
5277         if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5278             throw new SecurityException("Label must be specified in permission");
5279         }
5280         BasePermission tree = checkPermissionTreeLP(info.name);
5281         BasePermission bp = mSettings.mPermissions.get(info.name);
5282         boolean added = bp == null;
5283         boolean changed = true;
5284         int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5285         if (added) {
5286             enforcePermissionCapLocked(info, tree);
5287             bp = new BasePermission(info.name, tree.sourcePackage,
5288                     BasePermission.TYPE_DYNAMIC);
5289         } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5290             throw new SecurityException(
5291                     "Not allowed to modify non-dynamic permission "
5292                     + info.name);
5293         } else {
5294             if (bp.protectionLevel == fixedLevel
5295                     && bp.perm.owner.equals(tree.perm.owner)
5296                     && bp.uid == tree.uid
5297                     && comparePermissionInfos(bp.perm.info, info)) {
5298                 changed = false;
5299             }
5300         }
5301         bp.protectionLevel = fixedLevel;
5302         info = new PermissionInfo(info);
5303         info.protectionLevel = fixedLevel;
5304         bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5305         bp.perm.info.packageName = tree.perm.info.packageName;
5306         bp.uid = tree.uid;
5307         if (added) {
5308             mSettings.mPermissions.put(info.name, bp);
5309         }
5310         if (changed) {
5311             if (!async) {
5312                 mSettings.writeLPr();
5313             } else {
5314                 scheduleWriteSettingsLocked();
5315             }
5316         }
5317         return added;
5318     }
5319
5320     @Override
5321     public boolean addPermission(PermissionInfo info) {
5322         synchronized (mPackages) {
5323             return addPermissionLocked(info, false);
5324         }
5325     }
5326
5327     @Override
5328     public boolean addPermissionAsync(PermissionInfo info) {
5329         synchronized (mPackages) {
5330             return addPermissionLocked(info, true);
5331         }
5332     }
5333
5334     @Override
5335     public void removePermission(String name) {
5336         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5337             throw new SecurityException("Instant applications don't have access to this method");
5338         }
5339         synchronized (mPackages) {
5340             checkPermissionTreeLP(name);
5341             BasePermission bp = mSettings.mPermissions.get(name);
5342             if (bp != null) {
5343                 if (bp.type != BasePermission.TYPE_DYNAMIC) {
5344                     throw new SecurityException(
5345                             "Not allowed to modify non-dynamic permission "
5346                             + name);
5347                 }
5348                 mSettings.mPermissions.remove(name);
5349                 mSettings.writeLPr();
5350             }
5351         }
5352     }
5353
5354     private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5355             PackageParser.Package pkg, BasePermission bp) {
5356         int index = pkg.requestedPermissions.indexOf(bp.name);
5357         if (index == -1) {
5358             throw new SecurityException("Package " + pkg.packageName
5359                     + " has not requested permission " + bp.name);
5360         }
5361         if (!bp.isRuntime() && !bp.isDevelopment()) {
5362             throw new SecurityException("Permission " + bp.name
5363                     + " is not a changeable permission type");
5364         }
5365     }
5366
5367     @Override
5368     public void grantRuntimePermission(String packageName, String name, final int userId) {
5369         grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5370     }
5371
5372     private void grantRuntimePermission(String packageName, String name, final int userId,
5373             boolean overridePolicy) {
5374         if (!sUserManager.exists(userId)) {
5375             Log.e(TAG, "No such user:" + userId);
5376             return;
5377         }
5378         final int callingUid = Binder.getCallingUid();
5379
5380         mContext.enforceCallingOrSelfPermission(
5381                 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5382                 "grantRuntimePermission");
5383
5384         enforceCrossUserPermission(callingUid, userId,
5385                 true /* requireFullPermission */, true /* checkShell */,
5386                 "grantRuntimePermission");
5387
5388         final int uid;
5389         final PackageSetting ps;
5390
5391         synchronized (mPackages) {
5392             final PackageParser.Package pkg = mPackages.get(packageName);
5393             if (pkg == null) {
5394                 throw new IllegalArgumentException("Unknown package: " + packageName);
5395             }
5396             final BasePermission bp = mSettings.mPermissions.get(name);
5397             if (bp == null) {
5398                 throw new IllegalArgumentException("Unknown permission: " + name);
5399             }
5400             ps = (PackageSetting) pkg.mExtras;
5401             if (ps == null
5402                     || filterAppAccessLPr(ps, callingUid, userId)) {
5403                 throw new IllegalArgumentException("Unknown package: " + packageName);
5404             }
5405
5406             enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5407
5408             // If a permission review is required for legacy apps we represent
5409             // their permissions as always granted runtime ones since we need
5410             // to keep the review required permission flag per user while an
5411             // install permission's state is shared across all users.
5412             if (mPermissionReviewRequired
5413                     && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5414                     && bp.isRuntime()) {
5415                 return;
5416             }
5417
5418             uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5419
5420             final PermissionsState permissionsState = ps.getPermissionsState();
5421
5422             final int flags = permissionsState.getPermissionFlags(name, userId);
5423             if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5424                 throw new SecurityException("Cannot grant system fixed permission "
5425                         + name + " for package " + packageName);
5426             }
5427             if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5428                 throw new SecurityException("Cannot grant policy fixed permission "
5429                         + name + " for package " + packageName);
5430             }
5431
5432             if (bp.isDevelopment()) {
5433                 // Development permissions must be handled specially, since they are not
5434                 // normal runtime permissions.  For now they apply to all users.
5435                 if (permissionsState.grantInstallPermission(bp) !=
5436                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
5437                     scheduleWriteSettingsLocked();
5438                 }
5439                 return;
5440             }
5441
5442             if (ps.getInstantApp(userId) && !bp.isInstant()) {
5443                 throw new SecurityException("Cannot grant non-ephemeral permission"
5444                         + name + " for package " + packageName);
5445             }
5446
5447             if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5448                 Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5449                 return;
5450             }
5451
5452             final int result = permissionsState.grantRuntimePermission(bp, userId);
5453             switch (result) {
5454                 case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5455                     return;
5456                 }
5457
5458                 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5459                     final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5460                     mHandler.post(new Runnable() {
5461                         @Override
5462                         public void run() {
5463                             killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5464                         }
5465                     });
5466                 }
5467                 break;
5468             }
5469
5470             if (bp.isRuntime()) {
5471                 logPermissionGranted(mContext, name, packageName);
5472             }
5473
5474             mOnPermissionChangeListeners.onPermissionsChanged(uid);
5475
5476             // Not critical if that is lost - app has to request again.
5477             mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5478         }
5479
5480         // Only need to do this if user is initialized. Otherwise it's a new user
5481         // and there are no processes running as the user yet and there's no need
5482         // to make an expensive call to remount processes for the changed permissions.
5483         if (READ_EXTERNAL_STORAGE.equals(name)
5484                 || WRITE_EXTERNAL_STORAGE.equals(name)) {
5485             final long token = Binder.clearCallingIdentity();
5486             try {
5487                 if (sUserManager.isInitialized(userId)) {
5488                     StorageManagerInternal storageManagerInternal = LocalServices.getService(
5489                             StorageManagerInternal.class);
5490                     storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5491                 }
5492             } finally {
5493                 Binder.restoreCallingIdentity(token);
5494             }
5495         }
5496     }
5497
5498     @Override
5499     public void revokeRuntimePermission(String packageName, String name, int userId) {
5500         revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5501     }
5502
5503     private void revokeRuntimePermission(String packageName, String name, int userId,
5504             boolean overridePolicy) {
5505         if (!sUserManager.exists(userId)) {
5506             Log.e(TAG, "No such user:" + userId);
5507             return;
5508         }
5509
5510         mContext.enforceCallingOrSelfPermission(
5511                 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5512                 "revokeRuntimePermission");
5513
5514         enforceCrossUserPermission(Binder.getCallingUid(), userId,
5515                 true /* requireFullPermission */, true /* checkShell */,
5516                 "revokeRuntimePermission");
5517
5518         final int appId;
5519
5520         synchronized (mPackages) {
5521             final PackageParser.Package pkg = mPackages.get(packageName);
5522             if (pkg == null) {
5523                 throw new IllegalArgumentException("Unknown package: " + packageName);
5524             }
5525             final PackageSetting ps = (PackageSetting) pkg.mExtras;
5526             if (ps == null
5527                     || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5528                 throw new IllegalArgumentException("Unknown package: " + packageName);
5529             }
5530             final BasePermission bp = mSettings.mPermissions.get(name);
5531             if (bp == null) {
5532                 throw new IllegalArgumentException("Unknown permission: " + name);
5533             }
5534
5535             enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5536
5537             // If a permission review is required for legacy apps we represent
5538             // their permissions as always granted runtime ones since we need
5539             // to keep the review required permission flag per user while an
5540             // install permission's state is shared across all users.
5541             if (mPermissionReviewRequired
5542                     && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5543                     && bp.isRuntime()) {
5544                 return;
5545             }
5546
5547             final PermissionsState permissionsState = ps.getPermissionsState();
5548
5549             final int flags = permissionsState.getPermissionFlags(name, userId);
5550             if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5551                 throw new SecurityException("Cannot revoke system fixed permission "
5552                         + name + " for package " + packageName);
5553             }
5554             if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5555                 throw new SecurityException("Cannot revoke policy fixed permission "
5556                         + name + " for package " + packageName);
5557             }
5558
5559             if (bp.isDevelopment()) {
5560                 // Development permissions must be handled specially, since they are not
5561                 // normal runtime permissions.  For now they apply to all users.
5562                 if (permissionsState.revokeInstallPermission(bp) !=
5563                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
5564                     scheduleWriteSettingsLocked();
5565                 }
5566                 return;
5567             }
5568
5569             if (permissionsState.revokeRuntimePermission(bp, userId) ==
5570                     PermissionsState.PERMISSION_OPERATION_FAILURE) {
5571                 return;
5572             }
5573
5574             if (bp.isRuntime()) {
5575                 logPermissionRevoked(mContext, name, packageName);
5576             }
5577
5578             mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5579
5580             // Critical, after this call app should never have the permission.
5581             mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5582
5583             appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5584         }
5585
5586         killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5587     }
5588
5589     /**
5590      * We might auto-grant permissions if any permission of the group is already granted. Hence if
5591      * the group of a granted permission changes we need to revoke it to avoid having permissions of
5592      * the new group auto-granted.
5593      *
5594      * @param newPackage The new package that was installed
5595      * @param oldPackage The old package that was updated
5596      * @param allPackageNames All package names
5597      */
5598     private void revokeRuntimePermissionsIfGroupChanged(
5599             PackageParser.Package newPackage,
5600             PackageParser.Package oldPackage,
5601             ArrayList<String> allPackageNames) {
5602         final int numOldPackagePermissions = oldPackage.permissions.size();
5603         final ArrayMap<String, String> oldPermissionNameToGroupName
5604                 = new ArrayMap<>(numOldPackagePermissions);
5605
5606         for (int i = 0; i < numOldPackagePermissions; i++) {
5607             final PackageParser.Permission permission = oldPackage.permissions.get(i);
5608
5609             if (permission.group != null) {
5610                 oldPermissionNameToGroupName.put(permission.info.name,
5611                         permission.group.info.name);
5612             }
5613         }
5614
5615         final int numNewPackagePermissions = newPackage.permissions.size();
5616         for (int newPermissionNum = 0; newPermissionNum < numNewPackagePermissions;
5617                 newPermissionNum++) {
5618             final PackageParser.Permission newPermission =
5619                     newPackage.permissions.get(newPermissionNum);
5620             final int newProtection = newPermission.info.protectionLevel;
5621
5622             if ((newProtection & PermissionInfo.PROTECTION_DANGEROUS) != 0) {
5623                 final String permissionName = newPermission.info.name;
5624                 final String newPermissionGroupName =
5625                         newPermission.group == null ? null : newPermission.group.info.name;
5626                 final String oldPermissionGroupName = oldPermissionNameToGroupName.get(
5627                         permissionName);
5628
5629                 if (newPermissionGroupName != null
5630                         && !newPermissionGroupName.equals(oldPermissionGroupName)) {
5631                     final List<UserInfo> users = mContext.getSystemService(UserManager.class)
5632                             .getUsers();
5633
5634                     final int numUsers = users.size();
5635                     for (int userNum = 0; userNum < numUsers; userNum++) {
5636                         final int userId = users.get(userNum).id;
5637                         final int numPackages = allPackageNames.size();
5638
5639                         for (int packageNum = 0; packageNum < numPackages; packageNum++) {
5640                             final String packageName = allPackageNames.get(packageNum);
5641
5642                             if (checkPermission(permissionName, packageName, userId)
5643                                     == PackageManager.PERMISSION_GRANTED) {
5644                                 EventLog.writeEvent(0x534e4554, "72710897",
5645                                         newPackage.applicationInfo.uid,
5646                                         "Revoking permission", permissionName, "from package",
5647                                         packageName, "as the group changed from",
5648                                         oldPermissionGroupName, "to", newPermissionGroupName);
5649
5650                                 try {
5651                                     revokeRuntimePermission(packageName, permissionName, userId,
5652                                            false);
5653                                 } catch (IllegalArgumentException e) {
5654                                     Slog.e(TAG, "Could not revoke " + permissionName + " from "
5655                                             + packageName, e);
5656                                 }
5657                             }
5658                         }
5659                     }
5660                 }
5661             }
5662         }
5663     }
5664
5665
5666     /**
5667      * Get the first event id for the permission.
5668      *
5669      * <p>There are four events for each permission: <ul>
5670      *     <li>Request permission: first id + 0</li>
5671      *     <li>Grant permission: first id + 1</li>
5672      *     <li>Request for permission denied: first id + 2</li>
5673      *     <li>Revoke permission: first id + 3</li>
5674      * </ul></p>
5675      *
5676      * @param name name of the permission
5677      *
5678      * @return The first event id for the permission
5679      */
5680     private static int getBaseEventId(@NonNull String name) {
5681         int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5682
5683         if (eventIdIndex == -1) {
5684             if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5685                     || "user".equals(Build.TYPE)) {
5686                 Log.i(TAG, "Unknown permission " + name);
5687
5688                 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5689             } else {
5690                 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5691                 //
5692                 // Also update
5693                 // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5694                 // - metrics_constants.proto
5695                 throw new IllegalStateException("Unknown permission " + name);
5696             }
5697         }
5698
5699         return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5700     }
5701
5702     /**
5703      * Log that a permission was revoked.
5704      *
5705      * @param context Context of the caller
5706      * @param name name of the permission
5707      * @param packageName package permission if for
5708      */
5709     private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5710             @NonNull String packageName) {
5711         MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5712     }
5713
5714     /**
5715      * Log that a permission request was granted.
5716      *
5717      * @param context Context of the caller
5718      * @param name name of the permission
5719      * @param packageName package permission if for
5720      */
5721     private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5722             @NonNull String packageName) {
5723         MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5724     }
5725
5726     @Override
5727     public void resetRuntimePermissions() {
5728         mContext.enforceCallingOrSelfPermission(
5729                 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5730                 "revokeRuntimePermission");
5731
5732         int callingUid = Binder.getCallingUid();
5733         if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5734             mContext.enforceCallingOrSelfPermission(
5735                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5736                     "resetRuntimePermissions");
5737         }
5738
5739         synchronized (mPackages) {
5740             updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5741             for (int userId : UserManagerService.getInstance().getUserIds()) {
5742                 final int packageCount = mPackages.size();
5743                 for (int i = 0; i < packageCount; i++) {
5744                     PackageParser.Package pkg = mPackages.valueAt(i);
5745                     if (!(pkg.mExtras instanceof PackageSetting)) {
5746                         continue;
5747                     }
5748                     PackageSetting ps = (PackageSetting) pkg.mExtras;
5749                     resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5750                 }
5751             }
5752         }
5753     }
5754
5755     @Override
5756     public int getPermissionFlags(String name, String packageName, int userId) {
5757         if (!sUserManager.exists(userId)) {
5758             return 0;
5759         }
5760
5761         enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5762
5763         final int callingUid = Binder.getCallingUid();
5764         enforceCrossUserPermission(callingUid, userId,
5765                 true /* requireFullPermission */, false /* checkShell */,
5766                 "getPermissionFlags");
5767
5768         synchronized (mPackages) {
5769             final PackageParser.Package pkg = mPackages.get(packageName);
5770             if (pkg == null) {
5771                 return 0;
5772             }
5773             final BasePermission bp = mSettings.mPermissions.get(name);
5774             if (bp == null) {
5775                 return 0;
5776             }
5777             final PackageSetting ps = (PackageSetting) pkg.mExtras;
5778             if (ps == null
5779                     || filterAppAccessLPr(ps, callingUid, userId)) {
5780                 return 0;
5781             }
5782             PermissionsState permissionsState = ps.getPermissionsState();
5783             return permissionsState.getPermissionFlags(name, userId);
5784         }
5785     }
5786
5787     @Override
5788     public void updatePermissionFlags(String name, String packageName, int flagMask,
5789             int flagValues, int userId) {
5790         if (!sUserManager.exists(userId)) {
5791             return;
5792         }
5793
5794         enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5795
5796         final int callingUid = Binder.getCallingUid();
5797         enforceCrossUserPermission(callingUid, userId,
5798                 true /* requireFullPermission */, true /* checkShell */,
5799                 "updatePermissionFlags");
5800
5801         // Only the system can change these flags and nothing else.
5802         if (getCallingUid() != Process.SYSTEM_UID) {
5803             flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5804             flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5805             flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5806             flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5807             flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5808         }
5809
5810         synchronized (mPackages) {
5811             final PackageParser.Package pkg = mPackages.get(packageName);
5812             if (pkg == null) {
5813                 throw new IllegalArgumentException("Unknown package: " + packageName);
5814             }
5815             final PackageSetting ps = (PackageSetting) pkg.mExtras;
5816             if (ps == null
5817                     || filterAppAccessLPr(ps, callingUid, userId)) {
5818                 throw new IllegalArgumentException("Unknown package: " + packageName);
5819             }
5820
5821             final BasePermission bp = mSettings.mPermissions.get(name);
5822             if (bp == null) {
5823                 throw new IllegalArgumentException("Unknown permission: " + name);
5824             }
5825
5826             PermissionsState permissionsState = ps.getPermissionsState();
5827
5828             boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5829
5830             if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5831                 // Install and runtime permissions are stored in different places,
5832                 // so figure out what permission changed and persist the change.
5833                 if (permissionsState.getInstallPermissionState(name) != null) {
5834                     scheduleWriteSettingsLocked();
5835                 } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5836                         || hadState) {
5837                     mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5838                 }
5839             }
5840         }
5841     }
5842
5843     /**
5844      * Update the permission flags for all packages and runtime permissions of a user in order
5845      * to allow device or profile owner to remove POLICY_FIXED.
5846      */
5847     @Override
5848     public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5849         if (!sUserManager.exists(userId)) {
5850             return;
5851         }
5852
5853         enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5854
5855         enforceCrossUserPermission(Binder.getCallingUid(), userId,
5856                 true /* requireFullPermission */, true /* checkShell */,
5857                 "updatePermissionFlagsForAllApps");
5858
5859         // Only the system can change system fixed flags.
5860         if (getCallingUid() != Process.SYSTEM_UID) {
5861             flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5862             flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5863         }
5864
5865         synchronized (mPackages) {
5866             boolean changed = false;
5867             final int packageCount = mPackages.size();
5868             for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5869                 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5870                 final PackageSetting ps = (PackageSetting) pkg.mExtras;
5871                 if (ps == null) {
5872                     continue;
5873                 }
5874                 PermissionsState permissionsState = ps.getPermissionsState();
5875                 changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5876                         userId, flagMask, flagValues);
5877             }
5878             if (changed) {
5879                 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5880             }
5881         }
5882     }
5883
5884     private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5885         if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5886                 != PackageManager.PERMISSION_GRANTED
5887             && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5888                 != PackageManager.PERMISSION_GRANTED) {
5889             throw new SecurityException(message + " requires "
5890                     + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5891                     + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5892         }
5893     }
5894
5895     @Override
5896     public boolean shouldShowRequestPermissionRationale(String permissionName,
5897             String packageName, int userId) {
5898         if (UserHandle.getCallingUserId() != userId) {
5899             mContext.enforceCallingPermission(
5900                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5901                     "canShowRequestPermissionRationale for user " + userId);
5902         }
5903
5904         final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5905         if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5906             return false;
5907         }
5908
5909         if (checkPermission(permissionName, packageName, userId)
5910                 == PackageManager.PERMISSION_GRANTED) {
5911             return false;
5912         }
5913
5914         final int flags;
5915
5916         final long identity = Binder.clearCallingIdentity();
5917         try {
5918             flags = getPermissionFlags(permissionName,
5919                     packageName, userId);
5920         } finally {
5921             Binder.restoreCallingIdentity(identity);
5922         }
5923
5924         final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5925                 | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5926                 | PackageManager.FLAG_PERMISSION_USER_FIXED;
5927
5928         if ((flags & fixedFlags) != 0) {
5929             return false;
5930         }
5931
5932         return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5933     }
5934
5935     @Override
5936     public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5937         mContext.enforceCallingOrSelfPermission(
5938                 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5939                 "addOnPermissionsChangeListener");
5940
5941         synchronized (mPackages) {
5942             mOnPermissionChangeListeners.addListenerLocked(listener);
5943         }
5944     }
5945
5946     @Override
5947     public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5948         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5949             throw new SecurityException("Instant applications don't have access to this method");
5950         }
5951         synchronized (mPackages) {
5952             mOnPermissionChangeListeners.removeListenerLocked(listener);
5953         }
5954     }
5955
5956     @Override
5957     public boolean isProtectedBroadcast(String actionName) {
5958         // allow instant applications
5959         synchronized (mPackages) {
5960             if (mProtectedBroadcasts.contains(actionName)) {
5961                 return true;
5962             } else if (actionName != null) {
5963                 // TODO: remove these terrible hacks
5964                 if (actionName.startsWith("android.net.netmon.lingerExpired")
5965                         || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5966                         || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5967                         || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5968                     return true;
5969                 }
5970             }
5971         }
5972         return false;
5973     }
5974
5975     @Override
5976     public int checkSignatures(String pkg1, String pkg2) {
5977         synchronized (mPackages) {
5978             final PackageParser.Package p1 = mPackages.get(pkg1);
5979             final PackageParser.Package p2 = mPackages.get(pkg2);
5980             if (p1 == null || p1.mExtras == null
5981                     || p2 == null || p2.mExtras == null) {
5982                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5983             }
5984             final int callingUid = Binder.getCallingUid();
5985             final int callingUserId = UserHandle.getUserId(callingUid);
5986             final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5987             final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5988             if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5989                     || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5990                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5991             }
5992             return compareSignatures(p1.mSignatures, p2.mSignatures);
5993         }
5994     }
5995
5996     @Override
5997     public int checkUidSignatures(int uid1, int uid2) {
5998         final int callingUid = Binder.getCallingUid();
5999         final int callingUserId = UserHandle.getUserId(callingUid);
6000         final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6001         // Map to base uids.
6002         uid1 = UserHandle.getAppId(uid1);
6003         uid2 = UserHandle.getAppId(uid2);
6004         // reader
6005         synchronized (mPackages) {
6006             Signature[] s1;
6007             Signature[] s2;
6008             Object obj = mSettings.getUserIdLPr(uid1);
6009             if (obj != null) {
6010                 if (obj instanceof SharedUserSetting) {
6011                     if (isCallerInstantApp) {
6012                         return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6013                     }
6014                     s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6015                 } else if (obj instanceof PackageSetting) {
6016                     final PackageSetting ps = (PackageSetting) obj;
6017                     if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6018                         return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6019                     }
6020                     s1 = ps.signatures.mSignatures;
6021                 } else {
6022                     return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6023                 }
6024             } else {
6025                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6026             }
6027             obj = mSettings.getUserIdLPr(uid2);
6028             if (obj != null) {
6029                 if (obj instanceof SharedUserSetting) {
6030                     if (isCallerInstantApp) {
6031                         return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6032                     }
6033                     s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6034                 } else if (obj instanceof PackageSetting) {
6035                     final PackageSetting ps = (PackageSetting) obj;
6036                     if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6037                         return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6038                     }
6039                     s2 = ps.signatures.mSignatures;
6040                 } else {
6041                     return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6042                 }
6043             } else {
6044                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6045             }
6046             return compareSignatures(s1, s2);
6047         }
6048     }
6049
6050     /**
6051      * This method should typically only be used when granting or revoking
6052      * permissions, since the app may immediately restart after this call.
6053      * <p>
6054      * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6055      * guard your work against the app being relaunched.
6056      */
6057     private void killUid(int appId, int userId, String reason) {
6058         final long identity = Binder.clearCallingIdentity();
6059         try {
6060             IActivityManager am = ActivityManager.getService();
6061             if (am != null) {
6062                 try {
6063                     am.killUid(appId, userId, reason);
6064                 } catch (RemoteException e) {
6065                     /* ignore - same process */
6066                 }
6067             }
6068         } finally {
6069             Binder.restoreCallingIdentity(identity);
6070         }
6071     }
6072
6073     /**
6074      * Compares two sets of signatures. Returns:
6075      * <br />
6076      * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6077      * <br />
6078      * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6079      * <br />
6080      * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6081      * <br />
6082      * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6083      * <br />
6084      * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6085      */
6086     static int compareSignatures(Signature[] s1, Signature[] s2) {
6087         if (s1 == null) {
6088             return s2 == null
6089                     ? PackageManager.SIGNATURE_NEITHER_SIGNED
6090                     : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6091         }
6092
6093         if (s2 == null) {
6094             return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6095         }
6096
6097         if (s1.length != s2.length) {
6098             return PackageManager.SIGNATURE_NO_MATCH;
6099         }
6100
6101         // Since both signature sets are of size 1, we can compare without HashSets.
6102         if (s1.length == 1) {
6103             return s1[0].equals(s2[0]) ?
6104                     PackageManager.SIGNATURE_MATCH :
6105                     PackageManager.SIGNATURE_NO_MATCH;
6106         }
6107
6108         ArraySet<Signature> set1 = new ArraySet<Signature>();
6109         for (Signature sig : s1) {
6110             set1.add(sig);
6111         }
6112         ArraySet<Signature> set2 = new ArraySet<Signature>();
6113         for (Signature sig : s2) {
6114             set2.add(sig);
6115         }
6116         // Make sure s2 contains all signatures in s1.
6117         if (set1.equals(set2)) {
6118             return PackageManager.SIGNATURE_MATCH;
6119         }
6120         return PackageManager.SIGNATURE_NO_MATCH;
6121     }
6122
6123     /**
6124      * If the database version for this type of package (internal storage or
6125      * external storage) is less than the version where package signatures
6126      * were updated, return true.
6127      */
6128     private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6129         final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6130         return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6131     }
6132
6133     /**
6134      * Used for backward compatibility to make sure any packages with
6135      * certificate chains get upgraded to the new style. {@code existingSigs}
6136      * will be in the old format (since they were stored on disk from before the
6137      * system upgrade) and {@code scannedSigs} will be in the newer format.
6138      */
6139     private int compareSignaturesCompat(PackageSignatures existingSigs,
6140             PackageParser.Package scannedPkg) {
6141         if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6142             return PackageManager.SIGNATURE_NO_MATCH;
6143         }
6144
6145         ArraySet<Signature> existingSet = new ArraySet<Signature>();
6146         for (Signature sig : existingSigs.mSignatures) {
6147             existingSet.add(sig);
6148         }
6149         ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6150         for (Signature sig : scannedPkg.mSignatures) {
6151             try {
6152                 Signature[] chainSignatures = sig.getChainSignatures();
6153                 for (Signature chainSig : chainSignatures) {
6154                     scannedCompatSet.add(chainSig);
6155                 }
6156             } catch (CertificateEncodingException e) {
6157                 scannedCompatSet.add(sig);
6158             }
6159         }
6160         /*
6161          * Make sure the expanded scanned set contains all signatures in the
6162          * existing one.
6163          */
6164         if (scannedCompatSet.equals(existingSet)) {
6165             // Migrate the old signatures to the new scheme.
6166             existingSigs.assignSignatures(scannedPkg.mSignatures);
6167             // The new KeySets will be re-added later in the scanning process.
6168             synchronized (mPackages) {
6169                 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6170             }
6171             return PackageManager.SIGNATURE_MATCH;
6172         }
6173         return PackageManager.SIGNATURE_NO_MATCH;
6174     }
6175
6176     private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6177         final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6178         return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6179     }
6180
6181     private int compareSignaturesRecover(PackageSignatures existingSigs,
6182             PackageParser.Package scannedPkg) {
6183         if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6184             return PackageManager.SIGNATURE_NO_MATCH;
6185         }
6186
6187         String msg = null;
6188         try {
6189             if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6190                 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6191                         + scannedPkg.packageName);
6192                 return PackageManager.SIGNATURE_MATCH;
6193             }
6194         } catch (CertificateException e) {
6195             msg = e.getMessage();
6196         }
6197
6198         logCriticalInfo(Log.INFO,
6199                 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6200         return PackageManager.SIGNATURE_NO_MATCH;
6201     }
6202
6203     @Override
6204     public List<String> getAllPackages() {
6205         final int callingUid = Binder.getCallingUid();
6206         final int callingUserId = UserHandle.getUserId(callingUid);
6207         synchronized (mPackages) {
6208             if (canViewInstantApps(callingUid, callingUserId)) {
6209                 return new ArrayList<String>(mPackages.keySet());
6210             }
6211             final String instantAppPkgName = getInstantAppPackageName(callingUid);
6212             final List<String> result = new ArrayList<>();
6213             if (instantAppPkgName != null) {
6214                 // caller is an instant application; filter unexposed applications
6215                 for (PackageParser.Package pkg : mPackages.values()) {
6216                     if (!pkg.visibleToInstantApps) {
6217                         continue;
6218                     }
6219                     result.add(pkg.packageName);
6220                 }
6221             } else {
6222                 // caller is a normal application; filter instant applications
6223                 for (PackageParser.Package pkg : mPackages.values()) {
6224                     final PackageSetting ps =
6225                             pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6226                     if (ps != null
6227                             && ps.getInstantApp(callingUserId)
6228                             && !mInstantAppRegistry.isInstantAccessGranted(
6229                                     callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6230                         continue;
6231                     }
6232                     result.add(pkg.packageName);
6233                 }
6234             }
6235             return result;
6236         }
6237     }
6238
6239     @Override
6240     public String[] getPackagesForUid(int uid) {
6241         final int callingUid = Binder.getCallingUid();
6242         final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6243         final int userId = UserHandle.getUserId(uid);
6244         uid = UserHandle.getAppId(uid);
6245         // reader
6246         synchronized (mPackages) {
6247             Object obj = mSettings.getUserIdLPr(uid);
6248             if (obj instanceof SharedUserSetting) {
6249                 if (isCallerInstantApp) {
6250                     return null;
6251                 }
6252                 final SharedUserSetting sus = (SharedUserSetting) obj;
6253                 final int N = sus.packages.size();
6254                 String[] res = new String[N];
6255                 final Iterator<PackageSetting> it = sus.packages.iterator();
6256                 int i = 0;
6257                 while (it.hasNext()) {
6258                     PackageSetting ps = it.next();
6259                     if (ps.getInstalled(userId)) {
6260                         res[i++] = ps.name;
6261                     } else {
6262                         res = ArrayUtils.removeElement(String.class, res, res[i]);
6263                     }
6264                 }
6265                 return res;
6266             } else if (obj instanceof PackageSetting) {
6267                 final PackageSetting ps = (PackageSetting) obj;
6268                 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6269                     return new String[]{ps.name};
6270                 }
6271             }
6272         }
6273         return null;
6274     }
6275
6276     @Override
6277     public String getNameForUid(int uid) {
6278         final int callingUid = Binder.getCallingUid();
6279         if (getInstantAppPackageName(callingUid) != null) {
6280             return null;
6281         }
6282         synchronized (mPackages) {
6283             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6284             if (obj instanceof SharedUserSetting) {
6285                 final SharedUserSetting sus = (SharedUserSetting) obj;
6286                 return sus.name + ":" + sus.userId;
6287             } else if (obj instanceof PackageSetting) {
6288                 final PackageSetting ps = (PackageSetting) obj;
6289                 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6290                     return null;
6291                 }
6292                 return ps.name;
6293             }
6294         }
6295         return null;
6296     }
6297
6298     @Override
6299     public int getUidForSharedUser(String sharedUserName) {
6300         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6301             return -1;
6302         }
6303         if (sharedUserName == null) {
6304             return -1;
6305         }
6306         // reader
6307         synchronized (mPackages) {
6308             SharedUserSetting suid;
6309             try {
6310                 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6311                 if (suid != null) {
6312                     return suid.userId;
6313                 }
6314             } catch (PackageManagerException ignore) {
6315                 // can't happen, but, still need to catch it
6316             }
6317             return -1;
6318         }
6319     }
6320
6321     @Override
6322     public int getFlagsForUid(int uid) {
6323         final int callingUid = Binder.getCallingUid();
6324         if (getInstantAppPackageName(callingUid) != null) {
6325             return 0;
6326         }
6327         synchronized (mPackages) {
6328             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6329             if (obj instanceof SharedUserSetting) {
6330                 final SharedUserSetting sus = (SharedUserSetting) obj;
6331                 return sus.pkgFlags;
6332             } else if (obj instanceof PackageSetting) {
6333                 final PackageSetting ps = (PackageSetting) obj;
6334                 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6335                     return 0;
6336                 }
6337                 return ps.pkgFlags;
6338             }
6339         }
6340         return 0;
6341     }
6342
6343     @Override
6344     public int getPrivateFlagsForUid(int uid) {
6345         final int callingUid = Binder.getCallingUid();
6346         if (getInstantAppPackageName(callingUid) != null) {
6347             return 0;
6348         }
6349         synchronized (mPackages) {
6350             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6351             if (obj instanceof SharedUserSetting) {
6352                 final SharedUserSetting sus = (SharedUserSetting) obj;
6353                 return sus.pkgPrivateFlags;
6354             } else if (obj instanceof PackageSetting) {
6355                 final PackageSetting ps = (PackageSetting) obj;
6356                 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6357                     return 0;
6358                 }
6359                 return ps.pkgPrivateFlags;
6360             }
6361         }
6362         return 0;
6363     }
6364
6365     @Override
6366     public boolean isUidPrivileged(int uid) {
6367         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6368             return false;
6369         }
6370         uid = UserHandle.getAppId(uid);
6371         // reader
6372         synchronized (mPackages) {
6373             Object obj = mSettings.getUserIdLPr(uid);
6374             if (obj instanceof SharedUserSetting) {
6375                 final SharedUserSetting sus = (SharedUserSetting) obj;
6376                 final Iterator<PackageSetting> it = sus.packages.iterator();
6377                 while (it.hasNext()) {
6378                     if (it.next().isPrivileged()) {
6379                         return true;
6380                     }
6381                 }
6382             } else if (obj instanceof PackageSetting) {
6383                 final PackageSetting ps = (PackageSetting) obj;
6384                 return ps.isPrivileged();
6385             }
6386         }
6387         return false;
6388     }
6389
6390     @Override
6391     public String[] getAppOpPermissionPackages(String permissionName) {
6392         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6393             return null;
6394         }
6395         synchronized (mPackages) {
6396             ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6397             if (pkgs == null) {
6398                 return null;
6399             }
6400             return pkgs.toArray(new String[pkgs.size()]);
6401         }
6402     }
6403
6404     @Override
6405     public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6406             int flags, int userId) {
6407         return resolveIntentInternal(
6408                 intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6409     }
6410
6411     private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6412             int flags, int userId, boolean resolveForStart) {
6413         try {
6414             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6415
6416             if (!sUserManager.exists(userId)) return null;
6417             final int callingUid = Binder.getCallingUid();
6418             flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6419             enforceCrossUserPermission(callingUid, userId,
6420                     false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6421
6422             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6423             final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6424                     flags, callingUid, userId, resolveForStart);
6425             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6426
6427             final ResolveInfo bestChoice =
6428                     chooseBestActivity(intent, resolvedType, flags, query, userId);
6429             return bestChoice;
6430         } finally {
6431             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6432         }
6433     }
6434
6435     @Override
6436     public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6437         if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6438             throw new SecurityException(
6439                     "findPersistentPreferredActivity can only be run by the system");
6440         }
6441         if (!sUserManager.exists(userId)) {
6442             return null;
6443         }
6444         final int callingUid = Binder.getCallingUid();
6445         intent = updateIntentForResolve(intent);
6446         final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6447         final int flags = updateFlagsForResolve(
6448                 0, userId, intent, callingUid, false /*includeInstantApps*/);
6449         final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6450                 userId);
6451         synchronized (mPackages) {
6452             return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6453                     userId);
6454         }
6455     }
6456
6457     @Override
6458     public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6459             IntentFilter filter, int match, ComponentName activity) {
6460         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6461             return;
6462         }
6463         final int userId = UserHandle.getCallingUserId();
6464         if (DEBUG_PREFERRED) {
6465             Log.v(TAG, "setLastChosenActivity intent=" + intent
6466                 + " resolvedType=" + resolvedType
6467                 + " flags=" + flags
6468                 + " filter=" + filter
6469                 + " match=" + match
6470                 + " activity=" + activity);
6471             filter.dump(new PrintStreamPrinter(System.out), "    ");
6472         }
6473         intent.setComponent(null);
6474         final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6475                 userId);
6476         // Find any earlier preferred or last chosen entries and nuke them
6477         findPreferredActivity(intent, resolvedType,
6478                 flags, query, 0, false, true, false, userId);
6479         // Add the new activity as the last chosen for this filter
6480         addPreferredActivityInternal(filter, match, null, activity, false, userId,
6481                 "Setting last chosen");
6482     }
6483
6484     @Override
6485     public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6486         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6487             return null;
6488         }
6489         final int userId = UserHandle.getCallingUserId();
6490         if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6491         final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6492                 userId);
6493         return findPreferredActivity(intent, resolvedType, flags, query, 0,
6494                 false, false, false, userId);
6495     }
6496
6497     /**
6498      * Returns whether or not instant apps have been disabled remotely.
6499      */
6500     private boolean isEphemeralDisabled() {
6501         return mEphemeralAppsDisabled;
6502     }
6503
6504     private boolean isInstantAppAllowed(
6505             Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6506             boolean skipPackageCheck) {
6507         if (mInstantAppResolverConnection == null) {
6508             return false;
6509         }
6510         if (mInstantAppInstallerActivity == null) {
6511             return false;
6512         }
6513         if (intent.getComponent() != null) {
6514             return false;
6515         }
6516         if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6517             return false;
6518         }
6519         if (!skipPackageCheck && intent.getPackage() != null) {
6520             return false;
6521         }
6522         final boolean isWebUri = hasWebURI(intent);
6523         if (!isWebUri || intent.getData().getHost() == null) {
6524             return false;
6525         }
6526         // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6527         // Or if there's already an ephemeral app installed that handles the action
6528         synchronized (mPackages) {
6529             final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6530             for (int n = 0; n < count; n++) {
6531                 final ResolveInfo info = resolvedActivities.get(n);
6532                 final String packageName = info.activityInfo.packageName;
6533                 final PackageSetting ps = mSettings.mPackages.get(packageName);
6534                 if (ps != null) {
6535                     // only check domain verification status if the app is not a browser
6536                     if (!info.handleAllWebDataURI) {
6537                         // Try to get the status from User settings first
6538                         final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6539                         final int status = (int) (packedStatus >> 32);
6540                         if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6541                             || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6542                             if (DEBUG_EPHEMERAL) {
6543                                 Slog.v(TAG, "DENY instant app;"
6544                                     + " pkg: " + packageName + ", status: " + status);
6545                             }
6546                             return false;
6547                         }
6548                     }
6549                     if (ps.getInstantApp(userId)) {
6550                         if (DEBUG_EPHEMERAL) {
6551                             Slog.v(TAG, "DENY instant app installed;"
6552                                     + " pkg: " + packageName);
6553                         }
6554                         return false;
6555                     }
6556                 }
6557             }
6558         }
6559         // We've exhausted all ways to deny ephemeral application; let the system look for them.
6560         return true;
6561     }
6562
6563     private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6564             Intent origIntent, String resolvedType, String callingPackage,
6565             Bundle verificationBundle, int userId) {
6566         final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6567                 new InstantAppRequest(responseObj, origIntent, resolvedType,
6568                         callingPackage, userId, verificationBundle));
6569         mHandler.sendMessage(msg);
6570     }
6571
6572     private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6573             int flags, List<ResolveInfo> query, int userId) {
6574         if (query != null) {
6575             final int N = query.size();
6576             if (N == 1) {
6577                 return query.get(0);
6578             } else if (N > 1) {
6579                 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6580                 // If there is more than one activity with the same priority,
6581                 // then let the user decide between them.
6582                 ResolveInfo r0 = query.get(0);
6583                 ResolveInfo r1 = query.get(1);
6584                 if (DEBUG_INTENT_MATCHING || debug) {
6585                     Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6586                             + r1.activityInfo.name + "=" + r1.priority);
6587                 }
6588                 // If the first activity has a higher priority, or a different
6589                 // default, then it is always desirable to pick it.
6590                 if (r0.priority != r1.priority
6591                         || r0.preferredOrder != r1.preferredOrder
6592                         || r0.isDefault != r1.isDefault) {
6593                     return query.get(0);
6594                 }
6595                 // If we have saved a preference for a preferred activity for
6596                 // this Intent, use that.
6597                 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6598                         flags, query, r0.priority, true, false, debug, userId);
6599                 if (ri != null) {
6600                     return ri;
6601                 }
6602                 // If we have an ephemeral app, use it
6603                 for (int i = 0; i < N; i++) {
6604                     ri = query.get(i);
6605                     if (ri.activityInfo.applicationInfo.isInstantApp()) {
6606                         final String packageName = ri.activityInfo.packageName;
6607                         final PackageSetting ps = mSettings.mPackages.get(packageName);
6608                         final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6609                         final int status = (int)(packedStatus >> 32);
6610                         if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6611                             return ri;
6612                         }
6613                     }
6614                 }
6615                 ri = new ResolveInfo(mResolveInfo);
6616                 ri.activityInfo = new ActivityInfo(ri.activityInfo);
6617                 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6618                 // If all of the options come from the same package, show the application's
6619                 // label and icon instead of the generic resolver's.
6620                 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6621                 // and then throw away the ResolveInfo itself, meaning that the caller loses
6622                 // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6623                 // a fallback for this case; we only set the target package's resources on
6624                 // the ResolveInfo, not the ActivityInfo.
6625                 final String intentPackage = intent.getPackage();
6626                 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6627                     final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6628                     ri.resolvePackageName = intentPackage;
6629                     if (userNeedsBadging(userId)) {
6630                         ri.noResourceId = true;
6631                     } else {
6632                         ri.icon = appi.icon;
6633                     }
6634                     ri.iconResourceId = appi.icon;
6635                     ri.labelRes = appi.labelRes;
6636                 }
6637                 ri.activityInfo.applicationInfo = new ApplicationInfo(
6638                         ri.activityInfo.applicationInfo);
6639                 if (userId != 0) {
6640                     ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6641                             UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6642                 }
6643                 // Make sure that the resolver is displayable in car mode
6644                 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6645                 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6646                 return ri;
6647             }
6648         }
6649         return null;
6650     }
6651
6652     /**
6653      * Return true if the given list is not empty and all of its contents have
6654      * an activityInfo with the given package name.
6655      */
6656     private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6657         if (ArrayUtils.isEmpty(list)) {
6658             return false;
6659         }
6660         for (int i = 0, N = list.size(); i < N; i++) {
6661             final ResolveInfo ri = list.get(i);
6662             final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6663             if (ai == null || !packageName.equals(ai.packageName)) {
6664                 return false;
6665             }
6666         }
6667         return true;
6668     }
6669
6670     private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6671             int flags, List<ResolveInfo> query, boolean debug, int userId) {
6672         final int N = query.size();
6673         PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6674                 .get(userId);
6675         // Get the list of persistent preferred activities that handle the intent
6676         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6677         List<PersistentPreferredActivity> pprefs = ppir != null
6678                 ? ppir.queryIntent(intent, resolvedType,
6679                         (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6680                         userId)
6681                 : null;
6682         if (pprefs != null && pprefs.size() > 0) {
6683             final int M = pprefs.size();
6684             for (int i=0; i<M; i++) {
6685                 final PersistentPreferredActivity ppa = pprefs.get(i);
6686                 if (DEBUG_PREFERRED || debug) {
6687                     Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6688                             + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6689                             + "\n  component=" + ppa.mComponent);
6690                     ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6691                 }
6692                 final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6693                         flags | MATCH_DISABLED_COMPONENTS, userId);
6694                 if (DEBUG_PREFERRED || debug) {
6695                     Slog.v(TAG, "Found persistent preferred activity:");
6696                     if (ai != null) {
6697                         ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6698                     } else {
6699                         Slog.v(TAG, "  null");
6700                     }
6701                 }
6702                 if (ai == null) {
6703                     // This previously registered persistent preferred activity
6704                     // component is no longer known. Ignore it and do NOT remove it.
6705                     continue;
6706                 }
6707                 for (int j=0; j<N; j++) {
6708                     final ResolveInfo ri = query.get(j);
6709                     if (!ri.activityInfo.applicationInfo.packageName
6710                             .equals(ai.applicationInfo.packageName)) {
6711                         continue;
6712                     }
6713                     if (!ri.activityInfo.name.equals(ai.name)) {
6714                         continue;
6715                     }
6716                     //  Found a persistent preference that can handle the intent.
6717                     if (DEBUG_PREFERRED || debug) {
6718                         Slog.v(TAG, "Returning persistent preferred activity: " +
6719                                 ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6720                     }
6721                     return ri;
6722                 }
6723             }
6724         }
6725         return null;
6726     }
6727
6728     // TODO: handle preferred activities missing while user has amnesia
6729     ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6730             List<ResolveInfo> query, int priority, boolean always,
6731             boolean removeMatches, boolean debug, int userId) {
6732         if (!sUserManager.exists(userId)) return null;
6733         final int callingUid = Binder.getCallingUid();
6734         flags = updateFlagsForResolve(
6735                 flags, userId, intent, callingUid, false /*includeInstantApps*/);
6736         intent = updateIntentForResolve(intent);
6737         // writer
6738         synchronized (mPackages) {
6739             // Try to find a matching persistent preferred activity.
6740             ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6741                     debug, userId);
6742
6743             // If a persistent preferred activity matched, use it.
6744             if (pri != null) {
6745                 return pri;
6746             }
6747
6748             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6749             // Get the list of preferred activities that handle the intent
6750             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6751             List<PreferredActivity> prefs = pir != null
6752                     ? pir.queryIntent(intent, resolvedType,
6753                             (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6754                             userId)
6755                     : null;
6756             if (prefs != null && prefs.size() > 0) {
6757                 boolean changed = false;
6758                 try {
6759                     // First figure out how good the original match set is.
6760                     // We will only allow preferred activities that came
6761                     // from the same match quality.
6762                     int match = 0;
6763
6764                     if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6765
6766                     final int N = query.size();
6767                     for (int j=0; j<N; j++) {
6768                         final ResolveInfo ri = query.get(j);
6769                         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6770                                 + ": 0x" + Integer.toHexString(match));
6771                         if (ri.match > match) {
6772                             match = ri.match;
6773                         }
6774                     }
6775
6776                     if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6777                             + Integer.toHexString(match));
6778
6779                     match &= IntentFilter.MATCH_CATEGORY_MASK;
6780                     final int M = prefs.size();
6781                     for (int i=0; i<M; i++) {
6782                         final PreferredActivity pa = prefs.get(i);
6783                         if (DEBUG_PREFERRED || debug) {
6784                             Slog.v(TAG, "Checking PreferredActivity ds="
6785                                     + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6786                                     + "\n  component=" + pa.mPref.mComponent);
6787                             pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6788                         }
6789                         if (pa.mPref.mMatch != match) {
6790                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6791                                     + Integer.toHexString(pa.mPref.mMatch));
6792                             continue;
6793                         }
6794                         // If it's not an "always" type preferred activity and that's what we're
6795                         // looking for, skip it.
6796                         if (always && !pa.mPref.mAlways) {
6797                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6798                             continue;
6799                         }
6800                         final ActivityInfo ai = getActivityInfo(
6801                                 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6802                                         | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6803                                 userId);
6804                         if (DEBUG_PREFERRED || debug) {
6805                             Slog.v(TAG, "Found preferred activity:");
6806                             if (ai != null) {
6807                                 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6808                             } else {
6809                                 Slog.v(TAG, "  null");
6810                             }
6811                         }
6812                         if (ai == null) {
6813                             // This previously registered preferred activity
6814                             // component is no longer known.  Most likely an update
6815                             // to the app was installed and in the new version this
6816                             // component no longer exists.  Clean it up by removing
6817                             // it from the preferred activities list, and skip it.
6818                             Slog.w(TAG, "Removing dangling preferred activity: "
6819                                     + pa.mPref.mComponent);
6820                             pir.removeFilter(pa);
6821                             changed = true;
6822                             continue;
6823                         }
6824                         for (int j=0; j<N; j++) {
6825                             final ResolveInfo ri = query.get(j);
6826                             if (!ri.activityInfo.applicationInfo.packageName
6827                                     .equals(ai.applicationInfo.packageName)) {
6828                                 continue;
6829                             }
6830                             if (!ri.activityInfo.name.equals(ai.name)) {
6831                                 continue;
6832                             }
6833
6834                             if (removeMatches) {
6835                                 pir.removeFilter(pa);
6836                                 changed = true;
6837                                 if (DEBUG_PREFERRED) {
6838                                     Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6839                                 }
6840                                 break;
6841                             }
6842
6843                             // Okay we found a previously set preferred or last chosen app.
6844                             // If the result set is different from when this
6845                             // was created, we need to clear it and re-ask the
6846                             // user their preference, if we're looking for an "always" type entry.
6847                             if (always && !pa.mPref.sameSet(query)) {
6848                                 Slog.i(TAG, "Result set changed, dropping preferred activity for "
6849                                         + intent + " type " + resolvedType);
6850                                 if (DEBUG_PREFERRED) {
6851                                     Slog.v(TAG, "Removing preferred activity since set changed "
6852                                             + pa.mPref.mComponent);
6853                                 }
6854                                 pir.removeFilter(pa);
6855                                 // Re-add the filter as a "last chosen" entry (!always)
6856                                 PreferredActivity lastChosen = new PreferredActivity(
6857                                         pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6858                                 pir.addFilter(lastChosen);
6859                                 changed = true;
6860                                 return null;
6861                             }
6862
6863                             // Yay! Either the set matched or we're looking for the last chosen
6864                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6865                                     + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6866                             return ri;
6867                         }
6868                     }
6869                 } finally {
6870                     if (changed) {
6871                         if (DEBUG_PREFERRED) {
6872                             Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6873                         }
6874                         scheduleWritePackageRestrictionsLocked(userId);
6875                     }
6876                 }
6877             }
6878         }
6879         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6880         return null;
6881     }
6882
6883     /*
6884      * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6885      */
6886     @Override
6887     public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6888             int targetUserId) {
6889         mContext.enforceCallingOrSelfPermission(
6890                 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6891         List<CrossProfileIntentFilter> matches =
6892                 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6893         if (matches != null) {
6894             int size = matches.size();
6895             for (int i = 0; i < size; i++) {
6896                 if (matches.get(i).getTargetUserId() == targetUserId) return true;
6897             }
6898         }
6899         if (hasWebURI(intent)) {
6900             // cross-profile app linking works only towards the parent.
6901             final int callingUid = Binder.getCallingUid();
6902             final UserInfo parent = getProfileParent(sourceUserId);
6903             synchronized(mPackages) {
6904                 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6905                         false /*includeInstantApps*/);
6906                 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6907                         intent, resolvedType, flags, sourceUserId, parent.id);
6908                 return xpDomainInfo != null;
6909             }
6910         }
6911         return false;
6912     }
6913
6914     private UserInfo getProfileParent(int userId) {
6915         final long identity = Binder.clearCallingIdentity();
6916         try {
6917             return sUserManager.getProfileParent(userId);
6918         } finally {
6919             Binder.restoreCallingIdentity(identity);
6920         }
6921     }
6922
6923     private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6924             String resolvedType, int userId) {
6925         CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6926         if (resolver != null) {
6927             return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6928         }
6929         return null;
6930     }
6931
6932     @Override
6933     public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6934             String resolvedType, int flags, int userId) {
6935         try {
6936             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6937
6938             return new ParceledListSlice<>(
6939                     queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6940         } finally {
6941             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6942         }
6943     }
6944
6945     /**
6946      * Returns the package name of the calling Uid if it's an instant app. If it isn't
6947      * instant, returns {@code null}.
6948      */
6949     private String getInstantAppPackageName(int callingUid) {
6950         synchronized (mPackages) {
6951             // If the caller is an isolated app use the owner's uid for the lookup.
6952             if (Process.isIsolated(callingUid)) {
6953                 callingUid = mIsolatedOwners.get(callingUid);
6954             }
6955             final int appId = UserHandle.getAppId(callingUid);
6956             final Object obj = mSettings.getUserIdLPr(appId);
6957             if (obj instanceof PackageSetting) {
6958                 final PackageSetting ps = (PackageSetting) obj;
6959                 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6960                 return isInstantApp ? ps.pkg.packageName : null;
6961             }
6962         }
6963         return null;
6964     }
6965
6966     private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6967             String resolvedType, int flags, int userId) {
6968         return queryIntentActivitiesInternal(
6969                 intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6970     }
6971
6972     private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6973             String resolvedType, int flags, int filterCallingUid, int userId,
6974             boolean resolveForStart) {
6975         if (!sUserManager.exists(userId)) return Collections.emptyList();
6976         final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6977         enforceCrossUserPermission(Binder.getCallingUid(), userId,
6978                 false /* requireFullPermission */, false /* checkShell */,
6979                 "query intent activities");
6980         final String pkgName = intent.getPackage();
6981         ComponentName comp = intent.getComponent();
6982         if (comp == null) {
6983             if (intent.getSelector() != null) {
6984                 intent = intent.getSelector();
6985                 comp = intent.getComponent();
6986             }
6987         }
6988
6989         flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6990                 comp != null || pkgName != null /*onlyExposedExplicitly*/);
6991         if (comp != null) {
6992             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6993             final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6994             if (ai != null) {
6995                 // When specifying an explicit component, we prevent the activity from being
6996                 // used when either 1) the calling package is normal and the activity is within
6997                 // an ephemeral application or 2) the calling package is ephemeral and the
6998                 // activity is not visible to ephemeral applications.
6999                 final boolean matchInstantApp =
7000                         (flags & PackageManager.MATCH_INSTANT) != 0;
7001                 final boolean matchVisibleToInstantAppOnly =
7002                         (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7003                 final boolean matchExplicitlyVisibleOnly =
7004                         (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7005                 final boolean isCallerInstantApp =
7006                         instantAppPkgName != null;
7007                 final boolean isTargetSameInstantApp =
7008                         comp.getPackageName().equals(instantAppPkgName);
7009                 final boolean isTargetInstantApp =
7010                         (ai.applicationInfo.privateFlags
7011                                 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7012                 final boolean isTargetVisibleToInstantApp =
7013                         (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7014                 final boolean isTargetExplicitlyVisibleToInstantApp =
7015                         isTargetVisibleToInstantApp
7016                         && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7017                 final boolean isTargetHiddenFromInstantApp =
7018                         !isTargetVisibleToInstantApp
7019                         || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7020                 final boolean blockResolution =
7021                         !isTargetSameInstantApp
7022                         && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7023                                 || (matchVisibleToInstantAppOnly && isCallerInstantApp
7024                                         && isTargetHiddenFromInstantApp));
7025                 if (!blockResolution) {
7026                     final ResolveInfo ri = new ResolveInfo();
7027                     ri.activityInfo = ai;
7028                     list.add(ri);
7029                 }
7030             }
7031             return applyPostResolutionFilter(list, instantAppPkgName);
7032         }
7033
7034         // reader
7035         boolean sortResult = false;
7036         boolean addEphemeral = false;
7037         List<ResolveInfo> result;
7038         final boolean ephemeralDisabled = isEphemeralDisabled();
7039         synchronized (mPackages) {
7040             if (pkgName == null) {
7041                 List<CrossProfileIntentFilter> matchingFilters =
7042                         getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7043                 // Check for results that need to skip the current profile.
7044                 ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7045                         resolvedType, flags, userId);
7046                 if (xpResolveInfo != null) {
7047                     List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7048                     xpResult.add(xpResolveInfo);
7049                     return applyPostResolutionFilter(
7050                             filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
7051                 }
7052
7053                 // Check for results in the current profile.
7054                 result = filterIfNotSystemUser(mActivities.queryIntent(
7055                         intent, resolvedType, flags, userId), userId);
7056                 addEphemeral = !ephemeralDisabled
7057                         && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7058                 // Check for cross profile results.
7059                 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7060                 xpResolveInfo = queryCrossProfileIntents(
7061                         matchingFilters, intent, resolvedType, flags, userId,
7062                         hasNonNegativePriorityResult);
7063                 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7064                     boolean isVisibleToUser = filterIfNotSystemUser(
7065                             Collections.singletonList(xpResolveInfo), userId).size() > 0;
7066                     if (isVisibleToUser) {
7067                         result.add(xpResolveInfo);
7068                         sortResult = true;
7069                     }
7070                 }
7071                 if (hasWebURI(intent)) {
7072                     CrossProfileDomainInfo xpDomainInfo = null;
7073                     final UserInfo parent = getProfileParent(userId);
7074                     if (parent != null) {
7075                         xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7076                                 flags, userId, parent.id);
7077                     }
7078                     if (xpDomainInfo != null) {
7079                         if (xpResolveInfo != null) {
7080                             // If we didn't remove it, the cross-profile ResolveInfo would be twice
7081                             // in the result.
7082                             result.remove(xpResolveInfo);
7083                         }
7084                         if (result.size() == 0 && !addEphemeral) {
7085                             // No result in current profile, but found candidate in parent user.
7086                             // And we are not going to add emphemeral app, so we can return the
7087                             // result straight away.
7088                             result.add(xpDomainInfo.resolveInfo);
7089                             return applyPostResolutionFilter(result, instantAppPkgName);
7090                         }
7091                     } else if (result.size() <= 1 && !addEphemeral) {
7092                         // No result in parent user and <= 1 result in current profile, and we
7093                         // are not going to add emphemeral app, so we can return the result without
7094                         // further processing.
7095                         return applyPostResolutionFilter(result, instantAppPkgName);
7096                     }
7097                     // We have more than one candidate (combining results from current and parent
7098                     // profile), so we need filtering and sorting.
7099                     result = filterCandidatesWithDomainPreferredActivitiesLPr(
7100                             intent, flags, result, xpDomainInfo, userId);
7101                     sortResult = true;
7102                 }
7103             } else {
7104                 final PackageParser.Package pkg = mPackages.get(pkgName);
7105                 result = null;
7106                 if (pkg != null) {
7107                     result = filterIfNotSystemUser(
7108                             mActivities.queryIntentForPackage(
7109                                     intent, resolvedType, flags, pkg.activities, userId),
7110                             userId);
7111                 }
7112                 if (result == null || result.size() == 0) {
7113                     // the caller wants to resolve for a particular package; however, there
7114                     // were no installed results, so, try to find an ephemeral result
7115                     addEphemeral = !ephemeralDisabled
7116                             && isInstantAppAllowed(
7117                                     intent, null /*result*/, userId, true /*skipPackageCheck*/);
7118                     if (result == null) {
7119                         result = new ArrayList<>();
7120                     }
7121                 }
7122             }
7123         }
7124         if (addEphemeral) {
7125             result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7126         }
7127         if (sortResult) {
7128             Collections.sort(result, mResolvePrioritySorter);
7129         }
7130         return applyPostResolutionFilter(result, instantAppPkgName);
7131     }
7132
7133     private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7134             String resolvedType, int flags, int userId) {
7135         // first, check to see if we've got an instant app already installed
7136         final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7137         ResolveInfo localInstantApp = null;
7138         boolean blockResolution = false;
7139         if (!alreadyResolvedLocally) {
7140             final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7141                     flags
7142                         | PackageManager.GET_RESOLVED_FILTER
7143                         | PackageManager.MATCH_INSTANT
7144                         | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7145                     userId);
7146             for (int i = instantApps.size() - 1; i >= 0; --i) {
7147                 final ResolveInfo info = instantApps.get(i);
7148                 final String packageName = info.activityInfo.packageName;
7149                 final PackageSetting ps = mSettings.mPackages.get(packageName);
7150                 if (ps.getInstantApp(userId)) {
7151                     final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7152                     final int status = (int)(packedStatus >> 32);
7153                     final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7154                     if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7155                         // there's a local instant application installed, but, the user has
7156                         // chosen to never use it; skip resolution and don't acknowledge
7157                         // an instant application is even available
7158                         if (DEBUG_EPHEMERAL) {
7159                             Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7160                         }
7161                         blockResolution = true;
7162                         break;
7163                     } else {
7164                         // we have a locally installed instant application; skip resolution
7165                         // but acknowledge there's an instant application available
7166                         if (DEBUG_EPHEMERAL) {
7167                             Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7168                         }
7169                         localInstantApp = info;
7170                         break;
7171                     }
7172                 }
7173             }
7174         }
7175         // no app installed, let's see if one's available
7176         AuxiliaryResolveInfo auxiliaryResponse = null;
7177         if (!blockResolution) {
7178             if (localInstantApp == null) {
7179                 // we don't have an instant app locally, resolve externally
7180                 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7181                 final InstantAppRequest requestObject = new InstantAppRequest(
7182                         null /*responseObj*/, intent /*origIntent*/, resolvedType,
7183                         null /*callingPackage*/, userId, null /*verificationBundle*/);
7184                 auxiliaryResponse =
7185                         InstantAppResolver.doInstantAppResolutionPhaseOne(
7186                                 mContext, mInstantAppResolverConnection, requestObject);
7187                 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7188             } else {
7189                 // we have an instant application locally, but, we can't admit that since
7190                 // callers shouldn't be able to determine prior browsing. create a dummy
7191                 // auxiliary response so the downstream code behaves as if there's an
7192                 // instant application available externally. when it comes time to start
7193                 // the instant application, we'll do the right thing.
7194                 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7195                 auxiliaryResponse = new AuxiliaryResolveInfo(
7196                         ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7197             }
7198         }
7199         if (auxiliaryResponse != null) {
7200             if (DEBUG_EPHEMERAL) {
7201                 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7202             }
7203             final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7204             final PackageSetting ps =
7205                     mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7206             if (ps != null) {
7207                 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7208                         mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7209                 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7210                 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7211                 // make sure this resolver is the default
7212                 ephemeralInstaller.isDefault = true;
7213                 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7214                         | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7215                 // add a non-generic filter
7216                 ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7217                 ephemeralInstaller.filter.addDataPath(
7218                         intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7219                 ephemeralInstaller.isInstantAppAvailable = true;
7220                 result.add(ephemeralInstaller);
7221             }
7222         }
7223         return result;
7224     }
7225
7226     private static class CrossProfileDomainInfo {
7227         /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7228         ResolveInfo resolveInfo;
7229         /* Best domain verification status of the activities found in the other profile */
7230         int bestDomainVerificationStatus;
7231     }
7232
7233     private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7234             String resolvedType, int flags, int sourceUserId, int parentUserId) {
7235         if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7236                 sourceUserId)) {
7237             return null;
7238         }
7239         List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7240                 resolvedType, flags, parentUserId);
7241
7242         if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7243             return null;
7244         }
7245         CrossProfileDomainInfo result = null;
7246         int size = resultTargetUser.size();
7247         for (int i = 0; i < size; i++) {
7248             ResolveInfo riTargetUser = resultTargetUser.get(i);
7249             // Intent filter verification is only for filters that specify a host. So don't return
7250             // those that handle all web uris.
7251             if (riTargetUser.handleAllWebDataURI) {
7252                 continue;
7253             }
7254             String packageName = riTargetUser.activityInfo.packageName;
7255             PackageSetting ps = mSettings.mPackages.get(packageName);
7256             if (ps == null) {
7257                 continue;
7258             }
7259             long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7260             int status = (int)(verificationState >> 32);
7261             if (result == null) {
7262                 result = new CrossProfileDomainInfo();
7263                 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7264                         sourceUserId, parentUserId);
7265                 result.bestDomainVerificationStatus = status;
7266             } else {
7267                 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7268                         result.bestDomainVerificationStatus);
7269             }
7270         }
7271         // Don't consider matches with status NEVER across profiles.
7272         if (result != null && result.bestDomainVerificationStatus
7273                 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7274             return null;
7275         }
7276         return result;
7277     }
7278
7279     /**
7280      * Verification statuses are ordered from the worse to the best, except for
7281      * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7282      */
7283     private int bestDomainVerificationStatus(int status1, int status2) {
7284         if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7285             return status2;
7286         }
7287         if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7288             return status1;
7289         }
7290         return (int) MathUtils.max(status1, status2);
7291     }
7292
7293     private boolean isUserEnabled(int userId) {
7294         long callingId = Binder.clearCallingIdentity();
7295         try {
7296             UserInfo userInfo = sUserManager.getUserInfo(userId);
7297             return userInfo != null && userInfo.isEnabled();
7298         } finally {
7299             Binder.restoreCallingIdentity(callingId);
7300         }
7301     }
7302
7303     /**
7304      * Filter out activities with systemUserOnly flag set, when current user is not System.
7305      *
7306      * @return filtered list
7307      */
7308     private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7309         if (userId == UserHandle.USER_SYSTEM) {
7310             return resolveInfos;
7311         }
7312         for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7313             ResolveInfo info = resolveInfos.get(i);
7314             if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7315                 resolveInfos.remove(i);
7316             }
7317         }
7318         return resolveInfos;
7319     }
7320
7321     /**
7322      * Filters out ephemeral activities.
7323      * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7324      * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7325      *
7326      * @param resolveInfos The pre-filtered list of resolved activities
7327      * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7328      *          is performed.
7329      * @return A filtered list of resolved activities.
7330      */
7331     private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7332             String ephemeralPkgName) {
7333         for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7334             final ResolveInfo info = resolveInfos.get(i);
7335             final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7336             // TODO: When adding on-demand split support for non-instant apps, remove this check
7337             // and always apply post filtering
7338             // allow activities that are defined in the provided package
7339             if (isEphemeralApp) {
7340                 if (info.activityInfo.splitName != null
7341                         && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7342                                 info.activityInfo.splitName)) {
7343                     // requested activity is defined in a split that hasn't been installed yet.
7344                     // add the installer to the resolve list
7345                     if (DEBUG_EPHEMERAL) {
7346                         Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7347                     }
7348                     final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7349                     installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7350                             info.activityInfo.packageName, info.activityInfo.splitName,
7351                             info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7352                     // make sure this resolver is the default
7353                     installerInfo.isDefault = true;
7354                     installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7355                             | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7356                     // add a non-generic filter
7357                     installerInfo.filter = new IntentFilter();
7358                     // load resources from the correct package
7359                     installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7360                     resolveInfos.set(i, installerInfo);
7361                     continue;
7362                 }
7363             }
7364             // caller is a full app, don't need to apply any other filtering
7365             if (ephemeralPkgName == null) {
7366                 continue;
7367             } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7368                 // caller is same app; don't need to apply any other filtering
7369                 continue;
7370             }
7371             // allow activities that have been explicitly exposed to ephemeral apps
7372             if (!isEphemeralApp
7373                     && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7374                 continue;
7375             }
7376             resolveInfos.remove(i);
7377         }
7378         return resolveInfos;
7379     }
7380
7381     /**
7382      * @param resolveInfos list of resolve infos in descending priority order
7383      * @return if the list contains a resolve info with non-negative priority
7384      */
7385     private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7386         return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7387     }
7388
7389     private static boolean hasWebURI(Intent intent) {
7390         if (intent.getData() == null) {
7391             return false;
7392         }
7393         final String scheme = intent.getScheme();
7394         if (TextUtils.isEmpty(scheme)) {
7395             return false;
7396         }
7397         return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7398     }
7399
7400     private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7401             int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7402             int userId) {
7403         final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7404
7405         if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7406             Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7407                     candidates.size());
7408         }
7409
7410         ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7411         ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7412         ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7413         ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7414         ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7415         ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7416
7417         synchronized (mPackages) {
7418             final int count = candidates.size();
7419             // First, try to use linked apps. Partition the candidates into four lists:
7420             // one for the final results, one for the "do not use ever", one for "undefined status"
7421             // and finally one for "browser app type".
7422             for (int n=0; n<count; n++) {
7423                 ResolveInfo info = candidates.get(n);
7424                 String packageName = info.activityInfo.packageName;
7425                 PackageSetting ps = mSettings.mPackages.get(packageName);
7426                 if (ps != null) {
7427                     // Add to the special match all list (Browser use case)
7428                     if (info.handleAllWebDataURI) {
7429                         matchAllList.add(info);
7430                         continue;
7431                     }
7432                     // Try to get the status from User settings first
7433                     long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7434                     int status = (int)(packedStatus >> 32);
7435                     int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7436                     if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7437                         if (DEBUG_DOMAIN_VERIFICATION || debug) {
7438                             Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7439                                     + " : linkgen=" + linkGeneration);
7440                         }
7441                         // Use link-enabled generation as preferredOrder, i.e.
7442                         // prefer newly-enabled over earlier-enabled.
7443                         info.preferredOrder = linkGeneration;
7444                         alwaysList.add(info);
7445                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7446                         if (DEBUG_DOMAIN_VERIFICATION || debug) {
7447                             Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7448                         }
7449                         neverList.add(info);
7450                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7451                         if (DEBUG_DOMAIN_VERIFICATION || debug) {
7452                             Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7453                         }
7454                         alwaysAskList.add(info);
7455                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7456                             status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7457                         if (DEBUG_DOMAIN_VERIFICATION || debug) {
7458                             Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7459                         }
7460                         undefinedList.add(info);
7461                     }
7462                 }
7463             }
7464
7465             // We'll want to include browser possibilities in a few cases
7466             boolean includeBrowser = false;
7467
7468             // First try to add the "always" resolution(s) for the current user, if any
7469             if (alwaysList.size() > 0) {
7470                 result.addAll(alwaysList);
7471             } else {
7472                 // Add all undefined apps as we want them to appear in the disambiguation dialog.
7473                 result.addAll(undefinedList);
7474                 // Maybe add one for the other profile.
7475                 if (xpDomainInfo != null && (
7476                         xpDomainInfo.bestDomainVerificationStatus
7477                         != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7478                     result.add(xpDomainInfo.resolveInfo);
7479                 }
7480                 includeBrowser = true;
7481             }
7482
7483             // The presence of any 'always ask' alternatives means we'll also offer browsers.
7484             // If there were 'always' entries their preferred order has been set, so we also
7485             // back that off to make the alternatives equivalent
7486             if (alwaysAskList.size() > 0) {
7487                 for (ResolveInfo i : result) {
7488                     i.preferredOrder = 0;
7489                 }
7490                 result.addAll(alwaysAskList);
7491                 includeBrowser = true;
7492             }
7493
7494             if (includeBrowser) {
7495                 // Also add browsers (all of them or only the default one)
7496                 if (DEBUG_DOMAIN_VERIFICATION) {
7497                     Slog.v(TAG, "   ...including browsers in candidate set");
7498                 }
7499                 if ((matchFlags & MATCH_ALL) != 0) {
7500                     result.addAll(matchAllList);
7501                 } else {
7502                     // Browser/generic handling case.  If there's a default browser, go straight
7503                     // to that (but only if there is no other higher-priority match).
7504                     final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7505                     int maxMatchPrio = 0;
7506                     ResolveInfo defaultBrowserMatch = null;
7507                     final int numCandidates = matchAllList.size();
7508                     for (int n = 0; n < numCandidates; n++) {
7509                         ResolveInfo info = matchAllList.get(n);
7510                         // track the highest overall match priority...
7511                         if (info.priority > maxMatchPrio) {
7512                             maxMatchPrio = info.priority;
7513                         }
7514                         // ...and the highest-priority default browser match
7515                         if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7516                             if (defaultBrowserMatch == null
7517                                     || (defaultBrowserMatch.priority < info.priority)) {
7518                                 if (debug) {
7519                                     Slog.v(TAG, "Considering default browser match " + info);
7520                                 }
7521                                 defaultBrowserMatch = info;
7522                             }
7523                         }
7524                     }
7525                     if (defaultBrowserMatch != null
7526                             && defaultBrowserMatch.priority >= maxMatchPrio
7527                             && !TextUtils.isEmpty(defaultBrowserPackageName))
7528                     {
7529                         if (debug) {
7530                             Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7531                         }
7532                         result.add(defaultBrowserMatch);
7533                     } else {
7534                         result.addAll(matchAllList);
7535                     }
7536                 }
7537
7538                 // If there is nothing selected, add all candidates and remove the ones that the user
7539                 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7540                 if (result.size() == 0) {
7541                     result.addAll(candidates);
7542                     result.removeAll(neverList);
7543                 }
7544             }
7545         }
7546         if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7547             Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7548                     result.size());
7549             for (ResolveInfo info : result) {
7550                 Slog.v(TAG, "  + " + info.activityInfo);
7551             }
7552         }
7553         return result;
7554     }
7555
7556     // Returns a packed value as a long:
7557     //
7558     // high 'int'-sized word: link status: undefined/ask/never/always.
7559     // low 'int'-sized word: relative priority among 'always' results.
7560     private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7561         long result = ps.getDomainVerificationStatusForUser(userId);
7562         // if none available, get the master status
7563         if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7564             if (ps.getIntentFilterVerificationInfo() != null) {
7565                 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7566             }
7567         }
7568         return result;
7569     }
7570
7571     private ResolveInfo querySkipCurrentProfileIntents(
7572             List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7573             int flags, int sourceUserId) {
7574         if (matchingFilters != null) {
7575             int size = matchingFilters.size();
7576             for (int i = 0; i < size; i ++) {
7577                 CrossProfileIntentFilter filter = matchingFilters.get(i);
7578                 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7579                     // Checking if there are activities in the target user that can handle the
7580                     // intent.
7581                     ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7582                             resolvedType, flags, sourceUserId);
7583                     if (resolveInfo != null) {
7584                         return resolveInfo;
7585                     }
7586                 }
7587             }
7588         }
7589         return null;
7590     }
7591
7592     // Return matching ResolveInfo in target user if any.
7593     private ResolveInfo queryCrossProfileIntents(
7594             List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7595             int flags, int sourceUserId, boolean matchInCurrentProfile) {
7596         if (matchingFilters != null) {
7597             // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7598             // match the same intent. For performance reasons, it is better not to
7599             // run queryIntent twice for the same userId
7600             SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7601             int size = matchingFilters.size();
7602             for (int i = 0; i < size; i++) {
7603                 CrossProfileIntentFilter filter = matchingFilters.get(i);
7604                 int targetUserId = filter.getTargetUserId();
7605                 boolean skipCurrentProfile =
7606                         (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7607                 boolean skipCurrentProfileIfNoMatchFound =
7608                         (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7609                 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7610                         && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7611                     // Checking if there are activities in the target user that can handle the
7612                     // intent.
7613                     ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7614                             resolvedType, flags, sourceUserId);
7615                     if (resolveInfo != null) return resolveInfo;
7616                     alreadyTriedUserIds.put(targetUserId, true);
7617                 }
7618             }
7619         }
7620         return null;
7621     }
7622
7623     /**
7624      * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7625      * will forward the intent to the filter's target user.
7626      * Otherwise, returns null.
7627      */
7628     private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7629             String resolvedType, int flags, int sourceUserId) {
7630         int targetUserId = filter.getTargetUserId();
7631         List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7632                 resolvedType, flags, targetUserId);
7633         if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7634             // If all the matches in the target profile are suspended, return null.
7635             for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7636                 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7637                         & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7638                     return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7639                             targetUserId);
7640                 }
7641             }
7642         }
7643         return null;
7644     }
7645
7646     private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7647             int sourceUserId, int targetUserId) {
7648         ResolveInfo forwardingResolveInfo = new ResolveInfo();
7649         long ident = Binder.clearCallingIdentity();
7650         boolean targetIsProfile;
7651         try {
7652             targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7653         } finally {
7654             Binder.restoreCallingIdentity(ident);
7655         }
7656         String className;
7657         if (targetIsProfile) {
7658             className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7659         } else {
7660             className = FORWARD_INTENT_TO_PARENT;
7661         }
7662         ComponentName forwardingActivityComponentName = new ComponentName(
7663                 mAndroidApplication.packageName, className);
7664         ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7665                 sourceUserId);
7666         if (!targetIsProfile) {
7667             forwardingActivityInfo.showUserIcon = targetUserId;
7668             forwardingResolveInfo.noResourceId = true;
7669         }
7670         forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7671         forwardingResolveInfo.priority = 0;
7672         forwardingResolveInfo.preferredOrder = 0;
7673         forwardingResolveInfo.match = 0;
7674         forwardingResolveInfo.isDefault = true;
7675         forwardingResolveInfo.filter = filter;
7676         forwardingResolveInfo.targetUserId = targetUserId;
7677         return forwardingResolveInfo;
7678     }
7679
7680     @Override
7681     public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7682             Intent[] specifics, String[] specificTypes, Intent intent,
7683             String resolvedType, int flags, int userId) {
7684         return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7685                 specificTypes, intent, resolvedType, flags, userId));
7686     }
7687
7688     private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7689             Intent[] specifics, String[] specificTypes, Intent intent,
7690             String resolvedType, int flags, int userId) {
7691         if (!sUserManager.exists(userId)) return Collections.emptyList();
7692         final int callingUid = Binder.getCallingUid();
7693         flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7694                 false /*includeInstantApps*/);
7695         enforceCrossUserPermission(callingUid, userId,
7696                 false /*requireFullPermission*/, false /*checkShell*/,
7697                 "query intent activity options");
7698         final String resultsAction = intent.getAction();
7699
7700         final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7701                 | PackageManager.GET_RESOLVED_FILTER, userId);
7702
7703         if (DEBUG_INTENT_MATCHING) {
7704             Log.v(TAG, "Query " + intent + ": " + results);
7705         }
7706
7707         int specificsPos = 0;
7708         int N;
7709
7710         // todo: note that the algorithm used here is O(N^2).  This
7711         // isn't a problem in our current environment, but if we start running
7712         // into situations where we have more than 5 or 10 matches then this
7713         // should probably be changed to something smarter...
7714
7715         // First we go through and resolve each of the specific items
7716         // that were supplied, taking care of removing any corresponding
7717         // duplicate items in the generic resolve list.
7718         if (specifics != null) {
7719             for (int i=0; i<specifics.length; i++) {
7720                 final Intent sintent = specifics[i];
7721                 if (sintent == null) {
7722                     continue;
7723                 }
7724
7725                 if (DEBUG_INTENT_MATCHING) {
7726                     Log.v(TAG, "Specific #" + i + ": " + sintent);
7727                 }
7728
7729                 String action = sintent.getAction();
7730                 if (resultsAction != null && resultsAction.equals(action)) {
7731                     // If this action was explicitly requested, then don't
7732                     // remove things that have it.
7733                     action = null;
7734                 }
7735
7736                 ResolveInfo ri = null;
7737                 ActivityInfo ai = null;
7738
7739                 ComponentName comp = sintent.getComponent();
7740                 if (comp == null) {
7741                     ri = resolveIntent(
7742                         sintent,
7743                         specificTypes != null ? specificTypes[i] : null,
7744                             flags, userId);
7745                     if (ri == null) {
7746                         continue;
7747                     }
7748                     if (ri == mResolveInfo) {
7749                         // ACK!  Must do something better with this.
7750                     }
7751                     ai = ri.activityInfo;
7752                     comp = new ComponentName(ai.applicationInfo.packageName,
7753                             ai.name);
7754                 } else {
7755                     ai = getActivityInfo(comp, flags, userId);
7756                     if (ai == null) {
7757                         continue;
7758                     }
7759                 }
7760
7761                 // Look for any generic query activities that are duplicates
7762                 // of this specific one, and remove them from the results.
7763                 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7764                 N = results.size();
7765                 int j;
7766                 for (j=specificsPos; j<N; j++) {
7767                     ResolveInfo sri = results.get(j);
7768                     if ((sri.activityInfo.name.equals(comp.getClassName())
7769                             && sri.activityInfo.applicationInfo.packageName.equals(
7770                                     comp.getPackageName()))
7771                         || (action != null && sri.filter.matchAction(action))) {
7772                         results.remove(j);
7773                         if (DEBUG_INTENT_MATCHING) Log.v(
7774                             TAG, "Removing duplicate item from " + j
7775                             + " due to specific " + specificsPos);
7776                         if (ri == null) {
7777                             ri = sri;
7778                         }
7779                         j--;
7780                         N--;
7781                     }
7782                 }
7783
7784                 // Add this specific item to its proper place.
7785                 if (ri == null) {
7786                     ri = new ResolveInfo();
7787                     ri.activityInfo = ai;
7788                 }
7789                 results.add(specificsPos, ri);
7790                 ri.specificIndex = i;
7791                 specificsPos++;
7792             }
7793         }
7794
7795         // Now we go through the remaining generic results and remove any
7796         // duplicate actions that are found here.
7797         N = results.size();
7798         for (int i=specificsPos; i<N-1; i++) {
7799             final ResolveInfo rii = results.get(i);
7800             if (rii.filter == null) {
7801                 continue;
7802             }
7803
7804             // Iterate over all of the actions of this result's intent
7805             // filter...  typically this should be just one.
7806             final Iterator<String> it = rii.filter.actionsIterator();
7807             if (it == null) {
7808                 continue;
7809             }
7810             while (it.hasNext()) {
7811                 final String action = it.next();
7812                 if (resultsAction != null && resultsAction.equals(action)) {
7813                     // If this action was explicitly requested, then don't
7814                     // remove things that have it.
7815                     continue;
7816                 }
7817                 for (int j=i+1; j<N; j++) {
7818                     final ResolveInfo rij = results.get(j);
7819                     if (rij.filter != null && rij.filter.hasAction(action)) {
7820                         results.remove(j);
7821                         if (DEBUG_INTENT_MATCHING) Log.v(
7822                             TAG, "Removing duplicate item from " + j
7823                             + " due to action " + action + " at " + i);
7824                         j--;
7825                         N--;
7826                     }
7827                 }
7828             }
7829
7830             // If the caller didn't request filter information, drop it now
7831             // so we don't have to marshall/unmarshall it.
7832             if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7833                 rii.filter = null;
7834             }
7835         }
7836
7837         // Filter out the caller activity if so requested.
7838         if (caller != null) {
7839             N = results.size();
7840             for (int i=0; i<N; i++) {
7841                 ActivityInfo ainfo = results.get(i).activityInfo;
7842                 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7843                         && caller.getClassName().equals(ainfo.name)) {
7844                     results.remove(i);
7845                     break;
7846                 }
7847             }
7848         }
7849
7850         // If the caller didn't request filter information,
7851         // drop them now so we don't have to
7852         // marshall/unmarshall it.
7853         if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7854             N = results.size();
7855             for (int i=0; i<N; i++) {
7856                 results.get(i).filter = null;
7857             }
7858         }
7859
7860         if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7861         return results;
7862     }
7863
7864     @Override
7865     public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7866             String resolvedType, int flags, int userId) {
7867         return new ParceledListSlice<>(
7868                 queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7869     }
7870
7871     private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7872             String resolvedType, int flags, int userId) {
7873         if (!sUserManager.exists(userId)) return Collections.emptyList();
7874         final int callingUid = Binder.getCallingUid();
7875         final String instantAppPkgName = getInstantAppPackageName(callingUid);
7876         flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7877                 false /*includeInstantApps*/);
7878         ComponentName comp = intent.getComponent();
7879         if (comp == null) {
7880             if (intent.getSelector() != null) {
7881                 intent = intent.getSelector();
7882                 comp = intent.getComponent();
7883             }
7884         }
7885         if (comp != null) {
7886             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7887             final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7888             if (ai != null) {
7889                 // When specifying an explicit component, we prevent the activity from being
7890                 // used when either 1) the calling package is normal and the activity is within
7891                 // an instant application or 2) the calling package is ephemeral and the
7892                 // activity is not visible to instant applications.
7893                 final boolean matchInstantApp =
7894                         (flags & PackageManager.MATCH_INSTANT) != 0;
7895                 final boolean matchVisibleToInstantAppOnly =
7896                         (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7897                 final boolean matchExplicitlyVisibleOnly =
7898                         (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7899                 final boolean isCallerInstantApp =
7900                         instantAppPkgName != null;
7901                 final boolean isTargetSameInstantApp =
7902                         comp.getPackageName().equals(instantAppPkgName);
7903                 final boolean isTargetInstantApp =
7904                         (ai.applicationInfo.privateFlags
7905                                 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7906                 final boolean isTargetVisibleToInstantApp =
7907                         (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7908                 final boolean isTargetExplicitlyVisibleToInstantApp =
7909                         isTargetVisibleToInstantApp
7910                         && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7911                 final boolean isTargetHiddenFromInstantApp =
7912                         !isTargetVisibleToInstantApp
7913                         || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7914                 final boolean blockResolution =
7915                         !isTargetSameInstantApp
7916                         && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7917                                 || (matchVisibleToInstantAppOnly && isCallerInstantApp
7918                                         && isTargetHiddenFromInstantApp));
7919                 if (!blockResolution) {
7920                     ResolveInfo ri = new ResolveInfo();
7921                     ri.activityInfo = ai;
7922                     list.add(ri);
7923                 }
7924             }
7925             return applyPostResolutionFilter(list, instantAppPkgName);
7926         }
7927
7928         // reader
7929         synchronized (mPackages) {
7930             String pkgName = intent.getPackage();
7931             if (pkgName == null) {
7932                 final List<ResolveInfo> result =
7933                         mReceivers.queryIntent(intent, resolvedType, flags, userId);
7934                 return applyPostResolutionFilter(result, instantAppPkgName);
7935             }
7936             final PackageParser.Package pkg = mPackages.get(pkgName);
7937             if (pkg != null) {
7938                 final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7939                         intent, resolvedType, flags, pkg.receivers, userId);
7940                 return applyPostResolutionFilter(result, instantAppPkgName);
7941             }
7942             return Collections.emptyList();
7943         }
7944     }
7945
7946     @Override
7947     public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7948         final int callingUid = Binder.getCallingUid();
7949         return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7950     }
7951
7952     private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7953             int userId, int callingUid) {
7954         if (!sUserManager.exists(userId)) return null;
7955         flags = updateFlagsForResolve(
7956                 flags, userId, intent, callingUid, false /*includeInstantApps*/);
7957         List<ResolveInfo> query = queryIntentServicesInternal(
7958                 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7959         if (query != null) {
7960             if (query.size() >= 1) {
7961                 // If there is more than one service with the same priority,
7962                 // just arbitrarily pick the first one.
7963                 return query.get(0);
7964             }
7965         }
7966         return null;
7967     }
7968
7969     @Override
7970     public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7971             String resolvedType, int flags, int userId) {
7972         final int callingUid = Binder.getCallingUid();
7973         return new ParceledListSlice<>(queryIntentServicesInternal(
7974                 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7975     }
7976
7977     private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7978             String resolvedType, int flags, int userId, int callingUid,
7979             boolean includeInstantApps) {
7980         if (!sUserManager.exists(userId)) return Collections.emptyList();
7981         final String instantAppPkgName = getInstantAppPackageName(callingUid);
7982         flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7983         ComponentName comp = intent.getComponent();
7984         if (comp == null) {
7985             if (intent.getSelector() != null) {
7986                 intent = intent.getSelector();
7987                 comp = intent.getComponent();
7988             }
7989         }
7990         if (comp != null) {
7991             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7992             final ServiceInfo si = getServiceInfo(comp, flags, userId);
7993             if (si != null) {
7994                 // When specifying an explicit component, we prevent the service from being
7995                 // used when either 1) the service is in an instant application and the
7996                 // caller is not the same instant application or 2) the calling package is
7997                 // ephemeral and the activity is not visible to ephemeral applications.
7998                 final boolean matchInstantApp =
7999                         (flags & PackageManager.MATCH_INSTANT) != 0;
8000                 final boolean matchVisibleToInstantAppOnly =
8001                         (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8002                 final boolean isCallerInstantApp =
8003                         instantAppPkgName != null;
8004                 final boolean isTargetSameInstantApp =
8005                         comp.getPackageName().equals(instantAppPkgName);
8006                 final boolean isTargetInstantApp =
8007                         (si.applicationInfo.privateFlags
8008                                 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8009                 final boolean isTargetHiddenFromInstantApp =
8010                         (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8011                 final boolean blockResolution =
8012                         !isTargetSameInstantApp
8013                         && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8014                                 || (matchVisibleToInstantAppOnly && isCallerInstantApp
8015                                         && isTargetHiddenFromInstantApp));
8016                 if (!blockResolution) {
8017                     final ResolveInfo ri = new ResolveInfo();
8018                     ri.serviceInfo = si;
8019                     list.add(ri);
8020                 }
8021             }
8022             return list;
8023         }
8024
8025         // reader
8026         synchronized (mPackages) {
8027             String pkgName = intent.getPackage();
8028             if (pkgName == null) {
8029                 return applyPostServiceResolutionFilter(
8030                         mServices.queryIntent(intent, resolvedType, flags, userId),
8031                         instantAppPkgName);
8032             }
8033             final PackageParser.Package pkg = mPackages.get(pkgName);
8034             if (pkg != null) {
8035                 return applyPostServiceResolutionFilter(
8036                         mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8037                                 userId),
8038                         instantAppPkgName);
8039             }
8040             return Collections.emptyList();
8041         }
8042     }
8043
8044     private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8045             String instantAppPkgName) {
8046         // TODO: When adding on-demand split support for non-instant apps, remove this check
8047         // and always apply post filtering
8048         if (instantAppPkgName == null) {
8049             return resolveInfos;
8050         }
8051         for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8052             final ResolveInfo info = resolveInfos.get(i);
8053             final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8054             // allow services that are defined in the provided package
8055             if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8056                 if (info.serviceInfo.splitName != null
8057                         && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8058                                 info.serviceInfo.splitName)) {
8059                     // requested service is defined in a split that hasn't been installed yet.
8060                     // add the installer to the resolve list
8061                     if (DEBUG_EPHEMERAL) {
8062                         Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8063                     }
8064                     final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8065                     installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8066                             info.serviceInfo.packageName, info.serviceInfo.splitName,
8067                             info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
8068                     // make sure this resolver is the default
8069                     installerInfo.isDefault = true;
8070                     installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8071                             | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8072                     // add a non-generic filter
8073                     installerInfo.filter = new IntentFilter();
8074                     // load resources from the correct package
8075                     installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8076                     resolveInfos.set(i, installerInfo);
8077                 }
8078                 continue;
8079             }
8080             // allow services that have been explicitly exposed to ephemeral apps
8081             if (!isEphemeralApp
8082                     && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8083                 continue;
8084             }
8085             resolveInfos.remove(i);
8086         }
8087         return resolveInfos;
8088     }
8089
8090     @Override
8091     public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8092             String resolvedType, int flags, int userId) {
8093         return new ParceledListSlice<>(
8094                 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8095     }
8096
8097     private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8098             Intent intent, String resolvedType, int flags, int userId) {
8099         if (!sUserManager.exists(userId)) return Collections.emptyList();
8100         final int callingUid = Binder.getCallingUid();
8101         final String instantAppPkgName = getInstantAppPackageName(callingUid);
8102         flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8103                 false /*includeInstantApps*/);
8104         ComponentName comp = intent.getComponent();
8105         if (comp == null) {
8106             if (intent.getSelector() != null) {
8107                 intent = intent.getSelector();
8108                 comp = intent.getComponent();
8109             }
8110         }
8111         if (comp != null) {
8112             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8113             final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8114             if (pi != null) {
8115                 // When specifying an explicit component, we prevent the provider from being
8116                 // used when either 1) the provider is in an instant application and the
8117                 // caller is not the same instant application or 2) the calling package is an
8118                 // instant application and the provider is not visible to instant applications.
8119                 final boolean matchInstantApp =
8120                         (flags & PackageManager.MATCH_INSTANT) != 0;
8121                 final boolean matchVisibleToInstantAppOnly =
8122                         (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8123                 final boolean isCallerInstantApp =
8124                         instantAppPkgName != null;
8125                 final boolean isTargetSameInstantApp =
8126                         comp.getPackageName().equals(instantAppPkgName);
8127                 final boolean isTargetInstantApp =
8128                         (pi.applicationInfo.privateFlags
8129                                 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8130                 final boolean isTargetHiddenFromInstantApp =
8131                         (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8132                 final boolean blockResolution =
8133                         !isTargetSameInstantApp
8134                         && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8135                                 || (matchVisibleToInstantAppOnly && isCallerInstantApp
8136                                         && isTargetHiddenFromInstantApp));
8137                 if (!blockResolution) {
8138                     final ResolveInfo ri = new ResolveInfo();
8139                     ri.providerInfo = pi;
8140                     list.add(ri);
8141                 }
8142             }
8143             return list;
8144         }
8145
8146         // reader
8147         synchronized (mPackages) {
8148             String pkgName = intent.getPackage();
8149             if (pkgName == null) {
8150                 return applyPostContentProviderResolutionFilter(
8151                         mProviders.queryIntent(intent, resolvedType, flags, userId),
8152                         instantAppPkgName);
8153             }
8154             final PackageParser.Package pkg = mPackages.get(pkgName);
8155             if (pkg != null) {
8156                 return applyPostContentProviderResolutionFilter(
8157                         mProviders.queryIntentForPackage(
8158                         intent, resolvedType, flags, pkg.providers, userId),
8159                         instantAppPkgName);
8160             }
8161             return Collections.emptyList();
8162         }
8163     }
8164
8165     private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8166             List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8167         // TODO: When adding on-demand split support for non-instant applications, remove
8168         // this check and always apply post filtering
8169         if (instantAppPkgName == null) {
8170             return resolveInfos;
8171         }
8172         for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8173             final ResolveInfo info = resolveInfos.get(i);
8174             final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8175             // allow providers that are defined in the provided package
8176             if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8177                 if (info.providerInfo.splitName != null
8178                         && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8179                                 info.providerInfo.splitName)) {
8180                     // requested provider is defined in a split that hasn't been installed yet.
8181                     // add the installer to the resolve list
8182                     if (DEBUG_EPHEMERAL) {
8183                         Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8184                     }
8185                     final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8186                     installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8187                             info.providerInfo.packageName, info.providerInfo.splitName,
8188                             info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8189                     // make sure this resolver is the default
8190                     installerInfo.isDefault = true;
8191                     installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8192                             | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8193                     // add a non-generic filter
8194                     installerInfo.filter = new IntentFilter();
8195                     // load resources from the correct package
8196                     installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8197                     resolveInfos.set(i, installerInfo);
8198                 }
8199                 continue;
8200             }
8201             // allow providers that have been explicitly exposed to instant applications
8202             if (!isEphemeralApp
8203                     && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8204                 continue;
8205             }
8206             resolveInfos.remove(i);
8207         }
8208         return resolveInfos;
8209     }
8210
8211     @Override
8212     public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8213         final int callingUid = Binder.getCallingUid();
8214         if (getInstantAppPackageName(callingUid) != null) {
8215             return ParceledListSlice.emptyList();
8216         }
8217         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8218         flags = updateFlagsForPackage(flags, userId, null);
8219         final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8220         enforceCrossUserPermission(callingUid, userId,
8221                 false /* requireFullPermission */, false /* checkShell */,
8222                 "get installed packages");
8223
8224         // writer
8225         synchronized (mPackages) {
8226             ArrayList<PackageInfo> list;
8227             if (listUninstalled) {
8228                 list = new ArrayList<>(mSettings.mPackages.size());
8229                 for (PackageSetting ps : mSettings.mPackages.values()) {
8230                     if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8231                         continue;
8232                     }
8233                     if (filterAppAccessLPr(ps, callingUid, userId)) {
8234                         return null;
8235                     }
8236                     final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8237                     if (pi != null) {
8238                         list.add(pi);
8239                     }
8240                 }
8241             } else {
8242                 list = new ArrayList<>(mPackages.size());
8243                 for (PackageParser.Package p : mPackages.values()) {
8244                     final PackageSetting ps = (PackageSetting) p.mExtras;
8245                     if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8246                         continue;
8247                     }
8248                     if (filterAppAccessLPr(ps, callingUid, userId)) {
8249                         return null;
8250                     }
8251                     final PackageInfo pi = generatePackageInfo((PackageSetting)
8252                             p.mExtras, flags, userId);
8253                     if (pi != null) {
8254                         list.add(pi);
8255                     }
8256                 }
8257             }
8258
8259             return new ParceledListSlice<>(list);
8260         }
8261     }
8262
8263     private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8264             String[] permissions, boolean[] tmp, int flags, int userId) {
8265         int numMatch = 0;
8266         final PermissionsState permissionsState = ps.getPermissionsState();
8267         for (int i=0; i<permissions.length; i++) {
8268             final String permission = permissions[i];
8269             if (permissionsState.hasPermission(permission, userId)) {
8270                 tmp[i] = true;
8271                 numMatch++;
8272             } else {
8273                 tmp[i] = false;
8274             }
8275         }
8276         if (numMatch == 0) {
8277             return;
8278         }
8279         final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8280
8281         // The above might return null in cases of uninstalled apps or install-state
8282         // skew across users/profiles.
8283         if (pi != null) {
8284             if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8285                 if (numMatch == permissions.length) {
8286                     pi.requestedPermissions = permissions;
8287                 } else {
8288                     pi.requestedPermissions = new String[numMatch];
8289                     numMatch = 0;
8290                     for (int i=0; i<permissions.length; i++) {
8291                         if (tmp[i]) {
8292                             pi.requestedPermissions[numMatch] = permissions[i];
8293                             numMatch++;
8294                         }
8295                     }
8296                 }
8297             }
8298             list.add(pi);
8299         }
8300     }
8301
8302     @Override
8303     public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8304             String[] permissions, int flags, int userId) {
8305         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8306         flags = updateFlagsForPackage(flags, userId, permissions);
8307         enforceCrossUserPermission(Binder.getCallingUid(), userId,
8308                 true /* requireFullPermission */, false /* checkShell */,
8309                 "get packages holding permissions");
8310         final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8311
8312         // writer
8313         synchronized (mPackages) {
8314             ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8315             boolean[] tmpBools = new boolean[permissions.length];
8316             if (listUninstalled) {
8317                 for (PackageSetting ps : mSettings.mPackages.values()) {
8318                     addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8319                             userId);
8320                 }
8321             } else {
8322                 for (PackageParser.Package pkg : mPackages.values()) {
8323                     PackageSetting ps = (PackageSetting)pkg.mExtras;
8324                     if (ps != null) {
8325                         addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8326                                 userId);
8327                     }
8328                 }
8329             }
8330
8331             return new ParceledListSlice<PackageInfo>(list);
8332         }
8333     }
8334
8335     @Override
8336     public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8337         final int callingUid = Binder.getCallingUid();
8338         if (getInstantAppPackageName(callingUid) != null) {
8339             return ParceledListSlice.emptyList();
8340         }
8341         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8342         flags = updateFlagsForApplication(flags, userId, null);
8343         final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8344
8345         enforceCrossUserPermission(
8346             callingUid,
8347             userId,
8348             false /* requireFullPermission */,
8349             false /* checkShell */,
8350             "get installed application info");
8351
8352         // writer
8353         synchronized (mPackages) {
8354             ArrayList<ApplicationInfo> list;
8355             if (listUninstalled) {
8356                 list = new ArrayList<>(mSettings.mPackages.size());
8357                 for (PackageSetting ps : mSettings.mPackages.values()) {
8358                     ApplicationInfo ai;
8359                     int effectiveFlags = flags;
8360                     if (ps.isSystem()) {
8361                         effectiveFlags |= PackageManager.MATCH_ANY_USER;
8362                     }
8363                     if (ps.pkg != null) {
8364                         if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8365                             continue;
8366                         }
8367                         if (filterAppAccessLPr(ps, callingUid, userId)) {
8368                             return null;
8369                         }
8370                         ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8371                                 ps.readUserState(userId), userId);
8372                         if (ai != null) {
8373                             ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8374                         }
8375                     } else {
8376                         // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8377                         // and already converts to externally visible package name
8378                         ai = generateApplicationInfoFromSettingsLPw(ps.name,
8379                                 callingUid, effectiveFlags, userId);
8380                     }
8381                     if (ai != null) {
8382                         list.add(ai);
8383                     }
8384                 }
8385             } else {
8386                 list = new ArrayList<>(mPackages.size());
8387                 for (PackageParser.Package p : mPackages.values()) {
8388                     if (p.mExtras != null) {
8389                         PackageSetting ps = (PackageSetting) p.mExtras;
8390                         if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8391                             continue;
8392                         }
8393                         if (filterAppAccessLPr(ps, callingUid, userId)) {
8394                             return null;
8395                         }
8396                         ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8397                                 ps.readUserState(userId), userId);
8398                         if (ai != null) {
8399                             ai.packageName = resolveExternalPackageNameLPr(p);
8400                             list.add(ai);
8401                         }
8402                     }
8403                 }
8404             }
8405
8406             return new ParceledListSlice<>(list);
8407         }
8408     }
8409
8410     @Override
8411     public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8412         if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8413             return null;
8414         }
8415         mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8416                 "getEphemeralApplications");
8417         enforceCrossUserPermission(Binder.getCallingUid(), userId,
8418                 true /* requireFullPermission */, false /* checkShell */,
8419                 "getEphemeralApplications");
8420         synchronized (mPackages) {
8421             List<InstantAppInfo> instantApps = mInstantAppRegistry
8422                     .getInstantAppsLPr(userId);
8423             if (instantApps != null) {
8424                 return new ParceledListSlice<>(instantApps);
8425             }
8426         }
8427         return null;
8428     }
8429
8430     @Override
8431     public boolean isInstantApp(String packageName, int userId) {
8432         enforceCrossUserPermission(Binder.getCallingUid(), userId,
8433                 true /* requireFullPermission */, false /* checkShell */,
8434                 "isInstantApp");
8435         if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8436             return false;
8437         }
8438         int callingUid = Binder.getCallingUid();
8439         if (Process.isIsolated(callingUid)) {
8440             callingUid = mIsolatedOwners.get(callingUid);
8441         }
8442
8443         synchronized (mPackages) {
8444             final PackageSetting ps = mSettings.mPackages.get(packageName);
8445             PackageParser.Package pkg = mPackages.get(packageName);
8446             final boolean returnAllowed =
8447                     ps != null
8448                     && (isCallerSameApp(packageName, callingUid)
8449                             || canViewInstantApps(callingUid, userId)
8450                             || mInstantAppRegistry.isInstantAccessGranted(
8451                                     userId, UserHandle.getAppId(callingUid), ps.appId));
8452             if (returnAllowed) {
8453                 return ps.getInstantApp(userId);
8454             }
8455         }
8456         return false;
8457     }
8458
8459     @Override
8460     public byte[] getInstantAppCookie(String packageName, int userId) {
8461         if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8462             return null;
8463         }
8464
8465         enforceCrossUserPermission(Binder.getCallingUid(), userId,
8466                 true /* requireFullPermission */, false /* checkShell */,
8467                 "getInstantAppCookie");
8468         if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8469             return null;
8470         }
8471         synchronized (mPackages) {
8472             return mInstantAppRegistry.getInstantAppCookieLPw(
8473                     packageName, userId);
8474         }
8475     }
8476
8477     @Override
8478     public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8479         if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8480             return true;
8481         }
8482
8483         enforceCrossUserPermission(Binder.getCallingUid(), userId,
8484                 true /* requireFullPermission */, true /* checkShell */,
8485                 "setInstantAppCookie");
8486         if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8487             return false;
8488         }
8489         synchronized (mPackages) {
8490             return mInstantAppRegistry.setInstantAppCookieLPw(
8491                     packageName, cookie, userId);
8492         }
8493     }
8494
8495     @Override
8496     public Bitmap getInstantAppIcon(String packageName, int userId) {
8497         if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8498             return null;
8499         }
8500
8501         mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8502                 "getInstantAppIcon");
8503
8504         enforceCrossUserPermission(Binder.getCallingUid(), userId,
8505                 true /* requireFullPermission */, false /* checkShell */,
8506                 "getInstantAppIcon");
8507
8508         synchronized (mPackages) {
8509             return mInstantAppRegistry.getInstantAppIconLPw(
8510                     packageName, userId);
8511         }
8512     }
8513
8514     private boolean isCallerSameApp(String packageName, int uid) {
8515         PackageParser.Package pkg = mPackages.get(packageName);
8516         return pkg != null
8517                 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8518     }
8519
8520     @Override
8521     public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8522         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8523             return ParceledListSlice.emptyList();
8524         }
8525         return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8526     }
8527
8528     private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8529         final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8530
8531         // reader
8532         synchronized (mPackages) {
8533             final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8534             final int userId = UserHandle.getCallingUserId();
8535             while (i.hasNext()) {
8536                 final PackageParser.Package p = i.next();
8537                 if (p.applicationInfo == null) continue;
8538
8539                 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8540                         && !p.applicationInfo.isDirectBootAware();
8541                 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8542                         && p.applicationInfo.isDirectBootAware();
8543
8544                 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8545                         && (!mSafeMode || isSystemApp(p))
8546                         && (matchesUnaware || matchesAware)) {
8547                     PackageSetting ps = mSettings.mPackages.get(p.packageName);
8548                     if (ps != null) {
8549                         ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8550                                 ps.readUserState(userId), userId);
8551                         if (ai != null) {
8552                             finalList.add(ai);
8553                         }
8554                     }
8555                 }
8556             }
8557         }
8558
8559         return finalList;
8560     }
8561
8562     @Override
8563     public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8564         if (!sUserManager.exists(userId)) return null;
8565         flags = updateFlagsForComponent(flags, userId, name);
8566         final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8567         // reader
8568         synchronized (mPackages) {
8569             final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8570             PackageSetting ps = provider != null
8571                     ? mSettings.mPackages.get(provider.owner.packageName)
8572                     : null;
8573             if (ps != null) {
8574                 final boolean isInstantApp = ps.getInstantApp(userId);
8575                 // normal application; filter out instant application provider
8576                 if (instantAppPkgName == null && isInstantApp) {
8577                     return null;
8578                 }
8579                 // instant application; filter out other instant applications
8580                 if (instantAppPkgName != null
8581                         && isInstantApp
8582                         && !provider.owner.packageName.equals(instantAppPkgName)) {
8583                     return null;
8584                 }
8585                 // instant application; filter out non-exposed provider
8586                 if (instantAppPkgName != null
8587                         && !isInstantApp
8588                         && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8589                     return null;
8590                 }
8591                 // provider not enabled
8592                 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8593                     return null;
8594                 }
8595                 return PackageParser.generateProviderInfo(
8596                         provider, flags, ps.readUserState(userId), userId);
8597             }
8598             return null;
8599         }
8600     }
8601
8602     /**
8603      * @deprecated
8604      */
8605     @Deprecated
8606     public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8607         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8608             return;
8609         }
8610         // reader
8611         synchronized (mPackages) {
8612             final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8613                     .entrySet().iterator();
8614             final int userId = UserHandle.getCallingUserId();
8615             while (i.hasNext()) {
8616                 Map.Entry<String, PackageParser.Provider> entry = i.next();
8617                 PackageParser.Provider p = entry.getValue();
8618                 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8619
8620                 if (ps != null && p.syncable
8621                         && (!mSafeMode || (p.info.applicationInfo.flags
8622                                 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8623                     ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8624                             ps.readUserState(userId), userId);
8625                     if (info != null) {
8626                         outNames.add(entry.getKey());
8627                         outInfo.add(info);
8628                     }
8629                 }
8630             }
8631         }
8632     }
8633
8634     @Override
8635     public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8636             int uid, int flags, String metaDataKey) {
8637         final int callingUid = Binder.getCallingUid();
8638         final int userId = processName != null ? UserHandle.getUserId(uid)
8639                 : UserHandle.getCallingUserId();
8640         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8641         flags = updateFlagsForComponent(flags, userId, processName);
8642         ArrayList<ProviderInfo> finalList = null;
8643         // reader
8644         synchronized (mPackages) {
8645             final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8646             while (i.hasNext()) {
8647                 final PackageParser.Provider p = i.next();
8648                 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8649                 if (ps != null && p.info.authority != null
8650                         && (processName == null
8651                                 || (p.info.processName.equals(processName)
8652                                         && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8653                         && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8654
8655                     // See PM.queryContentProviders()'s javadoc for why we have the metaData
8656                     // parameter.
8657                     if (metaDataKey != null
8658                             && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8659                         continue;
8660                     }
8661                     final ComponentName component =
8662                             new ComponentName(p.info.packageName, p.info.name);
8663                     if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8664                         continue;
8665                     }
8666                     if (finalList == null) {
8667                         finalList = new ArrayList<ProviderInfo>(3);
8668                     }
8669                     ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8670                             ps.readUserState(userId), userId);
8671                     if (info != null) {
8672                         finalList.add(info);
8673                     }
8674                 }
8675             }
8676         }
8677
8678         if (finalList != null) {
8679             Collections.sort(finalList, mProviderInitOrderSorter);
8680             return new ParceledListSlice<ProviderInfo>(finalList);
8681         }
8682
8683         return ParceledListSlice.emptyList();
8684     }
8685
8686     @Override
8687     public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8688         // reader
8689         synchronized (mPackages) {
8690             final int callingUid = Binder.getCallingUid();
8691             final int callingUserId = UserHandle.getUserId(callingUid);
8692             final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8693             if (ps == null) return null;
8694             if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8695                 return null;
8696             }
8697             final PackageParser.Instrumentation i = mInstrumentation.get(component);
8698             return PackageParser.generateInstrumentationInfo(i, flags);
8699         }
8700     }
8701
8702     @Override
8703     public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8704             String targetPackage, int flags) {
8705         final int callingUid = Binder.getCallingUid();
8706         final int callingUserId = UserHandle.getUserId(callingUid);
8707         final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8708         if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8709             return ParceledListSlice.emptyList();
8710         }
8711         return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8712     }
8713
8714     private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8715             int flags) {
8716         ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8717
8718         // reader
8719         synchronized (mPackages) {
8720             final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8721             while (i.hasNext()) {
8722                 final PackageParser.Instrumentation p = i.next();
8723                 if (targetPackage == null
8724                         || targetPackage.equals(p.info.targetPackage)) {
8725                     InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8726                             flags);
8727                     if (ii != null) {
8728                         finalList.add(ii);
8729                     }
8730                 }
8731             }
8732         }
8733
8734         return finalList;
8735     }
8736
8737     private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8738         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8739         try {
8740             scanDirLI(dir, parseFlags, scanFlags, currentTime);
8741         } finally {
8742             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8743         }
8744     }
8745
8746     private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8747         final File[] files = dir.listFiles();
8748         if (ArrayUtils.isEmpty(files)) {
8749             Log.d(TAG, "No files in app dir " + dir);
8750             return;
8751         }
8752
8753         if (DEBUG_PACKAGE_SCANNING) {
8754             Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8755                     + " flags=0x" + Integer.toHexString(parseFlags));
8756         }
8757         ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8758                 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8759                 mParallelPackageParserCallback);
8760
8761         // Submit files for parsing in parallel
8762         int fileCount = 0;
8763         for (File file : files) {
8764             final boolean isPackage = (isApkFile(file) || file.isDirectory())
8765                     && !PackageInstallerService.isStageName(file.getName());
8766             if (!isPackage) {
8767                 // Ignore entries which are not packages
8768                 continue;
8769             }
8770             parallelPackageParser.submit(file, parseFlags);
8771             fileCount++;
8772         }
8773
8774         // Process results one by one
8775         for (; fileCount > 0; fileCount--) {
8776             ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8777             Throwable throwable = parseResult.throwable;
8778             int errorCode = PackageManager.INSTALL_SUCCEEDED;
8779
8780             if (throwable == null) {
8781                 // Static shared libraries have synthetic package names
8782                 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8783                     renameStaticSharedLibraryPackage(parseResult.pkg);
8784                 }
8785                 try {
8786                     if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8787                         scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8788                                 currentTime, null);
8789                     }
8790                 } catch (PackageManagerException e) {
8791                     errorCode = e.error;
8792                     Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8793                 }
8794             } else if (throwable instanceof PackageParser.PackageParserException) {
8795                 PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8796                         throwable;
8797                 errorCode = e.error;
8798                 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8799             } else {
8800                 throw new IllegalStateException("Unexpected exception occurred while parsing "
8801                         + parseResult.scanFile, throwable);
8802             }
8803
8804             // Delete invalid userdata apps
8805             if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8806                     errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8807                 logCriticalInfo(Log.WARN,
8808                         "Deleting invalid package at " + parseResult.scanFile);
8809                 removeCodePathLI(parseResult.scanFile);
8810             }
8811         }
8812         parallelPackageParser.close();
8813     }
8814
8815     private static File getSettingsProblemFile() {
8816         File dataDir = Environment.getDataDirectory();
8817         File systemDir = new File(dataDir, "system");
8818         File fname = new File(systemDir, "uiderrors.txt");
8819         return fname;
8820     }
8821
8822     static void reportSettingsProblem(int priority, String msg) {
8823         logCriticalInfo(priority, msg);
8824     }
8825
8826     public static void logCriticalInfo(int priority, String msg) {
8827         Slog.println(priority, TAG, msg);
8828         EventLogTags.writePmCriticalInfo(msg);
8829         try {
8830             File fname = getSettingsProblemFile();
8831             FileOutputStream out = new FileOutputStream(fname, true);
8832             PrintWriter pw = new FastPrintWriter(out);
8833             SimpleDateFormat formatter = new SimpleDateFormat();
8834             String dateString = formatter.format(new Date(System.currentTimeMillis()));
8835             pw.println(dateString + ": " + msg);
8836             pw.close();
8837             FileUtils.setPermissions(
8838                     fname.toString(),
8839                     FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8840                     -1, -1);
8841         } catch (java.io.IOException e) {
8842         }
8843     }
8844
8845     private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8846         if (srcFile.isDirectory()) {
8847             final File baseFile = new File(pkg.baseCodePath);
8848             long maxModifiedTime = baseFile.lastModified();
8849             if (pkg.splitCodePaths != null) {
8850                 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8851                     final File splitFile = new File(pkg.splitCodePaths[i]);
8852                     maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8853                 }
8854             }
8855             return maxModifiedTime;
8856         }
8857         return srcFile.lastModified();
8858     }
8859
8860     private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8861             final int policyFlags) throws PackageManagerException {
8862         // When upgrading from pre-N MR1, verify the package time stamp using the package
8863         // directory and not the APK file.
8864         final long lastModifiedTime = mIsPreNMR1Upgrade
8865                 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8866         if (ps != null
8867                 && ps.codePath.equals(srcFile)
8868                 && ps.timeStamp == lastModifiedTime
8869                 && !isCompatSignatureUpdateNeeded(pkg)
8870                 && !isRecoverSignatureUpdateNeeded(pkg)) {
8871             long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8872             KeySetManagerService ksms = mSettings.mKeySetManagerService;
8873             ArraySet<PublicKey> signingKs;
8874             synchronized (mPackages) {
8875                 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8876             }
8877             if (ps.signatures.mSignatures != null
8878                     && ps.signatures.mSignatures.length != 0
8879                     && signingKs != null) {
8880                 // Optimization: reuse the existing cached certificates
8881                 // if the package appears to be unchanged.
8882                 pkg.mSignatures = ps.signatures.mSignatures;
8883                 pkg.mSigningKeys = signingKs;
8884                 return;
8885             }
8886
8887             Slog.w(TAG, "PackageSetting for " + ps.name
8888                     + " is missing signatures.  Collecting certs again to recover them.");
8889         } else {
8890             Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8891         }
8892
8893         try {
8894             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8895             PackageParser.collectCertificates(pkg, policyFlags);
8896         } catch (PackageParserException e) {
8897             throw PackageManagerException.from(e);
8898         } finally {
8899             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8900         }
8901     }
8902
8903     /**
8904      *  Traces a package scan.
8905      *  @see #scanPackageLI(File, int, int, long, UserHandle)
8906      */
8907     private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8908             int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8909         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8910         try {
8911             return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8912         } finally {
8913             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8914         }
8915     }
8916
8917     /**
8918      *  Scans a package and returns the newly parsed package.
8919      *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8920      */
8921     private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8922             long currentTime, UserHandle user) throws PackageManagerException {
8923         if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8924         PackageParser pp = new PackageParser();
8925         pp.setSeparateProcesses(mSeparateProcesses);
8926         pp.setOnlyCoreApps(mOnlyCore);
8927         pp.setDisplayMetrics(mMetrics);
8928         pp.setCallback(mPackageParserCallback);
8929
8930         if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8931             parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8932         }
8933
8934         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8935         final PackageParser.Package pkg;
8936         try {
8937             pkg = pp.parsePackage(scanFile, parseFlags);
8938         } catch (PackageParserException e) {
8939             throw PackageManagerException.from(e);
8940         } finally {
8941             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8942         }
8943
8944         // Static shared libraries have synthetic package names
8945         if (pkg.applicationInfo.isStaticSharedLibrary()) {
8946             renameStaticSharedLibraryPackage(pkg);
8947         }
8948
8949         return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8950     }
8951
8952     /**
8953      *  Scans a package and returns the newly parsed package.
8954      *  @throws PackageManagerException on a parse error.
8955      */
8956     private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8957             final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8958             throws PackageManagerException {
8959         // If the package has children and this is the first dive in the function
8960         // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8961         // packages (parent and children) would be successfully scanned before the
8962         // actual scan since scanning mutates internal state and we want to atomically
8963         // install the package and its children.
8964         if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8965             if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8966                 scanFlags |= SCAN_CHECK_ONLY;
8967             }
8968         } else {
8969             scanFlags &= ~SCAN_CHECK_ONLY;
8970         }
8971
8972         // Scan the parent
8973         PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8974                 scanFlags, currentTime, user);
8975
8976         // Scan the children
8977         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8978         for (int i = 0; i < childCount; i++) {
8979             PackageParser.Package childPackage = pkg.childPackages.get(i);
8980             scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8981                     currentTime, user);
8982         }
8983
8984
8985         if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8986             return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8987         }
8988
8989         return scannedPkg;
8990     }
8991
8992     /**
8993      *  Scans a package and returns the newly parsed package.
8994      *  @throws PackageManagerException on a parse error.
8995      */
8996     private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8997             int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8998             throws PackageManagerException {
8999         PackageSetting ps = null;
9000         PackageSetting updatedPkg;
9001         // reader
9002         synchronized (mPackages) {
9003             // Look to see if we already know about this package.
9004             String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9005             if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9006                 // This package has been renamed to its original name.  Let's
9007                 // use that.
9008                 ps = mSettings.getPackageLPr(oldName);
9009             }
9010             // If there was no original package, see one for the real package name.
9011             if (ps == null) {
9012                 ps = mSettings.getPackageLPr(pkg.packageName);
9013             }
9014             // Check to see if this package could be hiding/updating a system
9015             // package.  Must look for it either under the original or real
9016             // package name depending on our state.
9017             updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9018             if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9019
9020             // If this is a package we don't know about on the system partition, we
9021             // may need to remove disabled child packages on the system partition
9022             // or may need to not add child packages if the parent apk is updated
9023             // on the data partition and no longer defines this child package.
9024             if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9025                 // If this is a parent package for an updated system app and this system
9026                 // app got an OTA update which no longer defines some of the child packages
9027                 // we have to prune them from the disabled system packages.
9028                 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9029                 if (disabledPs != null) {
9030                     final int scannedChildCount = (pkg.childPackages != null)
9031                             ? pkg.childPackages.size() : 0;
9032                     final int disabledChildCount = disabledPs.childPackageNames != null
9033                             ? disabledPs.childPackageNames.size() : 0;
9034                     for (int i = 0; i < disabledChildCount; i++) {
9035                         String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9036                         boolean disabledPackageAvailable = false;
9037                         for (int j = 0; j < scannedChildCount; j++) {
9038                             PackageParser.Package childPkg = pkg.childPackages.get(j);
9039                             if (childPkg.packageName.equals(disabledChildPackageName)) {
9040                                 disabledPackageAvailable = true;
9041                                 break;
9042                             }
9043                          }
9044                          if (!disabledPackageAvailable) {
9045                              mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9046                          }
9047                     }
9048                 }
9049             }
9050         }
9051
9052         boolean updatedPkgBetter = false;
9053         // First check if this is a system package that may involve an update
9054         if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9055             // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9056             // it needs to drop FLAG_PRIVILEGED.
9057             if (locationIsPrivileged(scanFile)) {
9058                 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9059             } else {
9060                 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9061             }
9062
9063             if (ps != null && !ps.codePath.equals(scanFile)) {
9064                 // The path has changed from what was last scanned...  check the
9065                 // version of the new path against what we have stored to determine
9066                 // what to do.
9067                 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9068                 if (pkg.mVersionCode <= ps.versionCode) {
9069                     // The system package has been updated and the code path does not match
9070                     // Ignore entry. Skip it.
9071                     if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9072                             + " ignored: updated version " + ps.versionCode
9073                             + " better than this " + pkg.mVersionCode);
9074                     if (!updatedPkg.codePath.equals(scanFile)) {
9075                         Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9076                                 + ps.name + " changing from " + updatedPkg.codePathString
9077                                 + " to " + scanFile);
9078                         updatedPkg.codePath = scanFile;
9079                         updatedPkg.codePathString = scanFile.toString();
9080                         updatedPkg.resourcePath = scanFile;
9081                         updatedPkg.resourcePathString = scanFile.toString();
9082                     }
9083                     updatedPkg.pkg = pkg;
9084                     updatedPkg.versionCode = pkg.mVersionCode;
9085
9086                     // Update the disabled system child packages to point to the package too.
9087                     final int childCount = updatedPkg.childPackageNames != null
9088                             ? updatedPkg.childPackageNames.size() : 0;
9089                     for (int i = 0; i < childCount; i++) {
9090                         String childPackageName = updatedPkg.childPackageNames.get(i);
9091                         PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9092                                 childPackageName);
9093                         if (updatedChildPkg != null) {
9094                             updatedChildPkg.pkg = pkg;
9095                             updatedChildPkg.versionCode = pkg.mVersionCode;
9096                         }
9097                     }
9098
9099                     throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9100                             + scanFile + " ignored: updated version " + ps.versionCode
9101                             + " better than this " + pkg.mVersionCode);
9102                 } else {
9103                     // The current app on the system partition is better than
9104                     // what we have updated to on the data partition; switch
9105                     // back to the system partition version.
9106                     // At this point, its safely assumed that package installation for
9107                     // apps in system partition will go through. If not there won't be a working
9108                     // version of the app
9109                     // writer
9110                     synchronized (mPackages) {
9111                         // Just remove the loaded entries from package lists.
9112                         mPackages.remove(ps.name);
9113                     }
9114
9115                     logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9116                             + " reverting from " + ps.codePathString
9117                             + ": new version " + pkg.mVersionCode
9118                             + " better than installed " + ps.versionCode);
9119
9120                     InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9121                             ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9122                     synchronized (mInstallLock) {
9123                         args.cleanUpResourcesLI();
9124                     }
9125                     synchronized (mPackages) {
9126                         mSettings.enableSystemPackageLPw(ps.name);
9127                     }
9128                     updatedPkgBetter = true;
9129                 }
9130             }
9131         }
9132
9133         if (updatedPkg != null) {
9134             // An updated system app will not have the PARSE_IS_SYSTEM flag set
9135             // initially
9136             policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9137
9138             // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9139             // flag set initially
9140             if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9141                 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9142             }
9143         }
9144
9145         // Verify certificates against what was last scanned
9146         collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9147
9148         /*
9149          * A new system app appeared, but we already had a non-system one of the
9150          * same name installed earlier.
9151          */
9152         boolean shouldHideSystemApp = false;
9153         if (updatedPkg == null && ps != null
9154                 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9155             /*
9156              * Check to make sure the signatures match first. If they don't,
9157              * wipe the installed application and its data.
9158              */
9159             if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9160                     != PackageManager.SIGNATURE_MATCH) {
9161                 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9162                         + " signatures don't match existing userdata copy; removing");
9163                 try (PackageFreezer freezer = freezePackage(pkg.packageName,
9164                         "scanPackageInternalLI")) {
9165                     deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9166                 }
9167                 ps = null;
9168             } else {
9169                 /*
9170                  * If the newly-added system app is an older version than the
9171                  * already installed version, hide it. It will be scanned later
9172                  * and re-added like an update.
9173                  */
9174                 if (pkg.mVersionCode <= ps.versionCode) {
9175                     shouldHideSystemApp = true;
9176                     logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9177                             + " but new version " + pkg.mVersionCode + " better than installed "
9178                             + ps.versionCode + "; hiding system");
9179                 } else {
9180                     /*
9181                      * The newly found system app is a newer version that the
9182                      * one previously installed. Simply remove the
9183                      * already-installed application and replace it with our own
9184                      * while keeping the application data.
9185                      */
9186                     logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9187                             + " reverting from " + ps.codePathString + ": new version "
9188                             + pkg.mVersionCode + " better than installed " + ps.versionCode);
9189                     InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9190                             ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9191                     synchronized (mInstallLock) {
9192                         args.cleanUpResourcesLI();
9193                     }
9194                 }
9195             }
9196         }
9197
9198         // The apk is forward locked (not public) if its code and resources
9199         // are kept in different files. (except for app in either system or
9200         // vendor path).
9201         // TODO grab this value from PackageSettings
9202         if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9203             if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9204                 policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9205             }
9206         }
9207
9208         // TODO: extend to support forward-locked splits
9209         String resourcePath = null;
9210         String baseResourcePath = null;
9211         if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
9212             if (ps != null && ps.resourcePathString != null) {
9213                 resourcePath = ps.resourcePathString;
9214                 baseResourcePath = ps.resourcePathString;
9215             } else {
9216                 // Should not happen at all. Just log an error.
9217                 Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9218             }
9219         } else {
9220             resourcePath = pkg.codePath;
9221             baseResourcePath = pkg.baseCodePath;
9222         }
9223
9224         // Set application objects path explicitly.
9225         pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9226         pkg.setApplicationInfoCodePath(pkg.codePath);
9227         pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9228         pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9229         pkg.setApplicationInfoResourcePath(resourcePath);
9230         pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9231         pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9232
9233         final int userId = ((user == null) ? 0 : user.getIdentifier());
9234         if (ps != null && ps.getInstantApp(userId)) {
9235             scanFlags |= SCAN_AS_INSTANT_APP;
9236         }
9237
9238         // Note that we invoke the following method only if we are about to unpack an application
9239         PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9240                 | SCAN_UPDATE_SIGNATURE, currentTime, user);
9241
9242         /*
9243          * If the system app should be overridden by a previously installed
9244          * data, hide the system app now and let the /data/app scan pick it up
9245          * again.
9246          */
9247         if (shouldHideSystemApp) {
9248             synchronized (mPackages) {
9249                 mSettings.disableSystemPackageLPw(pkg.packageName, true);
9250             }
9251         }
9252
9253         return scannedPkg;
9254     }
9255
9256     private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9257         // Derive the new package synthetic package name
9258         pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9259                 + pkg.staticSharedLibVersion);
9260     }
9261
9262     private static String fixProcessName(String defProcessName,
9263             String processName) {
9264         if (processName == null) {
9265             return defProcessName;
9266         }
9267         return processName;
9268     }
9269
9270     private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9271             throws PackageManagerException {
9272         if (pkgSetting.signatures.mSignatures != null) {
9273             // Already existing package. Make sure signatures match
9274             boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9275                     == PackageManager.SIGNATURE_MATCH;
9276             if (!match) {
9277                 match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9278                         == PackageManager.SIGNATURE_MATCH;
9279             }
9280             if (!match) {
9281                 match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9282                         == PackageManager.SIGNATURE_MATCH;
9283             }
9284             if (!match) {
9285                 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9286                         + pkg.packageName + " signatures do not match the "
9287                         + "previously installed version; ignoring!");
9288             }
9289         }
9290
9291         // Check for shared user signatures
9292         if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9293             // Already existing package. Make sure signatures match
9294             boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9295                     pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9296             if (!match) {
9297                 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9298                         == PackageManager.SIGNATURE_MATCH;
9299             }
9300             if (!match) {
9301                 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9302                         == PackageManager.SIGNATURE_MATCH;
9303             }
9304             if (!match) {
9305                 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9306                         "Package " + pkg.packageName
9307                         + " has no signatures that match those in shared user "
9308                         + pkgSetting.sharedUser.name + "; ignoring!");
9309             }
9310         }
9311     }
9312
9313     /**
9314      * Enforces that only the system UID or root's UID can call a method exposed
9315      * via Binder.
9316      *
9317      * @param message used as message if SecurityException is thrown
9318      * @throws SecurityException if the caller is not system or root
9319      */
9320     private static final void enforceSystemOrRoot(String message) {
9321         final int uid = Binder.getCallingUid();
9322         if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9323             throw new SecurityException(message);
9324         }
9325     }
9326
9327     @Override
9328     public void performFstrimIfNeeded() {
9329         enforceSystemOrRoot("Only the system can request fstrim");
9330
9331         // Before everything else, see whether we need to fstrim.
9332         try {
9333             IStorageManager sm = PackageHelper.getStorageManager();
9334             if (sm != null) {
9335                 boolean doTrim = false;
9336                 final long interval = android.provider.Settings.Global.getLong(
9337                         mContext.getContentResolver(),
9338                         android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9339                         DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9340                 if (interval > 0) {
9341                     final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9342                     if (timeSinceLast > interval) {
9343                         doTrim = true;
9344                         Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9345                                 + "; running immediately");
9346                     }
9347                 }
9348                 if (doTrim) {
9349                     final boolean dexOptDialogShown;
9350                     synchronized (mPackages) {
9351                         dexOptDialogShown = mDexOptDialogShown;
9352                     }
9353                     if (!isFirstBoot() && dexOptDialogShown) {
9354                         try {
9355                             ActivityManager.getService().showBootMessage(
9356                                     mContext.getResources().getString(
9357                                             R.string.android_upgrading_fstrim), true);
9358                         } catch (RemoteException e) {
9359                         }
9360                     }
9361                     sm.runMaintenance();
9362                 }
9363             } else {
9364                 Slog.e(TAG, "storageManager service unavailable!");
9365             }
9366         } catch (RemoteException e) {
9367             // Can't happen; StorageManagerService is local
9368         }
9369     }
9370
9371     @Override
9372     public void updatePackagesIfNeeded() {
9373         enforceSystemOrRoot("Only the system can request package update");
9374
9375         // We need to re-extract after an OTA.
9376         boolean causeUpgrade = isUpgrade();
9377
9378         // First boot or factory reset.
9379         // Note: we also handle devices that are upgrading to N right now as if it is their
9380         //       first boot, as they do not have profile data.
9381         boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9382
9383         // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9384         boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9385
9386         if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9387             return;
9388         }
9389
9390         List<PackageParser.Package> pkgs;
9391         synchronized (mPackages) {
9392             pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9393         }
9394
9395         final long startTime = System.nanoTime();
9396         final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9397                     getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
9398
9399         final int elapsedTimeSeconds =
9400                 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9401
9402         MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9403         MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9404         MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9405         MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9406         MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9407     }
9408
9409     /**
9410      * Performs dexopt on the set of packages in {@code packages} and returns an int array
9411      * containing statistics about the invocation. The array consists of three elements,
9412      * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9413      * and {@code numberOfPackagesFailed}.
9414      */
9415     private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9416             String compilerFilter) {
9417
9418         int numberOfPackagesVisited = 0;
9419         int numberOfPackagesOptimized = 0;
9420         int numberOfPackagesSkipped = 0;
9421         int numberOfPackagesFailed = 0;
9422         final int numberOfPackagesToDexopt = pkgs.size();
9423
9424         for (PackageParser.Package pkg : pkgs) {
9425             numberOfPackagesVisited++;
9426
9427             if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9428                 if (DEBUG_DEXOPT) {
9429                     Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9430                 }
9431                 numberOfPackagesSkipped++;
9432                 continue;
9433             }
9434
9435             if (DEBUG_DEXOPT) {
9436                 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9437                         numberOfPackagesToDexopt + ": " + pkg.packageName);
9438             }
9439
9440             if (showDialog) {
9441                 try {
9442                     ActivityManager.getService().showBootMessage(
9443                             mContext.getResources().getString(R.string.android_upgrading_apk,
9444                                     numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9445                 } catch (RemoteException e) {
9446                 }
9447                 synchronized (mPackages) {
9448                     mDexOptDialogShown = true;
9449                 }
9450             }
9451
9452             // If the OTA updates a system app which was previously preopted to a non-preopted state
9453             // the app might end up being verified at runtime. That's because by default the apps
9454             // are verify-profile but for preopted apps there's no profile.
9455             // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9456             // that before the OTA the app was preopted) the app gets compiled with a non-profile
9457             // filter (by default 'quicken').
9458             // Note that at this stage unused apps are already filtered.
9459             if (isSystemApp(pkg) &&
9460                     DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9461                     !Environment.getReferenceProfile(pkg.packageName).exists()) {
9462                 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9463             }
9464
9465             // checkProfiles is false to avoid merging profiles during boot which
9466             // might interfere with background compilation (b/28612421).
9467             // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9468             // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9469             // trade-off worth doing to save boot time work.
9470             int dexOptStatus = performDexOptTraced(pkg.packageName,
9471                     false /* checkProfiles */,
9472                     compilerFilter,
9473                     false /* force */);
9474             switch (dexOptStatus) {
9475                 case PackageDexOptimizer.DEX_OPT_PERFORMED:
9476                     numberOfPackagesOptimized++;
9477                     break;
9478                 case PackageDexOptimizer.DEX_OPT_SKIPPED:
9479                     numberOfPackagesSkipped++;
9480                     break;
9481                 case PackageDexOptimizer.DEX_OPT_FAILED:
9482                     numberOfPackagesFailed++;
9483                     break;
9484                 default:
9485                     Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
9486                     break;
9487             }
9488         }
9489
9490         return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9491                 numberOfPackagesFailed };
9492     }
9493
9494     @Override
9495     public void notifyPackageUse(String packageName, int reason) {
9496         synchronized (mPackages) {
9497             final int callingUid = Binder.getCallingUid();
9498             final int callingUserId = UserHandle.getUserId(callingUid);
9499             if (getInstantAppPackageName(callingUid) != null) {
9500                 if (!isCallerSameApp(packageName, callingUid)) {
9501                     return;
9502                 }
9503             } else {
9504                 if (isInstantApp(packageName, callingUserId)) {
9505                     return;
9506                 }
9507             }
9508             final PackageParser.Package p = mPackages.get(packageName);
9509             if (p == null) {
9510                 return;
9511             }
9512             p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9513         }
9514     }
9515
9516     @Override
9517     public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9518         int userId = UserHandle.getCallingUserId();
9519         ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9520         if (ai == null) {
9521             Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9522                 + loadingPackageName + ", user=" + userId);
9523             return;
9524         }
9525         mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9526     }
9527
9528     @Override
9529     public boolean performDexOpt(String packageName,
9530             boolean checkProfiles, int compileReason, boolean force) {
9531         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9532             return false;
9533         } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9534             return false;
9535         }
9536         return performDexOptWithStatus(packageName, checkProfiles, compileReason, force) !=
9537                 PackageDexOptimizer.DEX_OPT_FAILED;
9538     }
9539
9540     /**
9541      * Perform dexopt on the given package and return one of following result:
9542      *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9543      *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9544      *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9545      */
9546     /* package */ int performDexOptWithStatus(String packageName,
9547             boolean checkProfiles, int compileReason, boolean force) {
9548         return performDexOptTraced(packageName, checkProfiles,
9549                 getCompilerFilterForReason(compileReason), force);
9550     }
9551
9552     @Override
9553     public boolean performDexOptMode(String packageName,
9554             boolean checkProfiles, String targetCompilerFilter, boolean force) {
9555         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9556             return false;
9557         } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9558             return false;
9559         }
9560         int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
9561                 targetCompilerFilter, force);
9562         return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9563     }
9564
9565     private int performDexOptTraced(String packageName,
9566                 boolean checkProfiles, String targetCompilerFilter, boolean force) {
9567         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9568         try {
9569             return performDexOptInternal(packageName, checkProfiles,
9570                     targetCompilerFilter, force);
9571         } finally {
9572             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9573         }
9574     }
9575
9576     // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9577     // if the package can now be considered up to date for the given filter.
9578     private int performDexOptInternal(String packageName,
9579                 boolean checkProfiles, String targetCompilerFilter, boolean force) {
9580         PackageParser.Package p;
9581         synchronized (mPackages) {
9582             p = mPackages.get(packageName);
9583             if (p == null) {
9584                 // Package could not be found. Report failure.
9585                 return PackageDexOptimizer.DEX_OPT_FAILED;
9586             }
9587             mPackageUsage.maybeWriteAsync(mPackages);
9588             mCompilerStats.maybeWriteAsync();
9589         }
9590         long callingId = Binder.clearCallingIdentity();
9591         try {
9592             synchronized (mInstallLock) {
9593                 return performDexOptInternalWithDependenciesLI(p, checkProfiles,
9594                         targetCompilerFilter, force);
9595             }
9596         } finally {
9597             Binder.restoreCallingIdentity(callingId);
9598         }
9599     }
9600
9601     public ArraySet<String> getOptimizablePackages() {
9602         ArraySet<String> pkgs = new ArraySet<String>();
9603         synchronized (mPackages) {
9604             for (PackageParser.Package p : mPackages.values()) {
9605                 if (PackageDexOptimizer.canOptimizePackage(p)) {
9606                     pkgs.add(p.packageName);
9607                 }
9608             }
9609         }
9610         return pkgs;
9611     }
9612
9613     private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9614             boolean checkProfiles, String targetCompilerFilter,
9615             boolean force) {
9616         // Select the dex optimizer based on the force parameter.
9617         // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9618         //       allocate an object here.
9619         PackageDexOptimizer pdo = force
9620                 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9621                 : mPackageDexOptimizer;
9622
9623         // Dexopt all dependencies first. Note: we ignore the return value and march on
9624         // on errors.
9625         // Note that we are going to call performDexOpt on those libraries as many times as
9626         // they are referenced in packages. When we do a batch of performDexOpt (for example
9627         // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9628         // and the first package that uses the library will dexopt it. The
9629         // others will see that the compiled code for the library is up to date.
9630         Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9631         final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9632         if (!deps.isEmpty()) {
9633             for (PackageParser.Package depPackage : deps) {
9634                 // TODO: Analyze and investigate if we (should) profile libraries.
9635                 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9636                         false /* checkProfiles */,
9637                         targetCompilerFilter,
9638                         getOrCreateCompilerPackageStats(depPackage),
9639                         true /* isUsedByOtherApps */);
9640             }
9641         }
9642         return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
9643                 targetCompilerFilter, getOrCreateCompilerPackageStats(p),
9644                 mDexManager.isUsedByOtherApps(p.packageName));
9645     }
9646
9647     // Performs dexopt on the used secondary dex files belonging to the given package.
9648     // Returns true if all dex files were process successfully (which could mean either dexopt or
9649     // skip). Returns false if any of the files caused errors.
9650     @Override
9651     public boolean performDexOptSecondary(String packageName, String compilerFilter,
9652             boolean force) {
9653         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9654             return false;
9655         } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9656             return false;
9657         }
9658         mDexManager.reconcileSecondaryDexFiles(packageName);
9659         return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
9660     }
9661
9662     public boolean performDexOptSecondary(String packageName, int compileReason,
9663             boolean force) {
9664         return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
9665     }
9666
9667     /**
9668      * Reconcile the information we have about the secondary dex files belonging to
9669      * {@code packagName} and the actual dex files. For all dex files that were
9670      * deleted, update the internal records and delete the generated oat files.
9671      */
9672     @Override
9673     public void reconcileSecondaryDexFiles(String packageName) {
9674         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9675             return;
9676         } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9677             return;
9678         }
9679         mDexManager.reconcileSecondaryDexFiles(packageName);
9680     }
9681
9682     // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9683     // a reference there.
9684     /*package*/ DexManager getDexManager() {
9685         return mDexManager;
9686     }
9687
9688     /**
9689      * Execute the background dexopt job immediately.
9690      */
9691     @Override
9692     public boolean runBackgroundDexoptJob() {
9693         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9694             return false;
9695         }
9696         return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9697     }
9698
9699     List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9700         if (p.usesLibraries != null || p.usesOptionalLibraries != null
9701                 || p.usesStaticLibraries != null) {
9702             ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9703             Set<String> collectedNames = new HashSet<>();
9704             findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9705
9706             retValue.remove(p);
9707
9708             return retValue;
9709         } else {
9710             return Collections.emptyList();
9711         }
9712     }
9713
9714     private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9715             ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9716         if (!collectedNames.contains(p.packageName)) {
9717             collectedNames.add(p.packageName);
9718             collected.add(p);
9719
9720             if (p.usesLibraries != null) {
9721                 findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9722                         null, collected, collectedNames);
9723             }
9724             if (p.usesOptionalLibraries != null) {
9725                 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9726                         null, collected, collectedNames);
9727             }
9728             if (p.usesStaticLibraries != null) {
9729                 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9730                         p.usesStaticLibrariesVersions, collected, collectedNames);
9731             }
9732         }
9733     }
9734
9735     private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9736             ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9737         final int libNameCount = libs.size();
9738         for (int i = 0; i < libNameCount; i++) {
9739             String libName = libs.get(i);
9740             int version = (versions != null && versions.length == libNameCount)
9741                     ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9742             PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9743             if (libPkg != null) {
9744                 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9745             }
9746         }
9747     }
9748
9749     private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9750         synchronized (mPackages) {
9751             SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9752             if (libEntry != null) {
9753                 return mPackages.get(libEntry.apk);
9754             }
9755             return null;
9756         }
9757     }
9758
9759     private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9760         SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9761         if (versionedLib == null) {
9762             return null;
9763         }
9764         return versionedLib.get(version);
9765     }
9766
9767     private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9768         SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9769                 pkg.staticSharedLibName);
9770         if (versionedLib == null) {
9771             return null;
9772         }
9773         int previousLibVersion = -1;
9774         final int versionCount = versionedLib.size();
9775         for (int i = 0; i < versionCount; i++) {
9776             final int libVersion = versionedLib.keyAt(i);
9777             if (libVersion < pkg.staticSharedLibVersion) {
9778                 previousLibVersion = Math.max(previousLibVersion, libVersion);
9779             }
9780         }
9781         if (previousLibVersion >= 0) {
9782             return versionedLib.get(previousLibVersion);
9783         }
9784         return null;
9785     }
9786
9787     public void shutdown() {
9788         mPackageUsage.writeNow(mPackages);
9789         mCompilerStats.writeNow();
9790     }
9791
9792     @Override
9793     public void dumpProfiles(String packageName) {
9794         PackageParser.Package pkg;
9795         synchronized (mPackages) {
9796             pkg = mPackages.get(packageName);
9797             if (pkg == null) {
9798                 throw new IllegalArgumentException("Unknown package: " + packageName);
9799             }
9800         }
9801         /* Only the shell, root, or the app user should be able to dump profiles. */
9802         int callingUid = Binder.getCallingUid();
9803         if (callingUid != Process.SHELL_UID &&
9804             callingUid != Process.ROOT_UID &&
9805             callingUid != pkg.applicationInfo.uid) {
9806             throw new SecurityException("dumpProfiles");
9807         }
9808
9809         synchronized (mInstallLock) {
9810             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9811             final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9812             try {
9813                 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9814                 String codePaths = TextUtils.join(";", allCodePaths);
9815                 mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9816             } catch (InstallerException e) {
9817                 Slog.w(TAG, "Failed to dump profiles", e);
9818             }
9819             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9820         }
9821     }
9822
9823     @Override
9824     public void forceDexOpt(String packageName) {
9825         enforceSystemOrRoot("forceDexOpt");
9826
9827         PackageParser.Package pkg;
9828         synchronized (mPackages) {
9829             pkg = mPackages.get(packageName);
9830             if (pkg == null) {
9831                 throw new IllegalArgumentException("Unknown package: " + packageName);
9832             }
9833         }
9834
9835         synchronized (mInstallLock) {
9836             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9837
9838             // Whoever is calling forceDexOpt wants a compiled package.
9839             // Don't use profiles since that may cause compilation to be skipped.
9840             final int res = performDexOptInternalWithDependenciesLI(pkg,
9841                     false /* checkProfiles */, getDefaultCompilerFilter(),
9842                     true /* force */);
9843
9844             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9845             if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9846                 throw new IllegalStateException("Failed to dexopt: " + res);
9847             }
9848         }
9849     }
9850
9851     private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9852         if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9853             Slog.w(TAG, "Unable to update from " + oldPkg.name
9854                     + " to " + newPkg.packageName
9855                     + ": old package not in system partition");
9856             return false;
9857         } else if (mPackages.get(oldPkg.name) != null) {
9858             Slog.w(TAG, "Unable to update from " + oldPkg.name
9859                     + " to " + newPkg.packageName
9860                     + ": old package still exists");
9861             return false;
9862         }
9863         return true;
9864     }
9865
9866     void removeCodePathLI(File codePath) {
9867         if (codePath.isDirectory()) {
9868             try {
9869                 mInstaller.rmPackageDir(codePath.getAbsolutePath());
9870             } catch (InstallerException e) {
9871                 Slog.w(TAG, "Failed to remove code path", e);
9872             }
9873         } else {
9874             codePath.delete();
9875         }
9876     }
9877
9878     private int[] resolveUserIds(int userId) {
9879         return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9880     }
9881
9882     private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9883         if (pkg == null) {
9884             Slog.wtf(TAG, "Package was null!", new Throwable());
9885             return;
9886         }
9887         clearAppDataLeafLIF(pkg, userId, flags);
9888         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9889         for (int i = 0; i < childCount; i++) {
9890             clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9891         }
9892     }
9893
9894     private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9895         final PackageSetting ps;
9896         synchronized (mPackages) {
9897             ps = mSettings.mPackages.get(pkg.packageName);
9898         }
9899         for (int realUserId : resolveUserIds(userId)) {
9900             final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9901             try {
9902                 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9903                         ceDataInode);
9904             } catch (InstallerException e) {
9905                 Slog.w(TAG, String.valueOf(e));
9906             }
9907         }
9908     }
9909
9910     private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9911         if (pkg == null) {
9912             Slog.wtf(TAG, "Package was null!", new Throwable());
9913             return;
9914         }
9915         destroyAppDataLeafLIF(pkg, userId, flags);
9916         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9917         for (int i = 0; i < childCount; i++) {
9918             destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9919         }
9920     }
9921
9922     private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9923         final PackageSetting ps;
9924         synchronized (mPackages) {
9925             ps = mSettings.mPackages.get(pkg.packageName);
9926         }
9927         for (int realUserId : resolveUserIds(userId)) {
9928             final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9929             try {
9930                 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9931                         ceDataInode);
9932             } catch (InstallerException e) {
9933                 Slog.w(TAG, String.valueOf(e));
9934             }
9935             mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9936         }
9937     }
9938
9939     private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9940         if (pkg == null) {
9941             Slog.wtf(TAG, "Package was null!", new Throwable());
9942             return;
9943         }
9944         destroyAppProfilesLeafLIF(pkg);
9945         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9946         for (int i = 0; i < childCount; i++) {
9947             destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9948         }
9949     }
9950
9951     private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9952         try {
9953             mInstaller.destroyAppProfiles(pkg.packageName);
9954         } catch (InstallerException e) {
9955             Slog.w(TAG, String.valueOf(e));
9956         }
9957     }
9958
9959     private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9960         if (pkg == null) {
9961             Slog.wtf(TAG, "Package was null!", new Throwable());
9962             return;
9963         }
9964         clearAppProfilesLeafLIF(pkg);
9965         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9966         for (int i = 0; i < childCount; i++) {
9967             clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9968         }
9969     }
9970
9971     private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9972         try {
9973             mInstaller.clearAppProfiles(pkg.packageName);
9974         } catch (InstallerException e) {
9975             Slog.w(TAG, String.valueOf(e));
9976         }
9977     }
9978
9979     private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9980             long lastUpdateTime) {
9981         // Set parent install/update time
9982         PackageSetting ps = (PackageSetting) pkg.mExtras;
9983         if (ps != null) {
9984             ps.firstInstallTime = firstInstallTime;
9985             ps.lastUpdateTime = lastUpdateTime;
9986         }
9987         // Set children install/update time
9988         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9989         for (int i = 0; i < childCount; i++) {
9990             PackageParser.Package childPkg = pkg.childPackages.get(i);
9991             ps = (PackageSetting) childPkg.mExtras;
9992             if (ps != null) {
9993                 ps.firstInstallTime = firstInstallTime;
9994                 ps.lastUpdateTime = lastUpdateTime;
9995             }
9996         }
9997     }
9998
9999     private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
10000             PackageParser.Package changingLib) {
10001         if (file.path != null) {
10002             usesLibraryFiles.add(file.path);
10003             return;
10004         }
10005         PackageParser.Package p = mPackages.get(file.apk);
10006         if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10007             // If we are doing this while in the middle of updating a library apk,
10008             // then we need to make sure to use that new apk for determining the
10009             // dependencies here.  (We haven't yet finished committing the new apk
10010             // to the package manager state.)
10011             if (p == null || p.packageName.equals(changingLib.packageName)) {
10012                 p = changingLib;
10013             }
10014         }
10015         if (p != null) {
10016             usesLibraryFiles.addAll(p.getAllCodePaths());
10017             if (p.usesLibraryFiles != null) {
10018                 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10019             }
10020         }
10021     }
10022
10023     private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10024             PackageParser.Package changingLib) throws PackageManagerException {
10025         if (pkg == null) {
10026             return;
10027         }
10028         ArraySet<String> usesLibraryFiles = null;
10029         if (pkg.usesLibraries != null) {
10030             usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10031                     null, null, pkg.packageName, changingLib, true, null);
10032         }
10033         if (pkg.usesStaticLibraries != null) {
10034             usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10035                     pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10036                     pkg.packageName, changingLib, true, usesLibraryFiles);
10037         }
10038         if (pkg.usesOptionalLibraries != null) {
10039             usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10040                     null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
10041         }
10042         if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10043             pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10044         } else {
10045             pkg.usesLibraryFiles = null;
10046         }
10047     }
10048
10049     private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10050             @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
10051             @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10052             boolean required, @Nullable ArraySet<String> outUsedLibraries)
10053             throws PackageManagerException {
10054         final int libCount = requestedLibraries.size();
10055         for (int i = 0; i < libCount; i++) {
10056             final String libName = requestedLibraries.get(i);
10057             final int libVersion = requiredVersions != null ? requiredVersions[i]
10058                     : SharedLibraryInfo.VERSION_UNDEFINED;
10059             final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10060             if (libEntry == null) {
10061                 if (required) {
10062                     throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10063                             "Package " + packageName + " requires unavailable shared library "
10064                                     + libName + "; failing!");
10065                 } else if (DEBUG_SHARED_LIBRARIES) {
10066                     Slog.i(TAG, "Package " + packageName
10067                             + " desires unavailable shared library "
10068                             + libName + "; ignoring!");
10069                 }
10070             } else {
10071                 if (requiredVersions != null && requiredCertDigests != null) {
10072                     if (libEntry.info.getVersion() != requiredVersions[i]) {
10073                         throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10074                             "Package " + packageName + " requires unavailable static shared"
10075                                     + " library " + libName + " version "
10076                                     + libEntry.info.getVersion() + "; failing!");
10077                     }
10078
10079                     PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10080                     if (libPkg == null) {
10081                         throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10082                                 "Package " + packageName + " requires unavailable static shared"
10083                                         + " library; failing!");
10084                     }
10085
10086                     String expectedCertDigest = requiredCertDigests[i];
10087                     String libCertDigest = PackageUtils.computeCertSha256Digest(
10088                                 libPkg.mSignatures[0]);
10089                     if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10090                         throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10091                                 "Package " + packageName + " requires differently signed" +
10092                                         " static shared library; failing!");
10093                     }
10094                 }
10095
10096                 if (outUsedLibraries == null) {
10097                     outUsedLibraries = new ArraySet<>();
10098                 }
10099                 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10100             }
10101         }
10102         return outUsedLibraries;
10103     }
10104
10105     private static boolean hasString(List<String> list, List<String> which) {
10106         if (list == null) {
10107             return false;
10108         }
10109         for (int i=list.size()-1; i>=0; i--) {
10110             for (int j=which.size()-1; j>=0; j--) {
10111                 if (which.get(j).equals(list.get(i))) {
10112                     return true;
10113                 }
10114             }
10115         }
10116         return false;
10117     }
10118
10119     private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10120             PackageParser.Package changingPkg) {
10121         ArrayList<PackageParser.Package> res = null;
10122         for (PackageParser.Package pkg : mPackages.values()) {
10123             if (changingPkg != null
10124                     && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10125                     && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10126                     && !ArrayUtils.contains(pkg.usesStaticLibraries,
10127                             changingPkg.staticSharedLibName)) {
10128                 return null;
10129             }
10130             if (res == null) {
10131                 res = new ArrayList<>();
10132             }
10133             res.add(pkg);
10134             try {
10135                 updateSharedLibrariesLPr(pkg, changingPkg);
10136             } catch (PackageManagerException e) {
10137                 // If a system app update or an app and a required lib missing we
10138                 // delete the package and for updated system apps keep the data as
10139                 // it is better for the user to reinstall than to be in an limbo
10140                 // state. Also libs disappearing under an app should never happen
10141                 // - just in case.
10142                 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10143                     final int flags = pkg.isUpdatedSystemApp()
10144                             ? PackageManager.DELETE_KEEP_DATA : 0;
10145                     deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10146                             flags , null, true, null);
10147                 }
10148                 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10149             }
10150         }
10151         return res;
10152     }
10153
10154     /**
10155      * Derive the value of the {@code cpuAbiOverride} based on the provided
10156      * value and an optional stored value from the package settings.
10157      */
10158     private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10159         String cpuAbiOverride = null;
10160
10161         if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10162             cpuAbiOverride = null;
10163         } else if (abiOverride != null) {
10164             cpuAbiOverride = abiOverride;
10165         } else if (settings != null) {
10166             cpuAbiOverride = settings.cpuAbiOverrideString;
10167         }
10168
10169         return cpuAbiOverride;
10170     }
10171
10172     private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10173             final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10174                     throws PackageManagerException {
10175         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10176         // If the package has children and this is the first dive in the function
10177         // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10178         // whether all packages (parent and children) would be successfully scanned
10179         // before the actual scan since scanning mutates internal state and we want
10180         // to atomically install the package and its children.
10181         if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10182             if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10183                 scanFlags |= SCAN_CHECK_ONLY;
10184             }
10185         } else {
10186             scanFlags &= ~SCAN_CHECK_ONLY;
10187         }
10188
10189         final PackageParser.Package scannedPkg;
10190         try {
10191             // Scan the parent
10192             scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10193             // Scan the children
10194             final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10195             for (int i = 0; i < childCount; i++) {
10196                 PackageParser.Package childPkg = pkg.childPackages.get(i);
10197                 scanPackageLI(childPkg, policyFlags,
10198                         scanFlags, currentTime, user);
10199             }
10200         } finally {
10201             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10202         }
10203
10204         if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10205             return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10206         }
10207
10208         return scannedPkg;
10209     }
10210
10211     private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10212             int scanFlags, long currentTime, @Nullable UserHandle user)
10213                     throws PackageManagerException {
10214         boolean success = false;
10215         try {
10216             final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10217                     currentTime, user);
10218             success = true;
10219             return res;
10220         } finally {
10221             if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10222                 // DELETE_DATA_ON_FAILURES is only used by frozen paths
10223                 destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10224                         StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10225                 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10226             }
10227         }
10228     }
10229
10230     /**
10231      * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10232      */
10233     private static boolean apkHasCode(String fileName) {
10234         StrictJarFile jarFile = null;
10235         try {
10236             jarFile = new StrictJarFile(fileName,
10237                     false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10238             return jarFile.findEntry("classes.dex") != null;
10239         } catch (IOException ignore) {
10240         } finally {
10241             try {
10242                 if (jarFile != null) {
10243                     jarFile.close();
10244                 }
10245             } catch (IOException ignore) {}
10246         }
10247         return false;
10248     }
10249
10250     /**
10251      * Enforces code policy for the package. This ensures that if an APK has
10252      * declared hasCode="true" in its manifest that the APK actually contains
10253      * code.
10254      *
10255      * @throws PackageManagerException If bytecode could not be found when it should exist
10256      */
10257     private static void assertCodePolicy(PackageParser.Package pkg)
10258             throws PackageManagerException {
10259         final boolean shouldHaveCode =
10260                 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10261         if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10262             throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10263                     "Package " + pkg.baseCodePath + " code is missing");
10264         }
10265
10266         if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10267             for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10268                 final boolean splitShouldHaveCode =
10269                         (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10270                 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10271                     throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10272                             "Package " + pkg.splitCodePaths[i] + " code is missing");
10273                 }
10274             }
10275         }
10276     }
10277
10278     private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10279             final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10280                     throws PackageManagerException {
10281         if (DEBUG_PACKAGE_SCANNING) {
10282             if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10283                 Log.d(TAG, "Scanning package " + pkg.packageName);
10284         }
10285
10286         applyPolicy(pkg, policyFlags);
10287
10288         assertPackageIsValid(pkg, policyFlags, scanFlags);
10289
10290         // Initialize package source and resource directories
10291         final File scanFile = new File(pkg.codePath);
10292         final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10293         final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10294
10295         SharedUserSetting suid = null;
10296         PackageSetting pkgSetting = null;
10297
10298         // Getting the package setting may have a side-effect, so if we
10299         // are only checking if scan would succeed, stash a copy of the
10300         // old setting to restore at the end.
10301         PackageSetting nonMutatedPs = null;
10302
10303         // We keep references to the derived CPU Abis from settings in oder to reuse
10304         // them in the case where we're not upgrading or booting for the first time.
10305         String primaryCpuAbiFromSettings = null;
10306         String secondaryCpuAbiFromSettings = null;
10307
10308         final PackageParser.Package oldPkg;
10309
10310         // writer
10311         synchronized (mPackages) {
10312             if (pkg.mSharedUserId != null) {
10313                 // SIDE EFFECTS; may potentially allocate a new shared user
10314                 suid = mSettings.getSharedUserLPw(
10315                         pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10316                 if (DEBUG_PACKAGE_SCANNING) {
10317                     if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10318                         Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10319                                 + "): packages=" + suid.packages);
10320                 }
10321             }
10322
10323             // Check if we are renaming from an original package name.
10324             PackageSetting origPackage = null;
10325             String realName = null;
10326             if (pkg.mOriginalPackages != null) {
10327                 // This package may need to be renamed to a previously
10328                 // installed name.  Let's check on that...
10329                 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10330                 if (pkg.mOriginalPackages.contains(renamed)) {
10331                     // This package had originally been installed as the
10332                     // original name, and we have already taken care of
10333                     // transitioning to the new one.  Just update the new
10334                     // one to continue using the old name.
10335                     realName = pkg.mRealPackage;
10336                     if (!pkg.packageName.equals(renamed)) {
10337                         // Callers into this function may have already taken
10338                         // care of renaming the package; only do it here if
10339                         // it is not already done.
10340                         pkg.setPackageName(renamed);
10341                     }
10342                 } else {
10343                     for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10344                         if ((origPackage = mSettings.getPackageLPr(
10345                                 pkg.mOriginalPackages.get(i))) != null) {
10346                             // We do have the package already installed under its
10347                             // original name...  should we use it?
10348                             if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10349                                 // New package is not compatible with original.
10350                                 origPackage = null;
10351                                 continue;
10352                             } else if (origPackage.sharedUser != null) {
10353                                 // Make sure uid is compatible between packages.
10354                                 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10355                                     Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10356                                             + " to " + pkg.packageName + ": old uid "
10357                                             + origPackage.sharedUser.name
10358                                             + " differs from " + pkg.mSharedUserId);
10359                                     origPackage = null;
10360                                     continue;
10361                                 }
10362                                 // TODO: Add case when shared user id is added [b/28144775]
10363                             } else {
10364                                 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10365                                         + pkg.packageName + " to old name " + origPackage.name);
10366                             }
10367                             break;
10368                         }
10369                     }
10370                 }
10371             }
10372
10373             if (mTransferedPackages.contains(pkg.packageName)) {
10374                 Slog.w(TAG, "Package " + pkg.packageName
10375                         + " was transferred to another, but its .apk remains");
10376             }
10377
10378             // See comments in nonMutatedPs declaration
10379             if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10380                 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10381                 if (foundPs != null) {
10382                     nonMutatedPs = new PackageSetting(foundPs);
10383                 }
10384             }
10385
10386             if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10387                 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10388                 if (foundPs != null) {
10389                     primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10390                     secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10391                 }
10392             }
10393
10394             pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10395             if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10396                 PackageManagerService.reportSettingsProblem(Log.WARN,
10397                         "Package " + pkg.packageName + " shared user changed from "
10398                                 + (pkgSetting.sharedUser != null
10399                                         ? pkgSetting.sharedUser.name : "<nothing>")
10400                                 + " to "
10401                                 + (suid != null ? suid.name : "<nothing>")
10402                                 + "; replacing with new");
10403                 pkgSetting = null;
10404             }
10405             final PackageSetting oldPkgSetting =
10406                     pkgSetting == null ? null : new PackageSetting(pkgSetting);
10407             final PackageSetting disabledPkgSetting =
10408                     mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10409
10410             if (oldPkgSetting == null) {
10411                 oldPkg = null;
10412             } else {
10413                 oldPkg = oldPkgSetting.pkg;
10414             }
10415
10416             String[] usesStaticLibraries = null;
10417             if (pkg.usesStaticLibraries != null) {
10418                 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10419                 pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10420             }
10421
10422             if (pkgSetting == null) {
10423                 final String parentPackageName = (pkg.parentPackage != null)
10424                         ? pkg.parentPackage.packageName : null;
10425                 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10426                 // REMOVE SharedUserSetting from method; update in a separate call
10427                 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10428                         disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10429                         pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10430                         pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10431                         pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10432                         true /*allowInstall*/, instantApp, parentPackageName,
10433                         pkg.getChildPackageNames(), UserManagerService.getInstance(),
10434                         usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10435                 // SIDE EFFECTS; updates system state; move elsewhere
10436                 if (origPackage != null) {
10437                     mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10438                 }
10439                 mSettings.addUserToSettingLPw(pkgSetting);
10440             } else {
10441                 // REMOVE SharedUserSetting from method; update in a separate call.
10442                 //
10443                 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10444                 // secondaryCpuAbi are not known at this point so we always update them
10445                 // to null here, only to reset them at a later point.
10446                 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10447                         pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10448                         pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10449                         pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10450                         UserManagerService.getInstance(), usesStaticLibraries,
10451                         pkg.usesStaticLibrariesVersions);
10452             }
10453             // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10454             mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10455
10456             // SIDE EFFECTS; modifies system state; move elsewhere
10457             if (pkgSetting.origPackage != null) {
10458                 // If we are first transitioning from an original package,
10459                 // fix up the new package's name now.  We need to do this after
10460                 // looking up the package under its new name, so getPackageLP
10461                 // can take care of fiddling things correctly.
10462                 pkg.setPackageName(origPackage.name);
10463
10464                 // File a report about this.
10465                 String msg = "New package " + pkgSetting.realName
10466                         + " renamed to replace old package " + pkgSetting.name;
10467                 reportSettingsProblem(Log.WARN, msg);
10468
10469                 // Make a note of it.
10470                 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10471                     mTransferedPackages.add(origPackage.name);
10472                 }
10473
10474                 // No longer need to retain this.
10475                 pkgSetting.origPackage = null;
10476             }
10477
10478             // SIDE EFFECTS; modifies system state; move elsewhere
10479             if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10480                 // Make a note of it.
10481                 mTransferedPackages.add(pkg.packageName);
10482             }
10483
10484             if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10485                 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10486             }
10487
10488             if ((scanFlags & SCAN_BOOTING) == 0
10489                     && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10490                 // Check all shared libraries and map to their actual file path.
10491                 // We only do this here for apps not on a system dir, because those
10492                 // are the only ones that can fail an install due to this.  We
10493                 // will take care of the system apps by updating all of their
10494                 // library paths after the scan is done. Also during the initial
10495                 // scan don't update any libs as we do this wholesale after all
10496                 // apps are scanned to avoid dependency based scanning.
10497                 updateSharedLibrariesLPr(pkg, null);
10498             }
10499
10500             if (mFoundPolicyFile) {
10501                 SELinuxMMAC.assignSeInfoValue(pkg);
10502             }
10503             pkg.applicationInfo.uid = pkgSetting.appId;
10504             pkg.mExtras = pkgSetting;
10505
10506
10507             // Static shared libs have same package with different versions where
10508             // we internally use a synthetic package name to allow multiple versions
10509             // of the same package, therefore we need to compare signatures against
10510             // the package setting for the latest library version.
10511             PackageSetting signatureCheckPs = pkgSetting;
10512             if (pkg.applicationInfo.isStaticSharedLibrary()) {
10513                 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10514                 if (libraryEntry != null) {
10515                     signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10516                 }
10517             }
10518
10519             if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10520                 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10521                     // We just determined the app is signed correctly, so bring
10522                     // over the latest parsed certs.
10523                     pkgSetting.signatures.mSignatures = pkg.mSignatures;
10524                 } else {
10525                     if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10526                         throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10527                                 "Package " + pkg.packageName + " upgrade keys do not match the "
10528                                 + "previously installed version");
10529                     } else {
10530                         pkgSetting.signatures.mSignatures = pkg.mSignatures;
10531                         String msg = "System package " + pkg.packageName
10532                                 + " signature changed; retaining data.";
10533                         reportSettingsProblem(Log.WARN, msg);
10534                     }
10535                 }
10536             } else {
10537                 try {
10538                     // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10539                     verifySignaturesLP(signatureCheckPs, pkg);
10540                     // We just determined the app is signed correctly, so bring
10541                     // over the latest parsed certs.
10542                     pkgSetting.signatures.mSignatures = pkg.mSignatures;
10543                 } catch (PackageManagerException e) {
10544                     if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10545                         throw e;
10546                     }
10547                     // The signature has changed, but this package is in the system
10548                     // image...  let's recover!
10549                     pkgSetting.signatures.mSignatures = pkg.mSignatures;
10550                     // However...  if this package is part of a shared user, but it
10551                     // doesn't match the signature of the shared user, let's fail.
10552                     // What this means is that you can't change the signatures
10553                     // associated with an overall shared user, which doesn't seem all
10554                     // that unreasonable.
10555                     if (signatureCheckPs.sharedUser != null) {
10556                         if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10557                                 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10558                             throw new PackageManagerException(
10559                                     INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10560                                     "Signature mismatch for shared user: "
10561                                             + pkgSetting.sharedUser);
10562                         }
10563                     }
10564                     // File a report about this.
10565                     String msg = "System package " + pkg.packageName
10566                             + " signature changed; retaining data.";
10567                     reportSettingsProblem(Log.WARN, msg);
10568                 }
10569             }
10570
10571             if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10572                 // This package wants to adopt ownership of permissions from
10573                 // another package.
10574                 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10575                     final String origName = pkg.mAdoptPermissions.get(i);
10576                     final PackageSetting orig = mSettings.getPackageLPr(origName);
10577                     if (orig != null) {
10578                         if (verifyPackageUpdateLPr(orig, pkg)) {
10579                             Slog.i(TAG, "Adopting permissions from " + origName + " to "
10580                                     + pkg.packageName);
10581                             // SIDE EFFECTS; updates permissions system state; move elsewhere
10582                             mSettings.transferPermissionsLPw(origName, pkg.packageName);
10583                         }
10584                     }
10585                 }
10586             }
10587         }
10588
10589         pkg.applicationInfo.processName = fixProcessName(
10590                 pkg.applicationInfo.packageName,
10591                 pkg.applicationInfo.processName);
10592
10593         if (pkg != mPlatformPackage) {
10594             // Get all of our default paths setup
10595             pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10596         }
10597
10598         final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10599
10600         if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10601             if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10602                 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10603                 final boolean extractNativeLibs = !pkg.isLibrary();
10604                 derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10605                         mAppLib32InstallDir);
10606                 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10607
10608                 // Some system apps still use directory structure for native libraries
10609                 // in which case we might end up not detecting abi solely based on apk
10610                 // structure. Try to detect abi based on directory structure.
10611                 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10612                         pkg.applicationInfo.primaryCpuAbi == null) {
10613                     setBundledAppAbisAndRoots(pkg, pkgSetting);
10614                     setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10615                 }
10616             } else {
10617                 // This is not a first boot or an upgrade, don't bother deriving the
10618                 // ABI during the scan. Instead, trust the value that was stored in the
10619                 // package setting.
10620                 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10621                 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10622
10623                 setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10624
10625                 if (DEBUG_ABI_SELECTION) {
10626                     Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10627                         pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10628                         pkg.applicationInfo.secondaryCpuAbi);
10629                 }
10630             }
10631         } else {
10632             if ((scanFlags & SCAN_MOVE) != 0) {
10633                 // We haven't run dex-opt for this move (since we've moved the compiled output too)
10634                 // but we already have this packages package info in the PackageSetting. We just
10635                 // use that and derive the native library path based on the new codepath.
10636                 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10637                 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10638             }
10639
10640             // Set native library paths again. For moves, the path will be updated based on the
10641             // ABIs we've determined above. For non-moves, the path will be updated based on the
10642             // ABIs we determined during compilation, but the path will depend on the final
10643             // package path (after the rename away from the stage path).
10644             setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10645         }
10646
10647         // This is a special case for the "system" package, where the ABI is
10648         // dictated by the zygote configuration (and init.rc). We should keep track
10649         // of this ABI so that we can deal with "normal" applications that run under
10650         // the same UID correctly.
10651         if (mPlatformPackage == pkg) {
10652             pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10653                     Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10654         }
10655
10656         // If there's a mismatch between the abi-override in the package setting
10657         // and the abiOverride specified for the install. Warn about this because we
10658         // would've already compiled the app without taking the package setting into
10659         // account.
10660         if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10661             if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10662                 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10663                         " for package " + pkg.packageName);
10664             }
10665         }
10666
10667         pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10668         pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10669         pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10670
10671         // Copy the derived override back to the parsed package, so that we can
10672         // update the package settings accordingly.
10673         pkg.cpuAbiOverride = cpuAbiOverride;
10674
10675         if (DEBUG_ABI_SELECTION) {
10676             Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10677                     + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10678                     + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10679         }
10680
10681         // Push the derived path down into PackageSettings so we know what to
10682         // clean up at uninstall time.
10683         pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10684
10685         if (DEBUG_ABI_SELECTION) {
10686             Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10687                     " primary=" + pkg.applicationInfo.primaryCpuAbi +
10688                     " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10689         }
10690
10691         // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10692         if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10693             // We don't do this here during boot because we can do it all
10694             // at once after scanning all existing packages.
10695             //
10696             // We also do this *before* we perform dexopt on this package, so that
10697             // we can avoid redundant dexopts, and also to make sure we've got the
10698             // code and package path correct.
10699             adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10700         }
10701
10702         if (mFactoryTest && pkg.requestedPermissions.contains(
10703                 android.Manifest.permission.FACTORY_TEST)) {
10704             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10705         }
10706
10707         if (isSystemApp(pkg)) {
10708             pkgSetting.isOrphaned = true;
10709         }
10710
10711         // Take care of first install / last update times.
10712         final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10713         if (currentTime != 0) {
10714             if (pkgSetting.firstInstallTime == 0) {
10715                 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10716             } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10717                 pkgSetting.lastUpdateTime = currentTime;
10718             }
10719         } else if (pkgSetting.firstInstallTime == 0) {
10720             // We need *something*.  Take time time stamp of the file.
10721             pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10722         } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10723             if (scanFileTime != pkgSetting.timeStamp) {
10724                 // A package on the system image has changed; consider this
10725                 // to be an update.
10726                 pkgSetting.lastUpdateTime = scanFileTime;
10727             }
10728         }
10729         pkgSetting.setTimeStamp(scanFileTime);
10730
10731         if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10732             if (nonMutatedPs != null) {
10733                 synchronized (mPackages) {
10734                     mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10735                 }
10736             }
10737         } else {
10738             final int userId = user == null ? 0 : user.getIdentifier();
10739             // Modify state for the given package setting
10740             commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10741                     (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10742             if (pkgSetting.getInstantApp(userId)) {
10743                 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10744             }
10745         }
10746
10747         if (oldPkg != null) {
10748             // We need to call revokeRuntimePermissionsIfGroupChanged async as permission
10749             // revokation from this method might need to kill apps which need the
10750             // mPackages lock on a different thread. This would dead lock.
10751             //
10752             // Hence create a copy of all package names and pass it into
10753             // revokeRuntimePermissionsIfGroupChanged. Only for those permissions might get
10754             // revoked. If a new package is added before the async code runs the permission
10755             // won't be granted yet, hence new packages are no problem.
10756             final ArrayList<String> allPackageNames = new ArrayList<>(mPackages.keySet());
10757
10758             AsyncTask.execute(new Runnable() {
10759                 public void run() {
10760                     revokeRuntimePermissionsIfGroupChanged(pkg, oldPkg, allPackageNames);
10761                 }
10762             });
10763         }
10764
10765         return pkg;
10766     }
10767
10768     /**
10769      * Applies policy to the parsed package based upon the given policy flags.
10770      * Ensures the package is in a good state.
10771      * <p>
10772      * Implementation detail: This method must NOT have any side effect. It would
10773      * ideally be static, but, it requires locks to read system state.
10774      */
10775     private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10776         if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10777             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10778             if (pkg.applicationInfo.isDirectBootAware()) {
10779                 // we're direct boot aware; set for all components
10780                 for (PackageParser.Service s : pkg.services) {
10781                     s.info.encryptionAware = s.info.directBootAware = true;
10782                 }
10783                 for (PackageParser.Provider p : pkg.providers) {
10784                     p.info.encryptionAware = p.info.directBootAware = true;
10785                 }
10786                 for (PackageParser.Activity a : pkg.activities) {
10787                     a.info.encryptionAware = a.info.directBootAware = true;
10788                 }
10789                 for (PackageParser.Activity r : pkg.receivers) {
10790                     r.info.encryptionAware = r.info.directBootAware = true;
10791                 }
10792             }
10793         } else {
10794             // Only allow system apps to be flagged as core apps.
10795             pkg.coreApp = false;
10796             // clear flags not applicable to regular apps
10797             pkg.applicationInfo.privateFlags &=
10798                     ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10799             pkg.applicationInfo.privateFlags &=
10800                     ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10801         }
10802         pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10803
10804         if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10805             pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10806         }
10807
10808         if (!isSystemApp(pkg)) {
10809             // Only system apps can use these features.
10810             pkg.mOriginalPackages = null;
10811             pkg.mRealPackage = null;
10812             pkg.mAdoptPermissions = null;
10813         }
10814     }
10815
10816     /**
10817      * Asserts the parsed package is valid according to the given policy. If the
10818      * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10819      * <p>
10820      * Implementation detail: This method must NOT have any side effects. It would
10821      * ideally be static, but, it requires locks to read system state.
10822      *
10823      * @throws PackageManagerException If the package fails any of the validation checks
10824      */
10825     private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10826             throws PackageManagerException {
10827         if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10828             assertCodePolicy(pkg);
10829         }
10830
10831         if (pkg.applicationInfo.getCodePath() == null ||
10832                 pkg.applicationInfo.getResourcePath() == null) {
10833             // Bail out. The resource and code paths haven't been set.
10834             throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10835                     "Code and resource paths haven't been set correctly");
10836         }
10837
10838         // Make sure we're not adding any bogus keyset info
10839         KeySetManagerService ksms = mSettings.mKeySetManagerService;
10840         ksms.assertScannedPackageValid(pkg);
10841
10842         synchronized (mPackages) {
10843             // The special "android" package can only be defined once
10844             if (pkg.packageName.equals("android")) {
10845                 if (mAndroidApplication != null) {
10846                     Slog.w(TAG, "*************************************************");
10847                     Slog.w(TAG, "Core android package being redefined.  Skipping.");
10848                     Slog.w(TAG, " codePath=" + pkg.codePath);
10849                     Slog.w(TAG, "*************************************************");
10850                     throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10851                             "Core android package being redefined.  Skipping.");
10852                 }
10853             }
10854
10855             // A package name must be unique; don't allow duplicates
10856             if (mPackages.containsKey(pkg.packageName)) {
10857                 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10858                         "Application package " + pkg.packageName
10859                         + " already installed.  Skipping duplicate.");
10860             }
10861
10862             if (pkg.applicationInfo.isStaticSharedLibrary()) {
10863                 // Static libs have a synthetic package name containing the version
10864                 // but we still want the base name to be unique.
10865                 if (mPackages.containsKey(pkg.manifestPackageName)) {
10866                     throw new PackageManagerException(
10867                             "Duplicate static shared lib provider package");
10868                 }
10869
10870                 // Static shared libraries should have at least O target SDK
10871                 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10872                     throw new PackageManagerException(
10873                             "Packages declaring static-shared libs must target O SDK or higher");
10874                 }
10875
10876                 // Package declaring static a shared lib cannot be instant apps
10877                 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10878                     throw new PackageManagerException(
10879                             "Packages declaring static-shared libs cannot be instant apps");
10880                 }
10881
10882                 // Package declaring static a shared lib cannot be renamed since the package
10883                 // name is synthetic and apps can't code around package manager internals.
10884                 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10885                     throw new PackageManagerException(
10886                             "Packages declaring static-shared libs cannot be renamed");
10887                 }
10888
10889                 // Package declaring static a shared lib cannot declare child packages
10890                 if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10891                     throw new PackageManagerException(
10892                             "Packages declaring static-shared libs cannot have child packages");
10893                 }
10894
10895                 // Package declaring static a shared lib cannot declare dynamic libs
10896                 if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10897                     throw new PackageManagerException(
10898                             "Packages declaring static-shared libs cannot declare dynamic libs");
10899                 }
10900
10901                 // Package declaring static a shared lib cannot declare shared users
10902                 if (pkg.mSharedUserId != null) {
10903                     throw new PackageManagerException(
10904                             "Packages declaring static-shared libs cannot declare shared users");
10905                 }
10906
10907                 // Static shared libs cannot declare activities
10908                 if (!pkg.activities.isEmpty()) {
10909                     throw new PackageManagerException(
10910                             "Static shared libs cannot declare activities");
10911                 }
10912
10913                 // Static shared libs cannot declare services
10914                 if (!pkg.services.isEmpty()) {
10915                     throw new PackageManagerException(
10916                             "Static shared libs cannot declare services");
10917                 }
10918
10919                 // Static shared libs cannot declare providers
10920                 if (!pkg.providers.isEmpty()) {
10921                     throw new PackageManagerException(
10922                             "Static shared libs cannot declare content providers");
10923                 }
10924
10925                 // Static shared libs cannot declare receivers
10926                 if (!pkg.receivers.isEmpty()) {
10927                     throw new PackageManagerException(
10928                             "Static shared libs cannot declare broadcast receivers");
10929                 }
10930
10931                 // Static shared libs cannot declare permission groups
10932                 if (!pkg.permissionGroups.isEmpty()) {
10933                     throw new PackageManagerException(
10934                             "Static shared libs cannot declare permission groups");
10935                 }
10936
10937                 // Static shared libs cannot declare permissions
10938                 if (!pkg.permissions.isEmpty()) {
10939                     throw new PackageManagerException(
10940                             "Static shared libs cannot declare permissions");
10941                 }
10942
10943                 // Static shared libs cannot declare protected broadcasts
10944                 if (pkg.protectedBroadcasts != null) {
10945                     throw new PackageManagerException(
10946                             "Static shared libs cannot declare protected broadcasts");
10947                 }
10948
10949                 // Static shared libs cannot be overlay targets
10950                 if (pkg.mOverlayTarget != null) {
10951                     throw new PackageManagerException(
10952                             "Static shared libs cannot be overlay targets");
10953                 }
10954
10955                 // The version codes must be ordered as lib versions
10956                 int minVersionCode = Integer.MIN_VALUE;
10957                 int maxVersionCode = Integer.MAX_VALUE;
10958
10959                 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10960                         pkg.staticSharedLibName);
10961                 if (versionedLib != null) {
10962                     final int versionCount = versionedLib.size();
10963                     for (int i = 0; i < versionCount; i++) {
10964                         SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10965                         final int libVersionCode = libInfo.getDeclaringPackage()
10966                                 .getVersionCode();
10967                         if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10968                             minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10969                         } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10970                             maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10971                         } else {
10972                             minVersionCode = maxVersionCode = libVersionCode;
10973                             break;
10974                         }
10975                     }
10976                 }
10977                 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10978                     throw new PackageManagerException("Static shared"
10979                             + " lib version codes must be ordered as lib versions");
10980                 }
10981             }
10982
10983             // Only privileged apps and updated privileged apps can add child packages.
10984             if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10985                 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10986                     throw new PackageManagerException("Only privileged apps can add child "
10987                             + "packages. Ignoring package " + pkg.packageName);
10988                 }
10989                 final int childCount = pkg.childPackages.size();
10990                 for (int i = 0; i < childCount; i++) {
10991                     PackageParser.Package childPkg = pkg.childPackages.get(i);
10992                     if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10993                             childPkg.packageName)) {
10994                         throw new PackageManagerException("Can't override child of "
10995                                 + "another disabled app. Ignoring package " + pkg.packageName);
10996                     }
10997                 }
10998             }
10999
11000             // If we're only installing presumed-existing packages, require that the
11001             // scanned APK is both already known and at the path previously established
11002             // for it.  Previously unknown packages we pick up normally, but if we have an
11003             // a priori expectation about this package's install presence, enforce it.
11004             // With a singular exception for new system packages. When an OTA contains
11005             // a new system package, we allow the codepath to change from a system location
11006             // to the user-installed location. If we don't allow this change, any newer,
11007             // user-installed version of the application will be ignored.
11008             if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11009                 if (mExpectingBetter.containsKey(pkg.packageName)) {
11010                     logCriticalInfo(Log.WARN,
11011                             "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11012                 } else {
11013                     PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11014                     if (known != null) {
11015                         if (DEBUG_PACKAGE_SCANNING) {
11016                             Log.d(TAG, "Examining " + pkg.codePath
11017                                     + " and requiring known paths " + known.codePathString
11018                                     + " & " + known.resourcePathString);
11019                         }
11020                         if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11021                                 || !pkg.applicationInfo.getResourcePath().equals(
11022                                         known.resourcePathString)) {
11023                             throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11024                                     "Application package " + pkg.packageName
11025                                     + " found at " + pkg.applicationInfo.getCodePath()
11026                                     + " but expected at " + known.codePathString
11027                                     + "; ignoring.");
11028                         }
11029                     }
11030                 }
11031             }
11032
11033             // Verify that this new package doesn't have any content providers
11034             // that conflict with existing packages.  Only do this if the
11035             // package isn't already installed, since we don't want to break
11036             // things that are installed.
11037             if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11038                 final int N = pkg.providers.size();
11039                 int i;
11040                 for (i=0; i<N; i++) {
11041                     PackageParser.Provider p = pkg.providers.get(i);
11042                     if (p.info.authority != null) {
11043                         String names[] = p.info.authority.split(";");
11044                         for (int j = 0; j < names.length; j++) {
11045                             if (mProvidersByAuthority.containsKey(names[j])) {
11046                                 PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11047                                 final String otherPackageName =
11048                                         ((other != null && other.getComponentName() != null) ?
11049                                                 other.getComponentName().getPackageName() : "?");
11050                                 throw new PackageManagerException(
11051                                         INSTALL_FAILED_CONFLICTING_PROVIDER,
11052                                         "Can't install because provider name " + names[j]
11053                                                 + " (in package " + pkg.applicationInfo.packageName
11054                                                 + ") is already used by " + otherPackageName);
11055                             }
11056                         }
11057                     }
11058                 }
11059             }
11060         }
11061     }
11062
11063     private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11064             int type, String declaringPackageName, int declaringVersionCode) {
11065         SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11066         if (versionedLib == null) {
11067             versionedLib = new SparseArray<>();
11068             mSharedLibraries.put(name, versionedLib);
11069             if (type == SharedLibraryInfo.TYPE_STATIC) {
11070                 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11071             }
11072         } else if (versionedLib.indexOfKey(version) >= 0) {
11073             return false;
11074         }
11075         SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11076                 version, type, declaringPackageName, declaringVersionCode);
11077         versionedLib.put(version, libEntry);
11078         return true;
11079     }
11080
11081     private boolean removeSharedLibraryLPw(String name, int version) {
11082         SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11083         if (versionedLib == null) {
11084             return false;
11085         }
11086         final int libIdx = versionedLib.indexOfKey(version);
11087         if (libIdx < 0) {
11088             return false;
11089         }
11090         SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11091         versionedLib.remove(version);
11092         if (versionedLib.size() <= 0) {
11093             mSharedLibraries.remove(name);
11094             if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11095                 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11096                         .getPackageName());
11097             }
11098         }
11099         return true;
11100     }
11101
11102     /**
11103      * Adds a scanned package to the system. When this method is finished, the package will
11104      * be available for query, resolution, etc...
11105      */
11106     private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11107             UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11108         final String pkgName = pkg.packageName;
11109         if (mCustomResolverComponentName != null &&
11110                 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11111             setUpCustomResolverActivity(pkg);
11112         }
11113
11114         if (pkg.packageName.equals("android")) {
11115             synchronized (mPackages) {
11116                 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11117                     // Set up information for our fall-back user intent resolution activity.
11118                     mPlatformPackage = pkg;
11119                     pkg.mVersionCode = mSdkVersion;
11120                     mAndroidApplication = pkg.applicationInfo;
11121                     if (!mResolverReplaced) {
11122                         mResolveActivity.applicationInfo = mAndroidApplication;
11123                         mResolveActivity.name = ResolverActivity.class.getName();
11124                         mResolveActivity.packageName = mAndroidApplication.packageName;
11125                         mResolveActivity.processName = "system:ui";
11126                         mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11127                         mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11128                         mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11129                         mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11130                         mResolveActivity.exported = true;
11131                         mResolveActivity.enabled = true;
11132                         mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11133                         mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11134                                 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11135                                 | ActivityInfo.CONFIG_SCREEN_LAYOUT
11136                                 | ActivityInfo.CONFIG_ORIENTATION
11137                                 | ActivityInfo.CONFIG_KEYBOARD
11138                                 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11139                         mResolveInfo.activityInfo = mResolveActivity;
11140                         mResolveInfo.priority = 0;
11141                         mResolveInfo.preferredOrder = 0;
11142                         mResolveInfo.match = 0;
11143                         mResolveComponentName = new ComponentName(
11144                                 mAndroidApplication.packageName, mResolveActivity.name);
11145                     }
11146                 }
11147             }
11148         }
11149
11150         ArrayList<PackageParser.Package> clientLibPkgs = null;
11151         // writer
11152         synchronized (mPackages) {
11153             boolean hasStaticSharedLibs = false;
11154
11155             // Any app can add new static shared libraries
11156             if (pkg.staticSharedLibName != null) {
11157                 // Static shared libs don't allow renaming as they have synthetic package
11158                 // names to allow install of multiple versions, so use name from manifest.
11159                 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11160                         pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11161                         pkg.manifestPackageName, pkg.mVersionCode)) {
11162                     hasStaticSharedLibs = true;
11163                 } else {
11164                     Slog.w(TAG, "Package " + pkg.packageName + " library "
11165                                 + pkg.staticSharedLibName + " already exists; skipping");
11166                 }
11167                 // Static shared libs cannot be updated once installed since they
11168                 // use synthetic package name which includes the version code, so
11169                 // not need to update other packages's shared lib dependencies.
11170             }
11171
11172             if (!hasStaticSharedLibs
11173                     && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11174                 // Only system apps can add new dynamic shared libraries.
11175                 if (pkg.libraryNames != null) {
11176                     for (int i = 0; i < pkg.libraryNames.size(); i++) {
11177                         String name = pkg.libraryNames.get(i);
11178                         boolean allowed = false;
11179                         if (pkg.isUpdatedSystemApp()) {
11180                             // New library entries can only be added through the
11181                             // system image.  This is important to get rid of a lot
11182                             // of nasty edge cases: for example if we allowed a non-
11183                             // system update of the app to add a library, then uninstalling
11184                             // the update would make the library go away, and assumptions
11185                             // we made such as through app install filtering would now
11186                             // have allowed apps on the device which aren't compatible
11187                             // with it.  Better to just have the restriction here, be
11188                             // conservative, and create many fewer cases that can negatively
11189                             // impact the user experience.
11190                             final PackageSetting sysPs = mSettings
11191                                     .getDisabledSystemPkgLPr(pkg.packageName);
11192                             if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11193                                 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11194                                     if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11195                                         allowed = true;
11196                                         break;
11197                                     }
11198                                 }
11199                             }
11200                         } else {
11201                             allowed = true;
11202                         }
11203                         if (allowed) {
11204                             if (!addSharedLibraryLPw(null, pkg.packageName, name,
11205                                     SharedLibraryInfo.VERSION_UNDEFINED,
11206                                     SharedLibraryInfo.TYPE_DYNAMIC,
11207                                     pkg.packageName, pkg.mVersionCode)) {
11208                                 Slog.w(TAG, "Package " + pkg.packageName + " library "
11209                                         + name + " already exists; skipping");
11210                             }
11211                         } else {
11212                             Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11213                                     + name + " that is not declared on system image; skipping");
11214                         }
11215                     }
11216
11217                     if ((scanFlags & SCAN_BOOTING) == 0) {
11218                         // If we are not booting, we need to update any applications
11219                         // that are clients of our shared library.  If we are booting,
11220                         // this will all be done once the scan is complete.
11221                         clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11222                     }
11223                 }
11224             }
11225         }
11226
11227         if ((scanFlags & SCAN_BOOTING) != 0) {
11228             // No apps can run during boot scan, so they don't need to be frozen
11229         } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11230             // Caller asked to not kill app, so it's probably not frozen
11231         } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11232             // Caller asked us to ignore frozen check for some reason; they
11233             // probably didn't know the package name
11234         } else {
11235             // We're doing major surgery on this package, so it better be frozen
11236             // right now to keep it from launching
11237             checkPackageFrozen(pkgName);
11238         }
11239
11240         // Also need to kill any apps that are dependent on the library.
11241         if (clientLibPkgs != null) {
11242             for (int i=0; i<clientLibPkgs.size(); i++) {
11243                 PackageParser.Package clientPkg = clientLibPkgs.get(i);
11244                 killApplication(clientPkg.applicationInfo.packageName,
11245                         clientPkg.applicationInfo.uid, "update lib");
11246             }
11247         }
11248
11249         // writer
11250         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11251
11252         synchronized (mPackages) {
11253             // We don't expect installation to fail beyond this point
11254
11255             // Add the new setting to mSettings
11256             mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11257             // Add the new setting to mPackages
11258             mPackages.put(pkg.applicationInfo.packageName, pkg);
11259             // Make sure we don't accidentally delete its data.
11260             final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11261             while (iter.hasNext()) {
11262                 PackageCleanItem item = iter.next();
11263                 if (pkgName.equals(item.packageName)) {
11264                     iter.remove();
11265                 }
11266             }
11267
11268             // Add the package's KeySets to the global KeySetManagerService
11269             KeySetManagerService ksms = mSettings.mKeySetManagerService;
11270             ksms.addScannedPackageLPw(pkg);
11271
11272             int N = pkg.providers.size();
11273             StringBuilder r = null;
11274             int i;
11275             for (i=0; i<N; i++) {
11276                 PackageParser.Provider p = pkg.providers.get(i);
11277                 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11278                         p.info.processName);
11279                 mProviders.addProvider(p);
11280                 p.syncable = p.info.isSyncable;
11281                 if (p.info.authority != null) {
11282                     String names[] = p.info.authority.split(";");
11283                     p.info.authority = null;
11284                     for (int j = 0; j < names.length; j++) {
11285                         if (j == 1 && p.syncable) {
11286                             // We only want the first authority for a provider to possibly be
11287                             // syncable, so if we already added this provider using a different
11288                             // authority clear the syncable flag. We copy the provider before
11289                             // changing it because the mProviders object contains a reference
11290                             // to a provider that we don't want to change.
11291                             // Only do this for the second authority since the resulting provider
11292                             // object can be the same for all future authorities for this provider.
11293                             p = new PackageParser.Provider(p);
11294                             p.syncable = false;
11295                         }
11296                         if (!mProvidersByAuthority.containsKey(names[j])) {
11297                             mProvidersByAuthority.put(names[j], p);
11298                             if (p.info.authority == null) {
11299                                 p.info.authority = names[j];
11300                             } else {
11301                                 p.info.authority = p.info.authority + ";" + names[j];
11302                             }
11303                             if (DEBUG_PACKAGE_SCANNING) {
11304                                 if (chatty)
11305                                     Log.d(TAG, "Registered content provider: " + names[j]
11306                                             + ", className = " + p.info.name + ", isSyncable = "
11307                                             + p.info.isSyncable);
11308                             }
11309                         } else {
11310                             PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11311                             Slog.w(TAG, "Skipping provider name " + names[j] +
11312                                     " (in package " + pkg.applicationInfo.packageName +
11313                                     "): name already used by "
11314                                     + ((other != null && other.getComponentName() != null)
11315                                             ? other.getComponentName().getPackageName() : "?"));
11316                         }
11317                     }
11318                 }
11319                 if (chatty) {
11320                     if (r == null) {
11321                         r = new StringBuilder(256);
11322                     } else {
11323                         r.append(' ');
11324                     }
11325                     r.append(p.info.name);
11326                 }
11327             }
11328             if (r != null) {
11329                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11330             }
11331
11332             N = pkg.services.size();
11333             r = null;
11334             for (i=0; i<N; i++) {
11335                 PackageParser.Service s = pkg.services.get(i);
11336                 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11337                         s.info.processName);
11338                 mServices.addService(s);
11339                 if (chatty) {
11340                     if (r == null) {
11341                         r = new StringBuilder(256);
11342                     } else {
11343                         r.append(' ');
11344                     }
11345                     r.append(s.info.name);
11346                 }
11347             }
11348             if (r != null) {
11349                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11350             }
11351
11352             N = pkg.receivers.size();
11353             r = null;
11354             for (i=0; i<N; i++) {
11355                 PackageParser.Activity a = pkg.receivers.get(i);
11356                 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11357                         a.info.processName);
11358                 mReceivers.addActivity(a, "receiver");
11359                 if (chatty) {
11360                     if (r == null) {
11361                         r = new StringBuilder(256);
11362                     } else {
11363                         r.append(' ');
11364                     }
11365                     r.append(a.info.name);
11366                 }
11367             }
11368             if (r != null) {
11369                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11370             }
11371
11372             N = pkg.activities.size();
11373             r = null;
11374             for (i=0; i<N; i++) {
11375                 PackageParser.Activity a = pkg.activities.get(i);
11376                 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11377                         a.info.processName);
11378                 mActivities.addActivity(a, "activity");
11379                 if (chatty) {
11380                     if (r == null) {
11381                         r = new StringBuilder(256);
11382                     } else {
11383                         r.append(' ');
11384                     }
11385                     r.append(a.info.name);
11386                 }
11387             }
11388             if (r != null) {
11389                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11390             }
11391
11392             N = pkg.permissionGroups.size();
11393             r = null;
11394             for (i=0; i<N; i++) {
11395                 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11396                 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11397                 final String curPackageName = cur == null ? null : cur.info.packageName;
11398                 // Dont allow ephemeral apps to define new permission groups.
11399                 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11400                     Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11401                             + pg.info.packageName
11402                             + " ignored: instant apps cannot define new permission groups.");
11403                     continue;
11404                 }
11405                 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11406                 if (cur == null || isPackageUpdate) {
11407                     mPermissionGroups.put(pg.info.name, pg);
11408                     if (chatty) {
11409                         if (r == null) {
11410                             r = new StringBuilder(256);
11411                         } else {
11412                             r.append(' ');
11413                         }
11414                         if (isPackageUpdate) {
11415                             r.append("UPD:");
11416                         }
11417                         r.append(pg.info.name);
11418                     }
11419                 } else {
11420                     Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11421                             + pg.info.packageName + " ignored: original from "
11422                             + cur.info.packageName);
11423                     if (chatty) {
11424                         if (r == null) {
11425                             r = new StringBuilder(256);
11426                         } else {
11427                             r.append(' ');
11428                         }
11429                         r.append("DUP:");
11430                         r.append(pg.info.name);
11431                     }
11432                 }
11433             }
11434             if (r != null) {
11435                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11436             }
11437
11438             N = pkg.permissions.size();
11439             r = null;
11440             for (i=0; i<N; i++) {
11441                 PackageParser.Permission p = pkg.permissions.get(i);
11442
11443                 // Dont allow ephemeral apps to define new permissions.
11444                 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11445                     Slog.w(TAG, "Permission " + p.info.name + " from package "
11446                             + p.info.packageName
11447                             + " ignored: instant apps cannot define new permissions.");
11448                     continue;
11449                 }
11450
11451                 // Assume by default that we did not install this permission into the system.
11452                 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11453
11454                 // Now that permission groups have a special meaning, we ignore permission
11455                 // groups for legacy apps to prevent unexpected behavior. In particular,
11456                 // permissions for one app being granted to someone just because they happen
11457                 // to be in a group defined by another app (before this had no implications).
11458                 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11459                     p.group = mPermissionGroups.get(p.info.group);
11460                     // Warn for a permission in an unknown group.
11461                     if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11462                         Slog.i(TAG, "Permission " + p.info.name + " from package "
11463                                 + p.info.packageName + " in an unknown group " + p.info.group);
11464                     }
11465                 }
11466
11467                 ArrayMap<String, BasePermission> permissionMap =
11468                         p.tree ? mSettings.mPermissionTrees
11469                                 : mSettings.mPermissions;
11470                 BasePermission bp = permissionMap.get(p.info.name);
11471
11472                 // Allow system apps to redefine non-system permissions
11473                 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11474                     final boolean currentOwnerIsSystem = (bp.perm != null
11475                             && isSystemApp(bp.perm.owner));
11476                     if (isSystemApp(p.owner)) {
11477                         if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11478                             // It's a built-in permission and no owner, take ownership now
11479                             bp.packageSetting = pkgSetting;
11480                             bp.perm = p;
11481                             bp.uid = pkg.applicationInfo.uid;
11482                             bp.sourcePackage = p.info.packageName;
11483                             p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11484                         } else if (!currentOwnerIsSystem) {
11485                             String msg = "New decl " + p.owner + " of permission  "
11486                                     + p.info.name + " is system; overriding " + bp.sourcePackage;
11487                             reportSettingsProblem(Log.WARN, msg);
11488                             bp = null;
11489                         }
11490                     }
11491                 }
11492
11493                 if (bp == null) {
11494                     bp = new BasePermission(p.info.name, p.info.packageName,
11495                             BasePermission.TYPE_NORMAL);
11496                     permissionMap.put(p.info.name, bp);
11497                 }
11498
11499                 if (bp.perm == null) {
11500                     if (bp.sourcePackage == null
11501                             || bp.sourcePackage.equals(p.info.packageName)) {
11502                         BasePermission tree = findPermissionTreeLP(p.info.name);
11503                         if (tree == null
11504                                 || tree.sourcePackage.equals(p.info.packageName)) {
11505                             bp.packageSetting = pkgSetting;
11506                             bp.perm = p;
11507                             bp.uid = pkg.applicationInfo.uid;
11508                             bp.sourcePackage = p.info.packageName;
11509                             p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11510                             if (chatty) {
11511                                 if (r == null) {
11512                                     r = new StringBuilder(256);
11513                                 } else {
11514                                     r.append(' ');
11515                                 }
11516                                 r.append(p.info.name);
11517                             }
11518                         } else {
11519                             Slog.w(TAG, "Permission " + p.info.name + " from package "
11520                                     + p.info.packageName + " ignored: base tree "
11521                                     + tree.name + " is from package "
11522                                     + tree.sourcePackage);
11523                         }
11524                     } else {
11525                         Slog.w(TAG, "Permission " + p.info.name + " from package "
11526                                 + p.info.packageName + " ignored: original from "
11527                                 + bp.sourcePackage);
11528                     }
11529                 } else if (chatty) {
11530                     if (r == null) {
11531                         r = new StringBuilder(256);
11532                     } else {
11533                         r.append(' ');
11534                     }
11535                     r.append("DUP:");
11536                     r.append(p.info.name);
11537                 }
11538                 if (bp.perm == p) {
11539                     bp.protectionLevel = p.info.protectionLevel;
11540                 }
11541             }
11542
11543             if (r != null) {
11544                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11545             }
11546
11547             N = pkg.instrumentation.size();
11548             r = null;
11549             for (i=0; i<N; i++) {
11550                 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11551                 a.info.packageName = pkg.applicationInfo.packageName;
11552                 a.info.sourceDir = pkg.applicationInfo.sourceDir;
11553                 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11554                 a.info.splitNames = pkg.splitNames;
11555                 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11556                 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11557                 a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11558                 a.info.dataDir = pkg.applicationInfo.dataDir;
11559                 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11560                 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11561                 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11562                 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11563                 mInstrumentation.put(a.getComponentName(), a);
11564                 if (chatty) {
11565                     if (r == null) {
11566                         r = new StringBuilder(256);
11567                     } else {
11568                         r.append(' ');
11569                     }
11570                     r.append(a.info.name);
11571                 }
11572             }
11573             if (r != null) {
11574                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11575             }
11576
11577             if (pkg.protectedBroadcasts != null) {
11578                 N = pkg.protectedBroadcasts.size();
11579                 for (i=0; i<N; i++) {
11580                     mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11581                 }
11582             }
11583         }
11584
11585         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11586     }
11587
11588     /**
11589      * Derive the ABI of a non-system package located at {@code scanFile}. This information
11590      * is derived purely on the basis of the contents of {@code scanFile} and
11591      * {@code cpuAbiOverride}.
11592      *
11593      * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11594      */
11595     private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11596                                  String cpuAbiOverride, boolean extractLibs,
11597                                  File appLib32InstallDir)
11598             throws PackageManagerException {
11599         // Give ourselves some initial paths; we'll come back for another
11600         // pass once we've determined ABI below.
11601         setNativeLibraryPaths(pkg, appLib32InstallDir);
11602
11603         // We would never need to extract libs for forward-locked and external packages,
11604         // since the container service will do it for us. We shouldn't attempt to
11605         // extract libs from system app when it was not updated.
11606         if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11607                 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11608             extractLibs = false;
11609         }
11610
11611         final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11612         final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11613
11614         NativeLibraryHelper.Handle handle = null;
11615         try {
11616             handle = NativeLibraryHelper.Handle.create(pkg);
11617             // TODO(multiArch): This can be null for apps that didn't go through the
11618             // usual installation process. We can calculate it again, like we
11619             // do during install time.
11620             //
11621             // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11622             // unnecessary.
11623             final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11624
11625             // Null out the abis so that they can be recalculated.
11626             pkg.applicationInfo.primaryCpuAbi = null;
11627             pkg.applicationInfo.secondaryCpuAbi = null;
11628             if (isMultiArch(pkg.applicationInfo)) {
11629                 // Warn if we've set an abiOverride for multi-lib packages..
11630                 // By definition, we need to copy both 32 and 64 bit libraries for
11631                 // such packages.
11632                 if (pkg.cpuAbiOverride != null
11633                         && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11634                     Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11635                 }
11636
11637                 int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11638                 int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11639                 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11640                     if (extractLibs) {
11641                         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11642                         abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11643                                 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11644                                 useIsaSpecificSubdirs);
11645                     } else {
11646                         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11647                         abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11648                     }
11649                     Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11650                 }
11651
11652                 // Shared library native code should be in the APK zip aligned
11653                 if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11654                     throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11655                             "Shared library native lib extraction not supported");
11656                 }
11657
11658                 maybeThrowExceptionForMultiArchCopy(
11659                         "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11660
11661                 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11662                     if (extractLibs) {
11663                         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11664                         abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11665                                 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11666                                 useIsaSpecificSubdirs);
11667                     } else {
11668                         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11669                         abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11670                     }
11671                     Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11672                 }
11673
11674                 maybeThrowExceptionForMultiArchCopy(
11675                         "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11676
11677                 if (abi64 >= 0) {
11678                     // Shared library native libs should be in the APK zip aligned
11679                     if (extractLibs && pkg.isLibrary()) {
11680                         throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11681                                 "Shared library native lib extraction not supported");
11682                     }
11683                     pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11684                 }
11685
11686                 if (abi32 >= 0) {
11687                     final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11688                     if (abi64 >= 0) {
11689                         if (pkg.use32bitAbi) {
11690                             pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11691                             pkg.applicationInfo.primaryCpuAbi = abi;
11692                         } else {
11693                             pkg.applicationInfo.secondaryCpuAbi = abi;
11694                         }
11695                     } else {
11696                         pkg.applicationInfo.primaryCpuAbi = abi;
11697                     }
11698                 }
11699             } else {
11700                 String[] abiList = (cpuAbiOverride != null) ?
11701                         new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11702
11703                 // Enable gross and lame hacks for apps that are built with old
11704                 // SDK tools. We must scan their APKs for renderscript bitcode and
11705                 // not launch them if it's present. Don't bother checking on devices
11706                 // that don't have 64 bit support.
11707                 boolean needsRenderScriptOverride = false;
11708                 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11709                         NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11710                     abiList = Build.SUPPORTED_32_BIT_ABIS;
11711                     needsRenderScriptOverride = true;
11712                 }
11713
11714                 final int copyRet;
11715                 if (extractLibs) {
11716                     Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11717                     copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11718                             nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11719                 } else {
11720                     Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11721                     copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11722                 }
11723                 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11724
11725                 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11726                     throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11727                             "Error unpackaging native libs for app, errorCode=" + copyRet);
11728                 }
11729
11730                 if (copyRet >= 0) {
11731                     // Shared libraries that have native libs must be multi-architecture
11732                     if (pkg.isLibrary()) {
11733                         throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11734                                 "Shared library with native libs must be multiarch");
11735                     }
11736                     pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11737                 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11738                     pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11739                 } else if (needsRenderScriptOverride) {
11740                     pkg.applicationInfo.primaryCpuAbi = abiList[0];
11741                 }
11742             }
11743         } catch (IOException ioe) {
11744             Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11745         } finally {
11746             IoUtils.closeQuietly(handle);
11747         }
11748
11749         // Now that we've calculated the ABIs and determined if it's an internal app,
11750         // we will go ahead and populate the nativeLibraryPath.
11751         setNativeLibraryPaths(pkg, appLib32InstallDir);
11752     }
11753
11754     /**
11755      * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11756      * i.e, so that all packages can be run inside a single process if required.
11757      *
11758      * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11759      * this function will either try and make the ABI for all packages in {@code packagesForUser}
11760      * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11761      * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11762      * updating a package that belongs to a shared user.
11763      *
11764      * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11765      * adds unnecessary complexity.
11766      */
11767     private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11768             PackageParser.Package scannedPackage) {
11769         String requiredInstructionSet = null;
11770         if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11771             requiredInstructionSet = VMRuntime.getInstructionSet(
11772                      scannedPackage.applicationInfo.primaryCpuAbi);
11773         }
11774
11775         PackageSetting requirer = null;
11776         for (PackageSetting ps : packagesForUser) {
11777             // If packagesForUser contains scannedPackage, we skip it. This will happen
11778             // when scannedPackage is an update of an existing package. Without this check,
11779             // we will never be able to change the ABI of any package belonging to a shared
11780             // user, even if it's compatible with other packages.
11781             if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11782                 if (ps.primaryCpuAbiString == null) {
11783                     continue;
11784                 }
11785
11786                 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11787                 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11788                     // We have a mismatch between instruction sets (say arm vs arm64) warn about
11789                     // this but there's not much we can do.
11790                     String errorMessage = "Instruction set mismatch, "
11791                             + ((requirer == null) ? "[caller]" : requirer)
11792                             + " requires " + requiredInstructionSet + " whereas " + ps
11793                             + " requires " + instructionSet;
11794                     Slog.w(TAG, errorMessage);
11795                 }
11796
11797                 if (requiredInstructionSet == null) {
11798                     requiredInstructionSet = instructionSet;
11799                     requirer = ps;
11800                 }
11801             }
11802         }
11803
11804         if (requiredInstructionSet != null) {
11805             String adjustedAbi;
11806             if (requirer != null) {
11807                 // requirer != null implies that either scannedPackage was null or that scannedPackage
11808                 // did not require an ABI, in which case we have to adjust scannedPackage to match
11809                 // the ABI of the set (which is the same as requirer's ABI)
11810                 adjustedAbi = requirer.primaryCpuAbiString;
11811                 if (scannedPackage != null) {
11812                     scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11813                 }
11814             } else {
11815                 // requirer == null implies that we're updating all ABIs in the set to
11816                 // match scannedPackage.
11817                 adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11818             }
11819
11820             for (PackageSetting ps : packagesForUser) {
11821                 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11822                     if (ps.primaryCpuAbiString != null) {
11823                         continue;
11824                     }
11825
11826                     ps.primaryCpuAbiString = adjustedAbi;
11827                     if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11828                             !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11829                         ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11830                         if (DEBUG_ABI_SELECTION) {
11831                             Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11832                                     + " (requirer="
11833                                     + (requirer != null ? requirer.pkg : "null")
11834                                     + ", scannedPackage="
11835                                     + (scannedPackage != null ? scannedPackage : "null")
11836                                     + ")");
11837                         }
11838                         try {
11839                             mInstaller.rmdex(ps.codePathString,
11840                                     getDexCodeInstructionSet(getPreferredInstructionSet()));
11841                         } catch (InstallerException ignored) {
11842                         }
11843                     }
11844                 }
11845             }
11846         }
11847     }
11848
11849     private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11850         synchronized (mPackages) {
11851             mResolverReplaced = true;
11852             // Set up information for custom user intent resolution activity.
11853             mResolveActivity.applicationInfo = pkg.applicationInfo;
11854             mResolveActivity.name = mCustomResolverComponentName.getClassName();
11855             mResolveActivity.packageName = pkg.applicationInfo.packageName;
11856             mResolveActivity.processName = pkg.applicationInfo.packageName;
11857             mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11858             mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11859                     ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11860             mResolveActivity.theme = 0;
11861             mResolveActivity.exported = true;
11862             mResolveActivity.enabled = true;
11863             mResolveInfo.activityInfo = mResolveActivity;
11864             mResolveInfo.priority = 0;
11865             mResolveInfo.preferredOrder = 0;
11866             mResolveInfo.match = 0;
11867             mResolveComponentName = mCustomResolverComponentName;
11868             Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11869                     mResolveComponentName);
11870         }
11871     }
11872
11873     private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11874         if (installerActivity == null) {
11875             if (DEBUG_EPHEMERAL) {
11876                 Slog.d(TAG, "Clear ephemeral installer activity");
11877             }
11878             mInstantAppInstallerActivity = null;
11879             return;
11880         }
11881
11882         if (DEBUG_EPHEMERAL) {
11883             Slog.d(TAG, "Set ephemeral installer activity: "
11884                     + installerActivity.getComponentName());
11885         }
11886         // Set up information for ephemeral installer activity
11887         mInstantAppInstallerActivity = installerActivity;
11888         mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11889                 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11890         mInstantAppInstallerActivity.exported = true;
11891         mInstantAppInstallerActivity.enabled = true;
11892         mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11893         mInstantAppInstallerInfo.priority = 0;
11894         mInstantAppInstallerInfo.preferredOrder = 1;
11895         mInstantAppInstallerInfo.isDefault = true;
11896         mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11897                 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11898     }
11899
11900     private static String calculateBundledApkRoot(final String codePathString) {
11901         final File codePath = new File(codePathString);
11902         final File codeRoot;
11903         if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11904             codeRoot = Environment.getRootDirectory();
11905         } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11906             codeRoot = Environment.getOemDirectory();
11907         } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11908             codeRoot = Environment.getVendorDirectory();
11909         } else {
11910             // Unrecognized code path; take its top real segment as the apk root:
11911             // e.g. /something/app/blah.apk => /something
11912             try {
11913                 File f = codePath.getCanonicalFile();
11914                 File parent = f.getParentFile();    // non-null because codePath is a file
11915                 File tmp;
11916                 while ((tmp = parent.getParentFile()) != null) {
11917                     f = parent;
11918                     parent = tmp;
11919                 }
11920                 codeRoot = f;
11921                 Slog.w(TAG, "Unrecognized code path "
11922                         + codePath + " - using " + codeRoot);
11923             } catch (IOException e) {
11924                 // Can't canonicalize the code path -- shenanigans?
11925                 Slog.w(TAG, "Can't canonicalize code path " + codePath);
11926                 return Environment.getRootDirectory().getPath();
11927             }
11928         }
11929         return codeRoot.getPath();
11930     }
11931
11932     /**
11933      * Derive and set the location of native libraries for the given package,
11934      * which varies depending on where and how the package was installed.
11935      */
11936     private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11937         final ApplicationInfo info = pkg.applicationInfo;
11938         final String codePath = pkg.codePath;
11939         final File codeFile = new File(codePath);
11940         final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11941         final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11942
11943         info.nativeLibraryRootDir = null;
11944         info.nativeLibraryRootRequiresIsa = false;
11945         info.nativeLibraryDir = null;
11946         info.secondaryNativeLibraryDir = null;
11947
11948         if (isApkFile(codeFile)) {
11949             // Monolithic install
11950             if (bundledApp) {
11951                 // If "/system/lib64/apkname" exists, assume that is the per-package
11952                 // native library directory to use; otherwise use "/system/lib/apkname".
11953                 final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11954                 final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11955                         getPrimaryInstructionSet(info));
11956
11957                 // This is a bundled system app so choose the path based on the ABI.
11958                 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11959                 // is just the default path.
11960                 final String apkName = deriveCodePathName(codePath);
11961                 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11962                 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11963                         apkName).getAbsolutePath();
11964
11965                 if (info.secondaryCpuAbi != null) {
11966                     final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11967                     info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11968                             secondaryLibDir, apkName).getAbsolutePath();
11969                 }
11970             } else if (asecApp) {
11971                 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11972                         .getAbsolutePath();
11973             } else {
11974                 final String apkName = deriveCodePathName(codePath);
11975                 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11976                         .getAbsolutePath();
11977             }
11978
11979             info.nativeLibraryRootRequiresIsa = false;
11980             info.nativeLibraryDir = info.nativeLibraryRootDir;
11981         } else {
11982             // Cluster install
11983             info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11984             info.nativeLibraryRootRequiresIsa = true;
11985
11986             info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11987                     getPrimaryInstructionSet(info)).getAbsolutePath();
11988
11989             if (info.secondaryCpuAbi != null) {
11990                 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11991                         VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11992             }
11993         }
11994     }
11995
11996     /**
11997      * Calculate the abis and roots for a bundled app. These can uniquely
11998      * be determined from the contents of the system partition, i.e whether
11999      * it contains 64 or 32 bit shared libraries etc. We do not validate any
12000      * of this information, and instead assume that the system was built
12001      * sensibly.
12002      */
12003     private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12004                                            PackageSetting pkgSetting) {
12005         final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12006
12007         // If "/system/lib64/apkname" exists, assume that is the per-package
12008         // native library directory to use; otherwise use "/system/lib/apkname".
12009         final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12010         setBundledAppAbi(pkg, apkRoot, apkName);
12011         // pkgSetting might be null during rescan following uninstall of updates
12012         // to a bundled app, so accommodate that possibility.  The settings in
12013         // that case will be established later from the parsed package.
12014         //
12015         // If the settings aren't null, sync them up with what we've just derived.
12016         // note that apkRoot isn't stored in the package settings.
12017         if (pkgSetting != null) {
12018             pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12019             pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12020         }
12021     }
12022
12023     /**
12024      * Deduces the ABI of a bundled app and sets the relevant fields on the
12025      * parsed pkg object.
12026      *
12027      * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12028      *        under which system libraries are installed.
12029      * @param apkName the name of the installed package.
12030      */
12031     private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12032         final File codeFile = new File(pkg.codePath);
12033
12034         final boolean has64BitLibs;
12035         final boolean has32BitLibs;
12036         if (isApkFile(codeFile)) {
12037             // Monolithic install
12038             has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12039             has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12040         } else {
12041             // Cluster install
12042             final File rootDir = new File(codeFile, LIB_DIR_NAME);
12043             if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12044                     && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12045                 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12046                 has64BitLibs = (new File(rootDir, isa)).exists();
12047             } else {
12048                 has64BitLibs = false;
12049             }
12050             if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12051                     && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12052                 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12053                 has32BitLibs = (new File(rootDir, isa)).exists();
12054             } else {
12055                 has32BitLibs = false;
12056             }
12057         }
12058
12059         if (has64BitLibs && !has32BitLibs) {
12060             // The package has 64 bit libs, but not 32 bit libs. Its primary
12061             // ABI should be 64 bit. We can safely assume here that the bundled
12062             // native libraries correspond to the most preferred ABI in the list.
12063
12064             pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12065             pkg.applicationInfo.secondaryCpuAbi = null;
12066         } else if (has32BitLibs && !has64BitLibs) {
12067             // The package has 32 bit libs but not 64 bit libs. Its primary
12068             // ABI should be 32 bit.
12069
12070             pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12071             pkg.applicationInfo.secondaryCpuAbi = null;
12072         } else if (has32BitLibs && has64BitLibs) {
12073             // The application has both 64 and 32 bit bundled libraries. We check
12074             // here that the app declares multiArch support, and warn if it doesn't.
12075             //
12076             // We will be lenient here and record both ABIs. The primary will be the
12077             // ABI that's higher on the list, i.e, a device that's configured to prefer
12078             // 64 bit apps will see a 64 bit primary ABI,
12079
12080             if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12081                 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12082             }
12083
12084             if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12085                 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12086                 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12087             } else {
12088                 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12089                 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12090             }
12091         } else {
12092             pkg.applicationInfo.primaryCpuAbi = null;
12093             pkg.applicationInfo.secondaryCpuAbi = null;
12094         }
12095     }
12096
12097     private void killApplication(String pkgName, int appId, String reason) {
12098         killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12099     }
12100
12101     private void killApplication(String pkgName, int appId, int userId, String reason) {
12102         // Request the ActivityManager to kill the process(only for existing packages)
12103         // so that we do not end up in a confused state while the user is still using the older
12104         // version of the application while the new one gets installed.
12105         final long token = Binder.clearCallingIdentity();
12106         try {
12107             IActivityManager am = ActivityManager.getService();
12108             if (am != null) {
12109                 try {
12110                     am.killApplication(pkgName, appId, userId, reason);
12111                 } catch (RemoteException e) {
12112                 }
12113             }
12114         } finally {
12115             Binder.restoreCallingIdentity(token);
12116         }
12117     }
12118
12119     private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12120         // Remove the parent package setting
12121         PackageSetting ps = (PackageSetting) pkg.mExtras;
12122         if (ps != null) {
12123             removePackageLI(ps, chatty);
12124         }
12125         // Remove the child package setting
12126         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12127         for (int i = 0; i < childCount; i++) {
12128             PackageParser.Package childPkg = pkg.childPackages.get(i);
12129             ps = (PackageSetting) childPkg.mExtras;
12130             if (ps != null) {
12131                 removePackageLI(ps, chatty);
12132             }
12133         }
12134     }
12135
12136     void removePackageLI(PackageSetting ps, boolean chatty) {
12137         if (DEBUG_INSTALL) {
12138             if (chatty)
12139                 Log.d(TAG, "Removing package " + ps.name);
12140         }
12141
12142         // writer
12143         synchronized (mPackages) {
12144             mPackages.remove(ps.name);
12145             final PackageParser.Package pkg = ps.pkg;
12146             if (pkg != null) {
12147                 cleanPackageDataStructuresLILPw(pkg, chatty);
12148             }
12149         }
12150     }
12151
12152     void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12153         if (DEBUG_INSTALL) {
12154             if (chatty)
12155                 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12156         }
12157
12158         // writer
12159         synchronized (mPackages) {
12160             // Remove the parent package
12161             mPackages.remove(pkg.applicationInfo.packageName);
12162             cleanPackageDataStructuresLILPw(pkg, chatty);
12163
12164             // Remove the child packages
12165             final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12166             for (int i = 0; i < childCount; i++) {
12167                 PackageParser.Package childPkg = pkg.childPackages.get(i);
12168                 mPackages.remove(childPkg.applicationInfo.packageName);
12169                 cleanPackageDataStructuresLILPw(childPkg, chatty);
12170             }
12171         }
12172     }
12173
12174     void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12175         int N = pkg.providers.size();
12176         StringBuilder r = null;
12177         int i;
12178         for (i=0; i<N; i++) {
12179             PackageParser.Provider p = pkg.providers.get(i);
12180             mProviders.removeProvider(p);
12181             if (p.info.authority == null) {
12182
12183                 /* There was another ContentProvider with this authority when
12184                  * this app was installed so this authority is null,
12185                  * Ignore it as we don't have to unregister the provider.
12186                  */
12187                 continue;
12188             }
12189             String names[] = p.info.authority.split(";");
12190             for (int j = 0; j < names.length; j++) {
12191                 if (mProvidersByAuthority.get(names[j]) == p) {
12192                     mProvidersByAuthority.remove(names[j]);
12193                     if (DEBUG_REMOVE) {
12194                         if (chatty)
12195                             Log.d(TAG, "Unregistered content provider: " + names[j]
12196                                     + ", className = " + p.info.name + ", isSyncable = "
12197                                     + p.info.isSyncable);
12198                     }
12199                 }
12200             }
12201             if (DEBUG_REMOVE && chatty) {
12202                 if (r == null) {
12203                     r = new StringBuilder(256);
12204                 } else {
12205                     r.append(' ');
12206                 }
12207                 r.append(p.info.name);
12208             }
12209         }
12210         if (r != null) {
12211             if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12212         }
12213
12214         N = pkg.services.size();
12215         r = null;
12216         for (i=0; i<N; i++) {
12217             PackageParser.Service s = pkg.services.get(i);
12218             mServices.removeService(s);
12219             if (chatty) {
12220                 if (r == null) {
12221                     r = new StringBuilder(256);
12222                 } else {
12223                     r.append(' ');
12224                 }
12225                 r.append(s.info.name);
12226             }
12227         }
12228         if (r != null) {
12229             if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12230         }
12231
12232         N = pkg.receivers.size();
12233         r = null;
12234         for (i=0; i<N; i++) {
12235             PackageParser.Activity a = pkg.receivers.get(i);
12236             mReceivers.removeActivity(a, "receiver");
12237             if (DEBUG_REMOVE && chatty) {
12238                 if (r == null) {
12239                     r = new StringBuilder(256);
12240                 } else {
12241                     r.append(' ');
12242                 }
12243                 r.append(a.info.name);
12244             }
12245         }
12246         if (r != null) {
12247             if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12248         }
12249
12250         N = pkg.activities.size();
12251         r = null;
12252         for (i=0; i<N; i++) {
12253             PackageParser.Activity a = pkg.activities.get(i);
12254             mActivities.removeActivity(a, "activity");
12255             if (DEBUG_REMOVE && chatty) {
12256                 if (r == null) {
12257                     r = new StringBuilder(256);
12258                 } else {
12259                     r.append(' ');
12260                 }
12261                 r.append(a.info.name);
12262             }
12263         }
12264         if (r != null) {
12265             if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12266         }
12267
12268         N = pkg.permissions.size();
12269         r = null;
12270         for (i=0; i<N; i++) {
12271             PackageParser.Permission p = pkg.permissions.get(i);
12272             BasePermission bp = mSettings.mPermissions.get(p.info.name);
12273             if (bp == null) {
12274                 bp = mSettings.mPermissionTrees.get(p.info.name);
12275             }
12276             if (bp != null && bp.perm == p) {
12277                 bp.perm = null;
12278                 if (DEBUG_REMOVE && chatty) {
12279                     if (r == null) {
12280                         r = new StringBuilder(256);
12281                     } else {
12282                         r.append(' ');
12283                     }
12284                     r.append(p.info.name);
12285                 }
12286             }
12287             if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12288                 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12289                 if (appOpPkgs != null) {
12290                     appOpPkgs.remove(pkg.packageName);
12291                 }
12292             }
12293         }
12294         if (r != null) {
12295             if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12296         }
12297
12298         N = pkg.requestedPermissions.size();
12299         r = null;
12300         for (i=0; i<N; i++) {
12301             String perm = pkg.requestedPermissions.get(i);
12302             BasePermission bp = mSettings.mPermissions.get(perm);
12303             if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12304                 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12305                 if (appOpPkgs != null) {
12306                     appOpPkgs.remove(pkg.packageName);
12307                     if (appOpPkgs.isEmpty()) {
12308                         mAppOpPermissionPackages.remove(perm);
12309                     }
12310                 }
12311             }
12312         }
12313         if (r != null) {
12314             if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12315         }
12316
12317         N = pkg.instrumentation.size();
12318         r = null;
12319         for (i=0; i<N; i++) {
12320             PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12321             mInstrumentation.remove(a.getComponentName());
12322             if (DEBUG_REMOVE && chatty) {
12323                 if (r == null) {
12324                     r = new StringBuilder(256);
12325                 } else {
12326                     r.append(' ');
12327                 }
12328                 r.append(a.info.name);
12329             }
12330         }
12331         if (r != null) {
12332             if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12333         }
12334
12335         r = null;
12336         if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12337             // Only system apps can hold shared libraries.
12338             if (pkg.libraryNames != null) {
12339                 for (i = 0; i < pkg.libraryNames.size(); i++) {
12340                     String name = pkg.libraryNames.get(i);
12341                     if (removeSharedLibraryLPw(name, 0)) {
12342                         if (DEBUG_REMOVE && chatty) {
12343                             if (r == null) {
12344                                 r = new StringBuilder(256);
12345                             } else {
12346                                 r.append(' ');
12347                             }
12348                             r.append(name);
12349                         }
12350                     }
12351                 }
12352             }
12353         }
12354
12355         r = null;
12356
12357         // Any package can hold static shared libraries.
12358         if (pkg.staticSharedLibName != null) {
12359             if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12360                 if (DEBUG_REMOVE && chatty) {
12361                     if (r == null) {
12362                         r = new StringBuilder(256);
12363                     } else {
12364                         r.append(' ');
12365                     }
12366                     r.append(pkg.staticSharedLibName);
12367                 }
12368             }
12369         }
12370
12371         if (r != null) {
12372             if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12373         }
12374     }
12375
12376     private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12377         for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12378             if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12379                 return true;
12380             }
12381         }
12382         return false;
12383     }
12384
12385     static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12386     static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12387     static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12388
12389     private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12390         // Update the parent permissions
12391         updatePermissionsLPw(pkg.packageName, pkg, flags);
12392         // Update the child permissions
12393         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12394         for (int i = 0; i < childCount; i++) {
12395             PackageParser.Package childPkg = pkg.childPackages.get(i);
12396             updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12397         }
12398     }
12399
12400     private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12401             int flags) {
12402         final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12403         updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12404     }
12405
12406     private void updatePermissionsLPw(String changingPkg,
12407             PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12408         // Make sure there are no dangling permission trees.
12409         Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12410         while (it.hasNext()) {
12411             final BasePermission bp = it.next();
12412             if (bp.packageSetting == null) {
12413                 // We may not yet have parsed the package, so just see if
12414                 // we still know about its settings.
12415                 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12416             }
12417             if (bp.packageSetting == null) {
12418                 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12419                         + " from package " + bp.sourcePackage);
12420                 it.remove();
12421             } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12422                 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12423                     Slog.i(TAG, "Removing old permission tree: " + bp.name
12424                             + " from package " + bp.sourcePackage);
12425                     flags |= UPDATE_PERMISSIONS_ALL;
12426                     it.remove();
12427                 }
12428             }
12429         }
12430
12431         // Make sure all dynamic permissions have been assigned to a package,
12432         // and make sure there are no dangling permissions.
12433         it = mSettings.mPermissions.values().iterator();
12434         while (it.hasNext()) {
12435             final BasePermission bp = it.next();
12436             if (bp.type == BasePermission.TYPE_DYNAMIC) {
12437                 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12438                         + bp.name + " pkg=" + bp.sourcePackage
12439                         + " info=" + bp.pendingInfo);
12440                 if (bp.packageSetting == null && bp.pendingInfo != null) {
12441                     final BasePermission tree = findPermissionTreeLP(bp.name);
12442                     if (tree != null && tree.perm != null) {
12443                         bp.packageSetting = tree.packageSetting;
12444                         bp.perm = new PackageParser.Permission(tree.perm.owner,
12445                                 new PermissionInfo(bp.pendingInfo));
12446                         bp.perm.info.packageName = tree.perm.info.packageName;
12447                         bp.perm.info.name = bp.name;
12448                         bp.uid = tree.uid;
12449                     }
12450                 }
12451             }
12452             if (bp.packageSetting == null) {
12453                 // We may not yet have parsed the package, so just see if
12454                 // we still know about its settings.
12455                 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12456             }
12457             if (bp.packageSetting == null) {
12458                 Slog.w(TAG, "Removing dangling permission: " + bp.name
12459                         + " from package " + bp.sourcePackage);
12460                 it.remove();
12461             } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12462                 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12463                     Slog.i(TAG, "Removing old permission: " + bp.name
12464                             + " from package " + bp.sourcePackage);
12465                     flags |= UPDATE_PERMISSIONS_ALL;
12466                     it.remove();
12467                 }
12468             }
12469         }
12470
12471         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12472         // Now update the permissions for all packages, in particular
12473         // replace the granted permissions of the system packages.
12474         if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12475             for (PackageParser.Package pkg : mPackages.values()) {
12476                 if (pkg != pkgInfo) {
12477                     // Only replace for packages on requested volume
12478                     final String volumeUuid = getVolumeUuidForPackage(pkg);
12479                     final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12480                             && Objects.equals(replaceVolumeUuid, volumeUuid);
12481                     grantPermissionsLPw(pkg, replace, changingPkg);
12482                 }
12483             }
12484         }
12485
12486         if (pkgInfo != null) {
12487             // Only replace for packages on requested volume
12488             final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12489             final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12490                     && Objects.equals(replaceVolumeUuid, volumeUuid);
12491             grantPermissionsLPw(pkgInfo, replace, changingPkg);
12492         }
12493         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12494     }
12495
12496     private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12497             String packageOfInterest) {
12498         // IMPORTANT: There are two types of permissions: install and runtime.
12499         // Install time permissions are granted when the app is installed to
12500         // all device users and users added in the future. Runtime permissions
12501         // are granted at runtime explicitly to specific users. Normal and signature
12502         // protected permissions are install time permissions. Dangerous permissions
12503         // are install permissions if the app's target SDK is Lollipop MR1 or older,
12504         // otherwise they are runtime permissions. This function does not manage
12505         // runtime permissions except for the case an app targeting Lollipop MR1
12506         // being upgraded to target a newer SDK, in which case dangerous permissions
12507         // are transformed from install time to runtime ones.
12508
12509         final PackageSetting ps = (PackageSetting) pkg.mExtras;
12510         if (ps == null) {
12511             return;
12512         }
12513
12514         PermissionsState permissionsState = ps.getPermissionsState();
12515         PermissionsState origPermissions = permissionsState;
12516
12517         final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12518
12519         boolean runtimePermissionsRevoked = false;
12520         int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12521
12522         boolean changedInstallPermission = false;
12523
12524         if (replace) {
12525             ps.installPermissionsFixed = false;
12526             if (!ps.isSharedUser()) {
12527                 origPermissions = new PermissionsState(permissionsState);
12528                 permissionsState.reset();
12529             } else {
12530                 // We need to know only about runtime permission changes since the
12531                 // calling code always writes the install permissions state but
12532                 // the runtime ones are written only if changed. The only cases of
12533                 // changed runtime permissions here are promotion of an install to
12534                 // runtime and revocation of a runtime from a shared user.
12535                 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12536                         ps.sharedUser, UserManagerService.getInstance().getUserIds());
12537                 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12538                     runtimePermissionsRevoked = true;
12539                 }
12540             }
12541         }
12542
12543         permissionsState.setGlobalGids(mGlobalGids);
12544
12545         final int N = pkg.requestedPermissions.size();
12546         for (int i=0; i<N; i++) {
12547             final String name = pkg.requestedPermissions.get(i);
12548             final BasePermission bp = mSettings.mPermissions.get(name);
12549             final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12550                     >= Build.VERSION_CODES.M;
12551
12552             if (DEBUG_INSTALL) {
12553                 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12554             }
12555
12556             if (bp == null || bp.packageSetting == null) {
12557                 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12558                     if (DEBUG_PERMISSIONS) {
12559                         Slog.i(TAG, "Unknown permission " + name
12560                                 + " in package " + pkg.packageName);
12561                     }
12562                 }
12563                 continue;
12564             }
12565
12566
12567             // Limit ephemeral apps to ephemeral allowed permissions.
12568             if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12569                 if (DEBUG_PERMISSIONS) {
12570                     Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12571                             + pkg.packageName);
12572                 }
12573                 continue;
12574             }
12575
12576             if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12577                 if (DEBUG_PERMISSIONS) {
12578                     Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12579                             + pkg.packageName);
12580                 }
12581                 continue;
12582             }
12583
12584             final String perm = bp.name;
12585             boolean allowedSig = false;
12586             int grant = GRANT_DENIED;
12587
12588             // Keep track of app op permissions.
12589             if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12590                 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12591                 if (pkgs == null) {
12592                     pkgs = new ArraySet<>();
12593                     mAppOpPermissionPackages.put(bp.name, pkgs);
12594                 }
12595                 pkgs.add(pkg.packageName);
12596             }
12597
12598             final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12599             switch (level) {
12600                 case PermissionInfo.PROTECTION_NORMAL: {
12601                     // For all apps normal permissions are install time ones.
12602                     grant = GRANT_INSTALL;
12603                 } break;
12604
12605                 case PermissionInfo.PROTECTION_DANGEROUS: {
12606                     // If a permission review is required for legacy apps we represent
12607                     // their permissions as always granted runtime ones since we need
12608                     // to keep the review required permission flag per user while an
12609                     // install permission's state is shared across all users.
12610                     if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12611                         // For legacy apps dangerous permissions are install time ones.
12612                         grant = GRANT_INSTALL;
12613                     } else if (origPermissions.hasInstallPermission(bp.name)) {
12614                         // For legacy apps that became modern, install becomes runtime.
12615                         grant = GRANT_UPGRADE;
12616                     } else if (mPromoteSystemApps
12617                             && isSystemApp(ps)
12618                             && mExistingSystemPackages.contains(ps.name)) {
12619                         // For legacy system apps, install becomes runtime.
12620                         // We cannot check hasInstallPermission() for system apps since those
12621                         // permissions were granted implicitly and not persisted pre-M.
12622                         grant = GRANT_UPGRADE;
12623                     } else {
12624                         // For modern apps keep runtime permissions unchanged.
12625                         grant = GRANT_RUNTIME;
12626                     }
12627                 } break;
12628
12629                 case PermissionInfo.PROTECTION_SIGNATURE: {
12630                     // For all apps signature permissions are install time ones.
12631                     allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12632                     if (allowedSig) {
12633                         grant = GRANT_INSTALL;
12634                     }
12635                 } break;
12636             }
12637
12638             if (DEBUG_PERMISSIONS) {
12639                 Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12640             }
12641
12642             if (grant != GRANT_DENIED) {
12643                 if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12644                     // If this is an existing, non-system package, then
12645                     // we can't add any new permissions to it.
12646                     if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12647                         // Except...  if this is a permission that was added
12648                         // to the platform (note: need to only do this when
12649                         // updating the platform).
12650                         if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12651                             grant = GRANT_DENIED;
12652                         }
12653                     }
12654                 }
12655
12656                 switch (grant) {
12657                     case GRANT_INSTALL: {
12658                         // Revoke this as runtime permission to handle the case of
12659                         // a runtime permission being downgraded to an install one.
12660                         // Also in permission review mode we keep dangerous permissions
12661                         // for legacy apps
12662                         for (int userId : UserManagerService.getInstance().getUserIds()) {
12663                             if (origPermissions.getRuntimePermissionState(
12664                                     bp.name, userId) != null) {
12665                                 // Revoke the runtime permission and clear the flags.
12666                                 origPermissions.revokeRuntimePermission(bp, userId);
12667                                 origPermissions.updatePermissionFlags(bp, userId,
12668                                       PackageManager.MASK_PERMISSION_FLAGS, 0);
12669                                 // If we revoked a permission permission, we have to write.
12670                                 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12671                                         changedRuntimePermissionUserIds, userId);
12672                             }
12673                         }
12674                         // Grant an install permission.
12675                         if (permissionsState.grantInstallPermission(bp) !=
12676                                 PermissionsState.PERMISSION_OPERATION_FAILURE) {
12677                             changedInstallPermission = true;
12678                         }
12679                     } break;
12680
12681                     case GRANT_RUNTIME: {
12682                         // Grant previously granted runtime permissions.
12683                         for (int userId : UserManagerService.getInstance().getUserIds()) {
12684                             PermissionState permissionState = origPermissions
12685                                     .getRuntimePermissionState(bp.name, userId);
12686                             int flags = permissionState != null
12687                                     ? permissionState.getFlags() : 0;
12688                             if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12689                                 // Don't propagate the permission in a permission review mode if
12690                                 // the former was revoked, i.e. marked to not propagate on upgrade.
12691                                 // Note that in a permission review mode install permissions are
12692                                 // represented as constantly granted runtime ones since we need to
12693                                 // keep a per user state associated with the permission. Also the
12694                                 // revoke on upgrade flag is no longer applicable and is reset.
12695                                 final boolean revokeOnUpgrade = (flags & PackageManager
12696                                         .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12697                                 if (revokeOnUpgrade) {
12698                                     flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12699                                     // Since we changed the flags, we have to write.
12700                                     changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12701                                             changedRuntimePermissionUserIds, userId);
12702                                 }
12703                                 if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12704                                     if (permissionsState.grantRuntimePermission(bp, userId) ==
12705                                             PermissionsState.PERMISSION_OPERATION_FAILURE) {
12706                                         // If we cannot put the permission as it was,
12707                                         // we have to write.
12708                                         changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12709                                                 changedRuntimePermissionUserIds, userId);
12710                                     }
12711                                 }
12712
12713                                 // If the app supports runtime permissions no need for a review.
12714                                 if (mPermissionReviewRequired
12715                                         && appSupportsRuntimePermissions
12716                                         && (flags & PackageManager
12717                                                 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12718                                     flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12719                                     // Since we changed the flags, we have to write.
12720                                     changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12721                                             changedRuntimePermissionUserIds, userId);
12722                                 }
12723                             } else if (mPermissionReviewRequired
12724                                     && !appSupportsRuntimePermissions) {
12725                                 // For legacy apps that need a permission review, every new
12726                                 // runtime permission is granted but it is pending a review.
12727                                 // We also need to review only platform defined runtime
12728                                 // permissions as these are the only ones the platform knows
12729                                 // how to disable the API to simulate revocation as legacy
12730                                 // apps don't expect to run with revoked permissions.
12731                                 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12732                                     if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12733                                         flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12734                                         // We changed the flags, hence have to write.
12735                                         changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12736                                                 changedRuntimePermissionUserIds, userId);
12737                                     }
12738                                 }
12739                                 if (permissionsState.grantRuntimePermission(bp, userId)
12740                                         != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12741                                     // We changed the permission, hence have to write.
12742                                     changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12743                                             changedRuntimePermissionUserIds, userId);
12744                                 }
12745                             }
12746                             // Propagate the permission flags.
12747                             permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12748                         }
12749                     } break;
12750
12751                     case GRANT_UPGRADE: {
12752                         // Grant runtime permissions for a previously held install permission.
12753                         PermissionState permissionState = origPermissions
12754                                 .getInstallPermissionState(bp.name);
12755                         final int flags = permissionState != null ? permissionState.getFlags() : 0;
12756
12757                         if (origPermissions.revokeInstallPermission(bp)
12758                                 != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12759                             // We will be transferring the permission flags, so clear them.
12760                             origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12761                                     PackageManager.MASK_PERMISSION_FLAGS, 0);
12762                             changedInstallPermission = true;
12763                         }
12764
12765                         // If the permission is not to be promoted to runtime we ignore it and
12766                         // also its other flags as they are not applicable to install permissions.
12767                         if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12768                             for (int userId : currentUserIds) {
12769                                 if (permissionsState.grantRuntimePermission(bp, userId) !=
12770                                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
12771                                     // Transfer the permission flags.
12772                                     permissionsState.updatePermissionFlags(bp, userId,
12773                                             flags, flags);
12774                                     // If we granted the permission, we have to write.
12775                                     changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12776                                             changedRuntimePermissionUserIds, userId);
12777                                 }
12778                             }
12779                         }
12780                     } break;
12781
12782                     default: {
12783                         if (packageOfInterest == null
12784                                 || packageOfInterest.equals(pkg.packageName)) {
12785                             if (DEBUG_PERMISSIONS) {
12786                                 Slog.i(TAG, "Not granting permission " + perm
12787                                         + " to package " + pkg.packageName
12788                                         + " because it was previously installed without");
12789                             }
12790                         }
12791                     } break;
12792                 }
12793             } else {
12794                 if (permissionsState.revokeInstallPermission(bp) !=
12795                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
12796                     // Also drop the permission flags.
12797                     permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12798                             PackageManager.MASK_PERMISSION_FLAGS, 0);
12799                     changedInstallPermission = true;
12800                     Slog.i(TAG, "Un-granting permission " + perm
12801                             + " from package " + pkg.packageName
12802                             + " (protectionLevel=" + bp.protectionLevel
12803                             + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12804                             + ")");
12805                 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12806                     // Don't print warning for app op permissions, since it is fine for them
12807                     // not to be granted, there is a UI for the user to decide.
12808                     if (DEBUG_PERMISSIONS
12809                             && (packageOfInterest == null
12810                                     || packageOfInterest.equals(pkg.packageName))) {
12811                         Slog.i(TAG, "Not granting permission " + perm
12812                                 + " to package " + pkg.packageName
12813                                 + " (protectionLevel=" + bp.protectionLevel
12814                                 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12815                                 + ")");
12816                     }
12817                 }
12818             }
12819         }
12820
12821         if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12822                 !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12823             // This is the first that we have heard about this package, so the
12824             // permissions we have now selected are fixed until explicitly
12825             // changed.
12826             ps.installPermissionsFixed = true;
12827         }
12828
12829         // Persist the runtime permissions state for users with changes. If permissions
12830         // were revoked because no app in the shared user declares them we have to
12831         // write synchronously to avoid losing runtime permissions state.
12832         for (int userId : changedRuntimePermissionUserIds) {
12833             mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12834         }
12835     }
12836
12837     private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12838         boolean allowed = false;
12839         final int NP = PackageParser.NEW_PERMISSIONS.length;
12840         for (int ip=0; ip<NP; ip++) {
12841             final PackageParser.NewPermissionInfo npi
12842                     = PackageParser.NEW_PERMISSIONS[ip];
12843             if (npi.name.equals(perm)
12844                     && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12845                 allowed = true;
12846                 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12847                         + pkg.packageName);
12848                 break;
12849             }
12850         }
12851         return allowed;
12852     }
12853
12854     private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12855             BasePermission bp, PermissionsState origPermissions) {
12856         boolean privilegedPermission = (bp.protectionLevel
12857                 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12858         boolean privappPermissionsDisable =
12859                 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12860         boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12861         boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12862         if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12863                 && !platformPackage && platformPermission) {
12864             ArraySet<String> wlPermissions = SystemConfig.getInstance()
12865                     .getPrivAppPermissions(pkg.packageName);
12866             boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12867             if (!whitelisted) {
12868                 Slog.w(TAG, "Privileged permission " + perm + " for package "
12869                         + pkg.packageName + " - not in privapp-permissions whitelist");
12870                 // Only report violations for apps on system image
12871                 if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12872                     if (mPrivappPermissionsViolations == null) {
12873                         mPrivappPermissionsViolations = new ArraySet<>();
12874                     }
12875                     mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12876                 }
12877                 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12878                     return false;
12879                 }
12880             }
12881         }
12882         boolean allowed = (compareSignatures(
12883                 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12884                         == PackageManager.SIGNATURE_MATCH)
12885                 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12886                         == PackageManager.SIGNATURE_MATCH);
12887         if (!allowed && privilegedPermission) {
12888             if (isSystemApp(pkg)) {
12889                 // For updated system applications, a system permission
12890                 // is granted only if it had been defined by the original application.
12891                 if (pkg.isUpdatedSystemApp()) {
12892                     final PackageSetting sysPs = mSettings
12893                             .getDisabledSystemPkgLPr(pkg.packageName);
12894                     if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12895                         // If the original was granted this permission, we take
12896                         // that grant decision as read and propagate it to the
12897                         // update.
12898                         if (sysPs.isPrivileged()) {
12899                             allowed = true;
12900                         }
12901                     } else {
12902                         // The system apk may have been updated with an older
12903                         // version of the one on the data partition, but which
12904                         // granted a new system permission that it didn't have
12905                         // before.  In this case we do want to allow the app to
12906                         // now get the new permission if the ancestral apk is
12907                         // privileged to get it.
12908                         if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12909                             for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12910                                 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12911                                     allowed = true;
12912                                     break;
12913                                 }
12914                             }
12915                         }
12916                         // Also if a privileged parent package on the system image or any of
12917                         // its children requested a privileged permission, the updated child
12918                         // packages can also get the permission.
12919                         if (pkg.parentPackage != null) {
12920                             final PackageSetting disabledSysParentPs = mSettings
12921                                     .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12922                             if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12923                                     && disabledSysParentPs.isPrivileged()) {
12924                                 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12925                                     allowed = true;
12926                                 } else if (disabledSysParentPs.pkg.childPackages != null) {
12927                                     final int count = disabledSysParentPs.pkg.childPackages.size();
12928                                     for (int i = 0; i < count; i++) {
12929                                         PackageParser.Package disabledSysChildPkg =
12930                                                 disabledSysParentPs.pkg.childPackages.get(i);
12931                                         if (isPackageRequestingPermission(disabledSysChildPkg,
12932                                                 perm)) {
12933                                             allowed = true;
12934                                             break;
12935                                         }
12936                                     }
12937                                 }
12938                             }
12939                         }
12940                     }
12941                 } else {
12942                     allowed = isPrivilegedApp(pkg);
12943                 }
12944             }
12945         }
12946         if (!allowed) {
12947             if (!allowed && (bp.protectionLevel
12948                     & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12949                     && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12950                 // If this was a previously normal/dangerous permission that got moved
12951                 // to a system permission as part of the runtime permission redesign, then
12952                 // we still want to blindly grant it to old apps.
12953                 allowed = true;
12954             }
12955             if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12956                     && pkg.packageName.equals(mRequiredInstallerPackage)) {
12957                 // If this permission is to be granted to the system installer and
12958                 // this app is an installer, then it gets the permission.
12959                 allowed = true;
12960             }
12961             if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12962                     && pkg.packageName.equals(mRequiredVerifierPackage)) {
12963                 // If this permission is to be granted to the system verifier and
12964                 // this app is a verifier, then it gets the permission.
12965                 allowed = true;
12966             }
12967             if (!allowed && (bp.protectionLevel
12968                     & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12969                     && isSystemApp(pkg)) {
12970                 // Any pre-installed system app is allowed to get this permission.
12971                 allowed = true;
12972             }
12973             if (!allowed && (bp.protectionLevel
12974                     & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12975                 // For development permissions, a development permission
12976                 // is granted only if it was already granted.
12977                 allowed = origPermissions.hasInstallPermission(perm);
12978             }
12979             if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12980                     && pkg.packageName.equals(mSetupWizardPackage)) {
12981                 // If this permission is to be granted to the system setup wizard and
12982                 // this app is a setup wizard, then it gets the permission.
12983                 allowed = true;
12984             }
12985         }
12986         return allowed;
12987     }
12988
12989     private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12990         final int permCount = pkg.requestedPermissions.size();
12991         for (int j = 0; j < permCount; j++) {
12992             String requestedPermission = pkg.requestedPermissions.get(j);
12993             if (permission.equals(requestedPermission)) {
12994                 return true;
12995             }
12996         }
12997         return false;
12998     }
12999
13000     final class ActivityIntentResolver
13001             extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13002         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13003                 boolean defaultOnly, int userId) {
13004             if (!sUserManager.exists(userId)) return null;
13005             mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13006             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13007         }
13008
13009         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13010                 int userId) {
13011             if (!sUserManager.exists(userId)) return null;
13012             mFlags = flags;
13013             return super.queryIntent(intent, resolvedType,
13014                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13015                     userId);
13016         }
13017
13018         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13019                 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13020             if (!sUserManager.exists(userId)) return null;
13021             if (packageActivities == null) {
13022                 return null;
13023             }
13024             mFlags = flags;
13025             final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13026             final int N = packageActivities.size();
13027             ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13028                 new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13029
13030             ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13031             for (int i = 0; i < N; ++i) {
13032                 intentFilters = packageActivities.get(i).intents;
13033                 if (intentFilters != null && intentFilters.size() > 0) {
13034                     PackageParser.ActivityIntentInfo[] array =
13035                             new PackageParser.ActivityIntentInfo[intentFilters.size()];
13036                     intentFilters.toArray(array);
13037                     listCut.add(array);
13038                 }
13039             }
13040             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13041         }
13042
13043         /**
13044          * Finds a privileged activity that matches the specified activity names.
13045          */
13046         private PackageParser.Activity findMatchingActivity(
13047                 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13048             for (PackageParser.Activity sysActivity : activityList) {
13049                 if (sysActivity.info.name.equals(activityInfo.name)) {
13050                     return sysActivity;
13051                 }
13052                 if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13053                     return sysActivity;
13054                 }
13055                 if (sysActivity.info.targetActivity != null) {
13056                     if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13057                         return sysActivity;
13058                     }
13059                     if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13060                         return sysActivity;
13061                     }
13062                 }
13063             }
13064             return null;
13065         }
13066
13067         public class IterGenerator<E> {
13068             public Iterator<E> generate(ActivityIntentInfo info) {
13069                 return null;
13070             }
13071         }
13072
13073         public class ActionIterGenerator extends IterGenerator<String> {
13074             @Override
13075             public Iterator<String> generate(ActivityIntentInfo info) {
13076                 return info.actionsIterator();
13077             }
13078         }
13079
13080         public class CategoriesIterGenerator extends IterGenerator<String> {
13081             @Override
13082             public Iterator<String> generate(ActivityIntentInfo info) {
13083                 return info.categoriesIterator();
13084             }
13085         }
13086
13087         public class SchemesIterGenerator extends IterGenerator<String> {
13088             @Override
13089             public Iterator<String> generate(ActivityIntentInfo info) {
13090                 return info.schemesIterator();
13091             }
13092         }
13093
13094         public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13095             @Override
13096             public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13097                 return info.authoritiesIterator();
13098             }
13099         }
13100
13101         /**
13102          * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13103          * MODIFIED. Do not pass in a list that should not be changed.
13104          */
13105         private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13106                 IterGenerator<T> generator, Iterator<T> searchIterator) {
13107             // loop through the set of actions; every one must be found in the intent filter
13108             while (searchIterator.hasNext()) {
13109                 // we must have at least one filter in the list to consider a match
13110                 if (intentList.size() == 0) {
13111                     break;
13112                 }
13113
13114                 final T searchAction = searchIterator.next();
13115
13116                 // loop through the set of intent filters
13117                 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13118                 while (intentIter.hasNext()) {
13119                     final ActivityIntentInfo intentInfo = intentIter.next();
13120                     boolean selectionFound = false;
13121
13122                     // loop through the intent filter's selection criteria; at least one
13123                     // of them must match the searched criteria
13124                     final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13125                     while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13126                         final T intentSelection = intentSelectionIter.next();
13127                         if (intentSelection != null && intentSelection.equals(searchAction)) {
13128                             selectionFound = true;
13129                             break;
13130                         }
13131                     }
13132
13133                     // the selection criteria wasn't found in this filter's set; this filter
13134                     // is not a potential match
13135                     if (!selectionFound) {
13136                         intentIter.remove();
13137                     }
13138                 }
13139             }
13140         }
13141
13142         private boolean isProtectedAction(ActivityIntentInfo filter) {
13143             final Iterator<String> actionsIter = filter.actionsIterator();
13144             while (actionsIter != null && actionsIter.hasNext()) {
13145                 final String filterAction = actionsIter.next();
13146                 if (PROTECTED_ACTIONS.contains(filterAction)) {
13147                     return true;
13148                 }
13149             }
13150             return false;
13151         }
13152
13153         /**
13154          * Adjusts the priority of the given intent filter according to policy.
13155          * <p>
13156          * <ul>
13157          * <li>The priority for non privileged applications is capped to '0'</li>
13158          * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13159          * <li>The priority for unbundled updates to privileged applications is capped to the
13160          *      priority defined on the system partition</li>
13161          * </ul>
13162          * <p>
13163          * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13164          * allowed to obtain any priority on any action.
13165          */
13166         private void adjustPriority(
13167                 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13168             // nothing to do; priority is fine as-is
13169             if (intent.getPriority() <= 0) {
13170                 return;
13171             }
13172
13173             final ActivityInfo activityInfo = intent.activity.info;
13174             final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13175
13176             final boolean privilegedApp =
13177                     ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13178             if (!privilegedApp) {
13179                 // non-privileged applications can never define a priority >0
13180                 if (DEBUG_FILTERS) {
13181                     Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13182                             + " package: " + applicationInfo.packageName
13183                             + " activity: " + intent.activity.className
13184                             + " origPrio: " + intent.getPriority());
13185                 }
13186                 intent.setPriority(0);
13187                 return;
13188             }
13189
13190             if (systemActivities == null) {
13191                 // the system package is not disabled; we're parsing the system partition
13192                 if (isProtectedAction(intent)) {
13193                     if (mDeferProtectedFilters) {
13194                         // We can't deal with these just yet. No component should ever obtain a
13195                         // >0 priority for a protected actions, with ONE exception -- the setup
13196                         // wizard. The setup wizard, however, cannot be known until we're able to
13197                         // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13198                         // until all intent filters have been processed. Chicken, meet egg.
13199                         // Let the filter temporarily have a high priority and rectify the
13200                         // priorities after all system packages have been scanned.
13201                         mProtectedFilters.add(intent);
13202                         if (DEBUG_FILTERS) {
13203                             Slog.i(TAG, "Protected action; save for later;"
13204                                     + " package: " + applicationInfo.packageName
13205                                     + " activity: " + intent.activity.className
13206                                     + " origPrio: " + intent.getPriority());
13207                         }
13208                         return;
13209                     } else {
13210                         if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13211                             Slog.i(TAG, "No setup wizard;"
13212                                 + " All protected intents capped to priority 0");
13213                         }
13214                         if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13215                             if (DEBUG_FILTERS) {
13216                                 Slog.i(TAG, "Found setup wizard;"
13217                                     + " allow priority " + intent.getPriority() + ";"
13218                                     + " package: " + intent.activity.info.packageName
13219                                     + " activity: " + intent.activity.className
13220                                     + " priority: " + intent.getPriority());
13221                             }
13222                             // setup wizard gets whatever it wants
13223                             return;
13224                         }
13225                         if (DEBUG_FILTERS) {
13226                             Slog.i(TAG, "Protected action; cap priority to 0;"
13227                                     + " package: " + intent.activity.info.packageName
13228                                     + " activity: " + intent.activity.className
13229                                     + " origPrio: " + intent.getPriority());
13230                         }
13231                         intent.setPriority(0);
13232                         return;
13233                     }
13234                 }
13235                 // privileged apps on the system image get whatever priority they request
13236                 return;
13237             }
13238
13239             // privileged app unbundled update ... try to find the same activity
13240             final PackageParser.Activity foundActivity =
13241                     findMatchingActivity(systemActivities, activityInfo);
13242             if (foundActivity == null) {
13243                 // this is a new activity; it cannot obtain >0 priority
13244                 if (DEBUG_FILTERS) {
13245                     Slog.i(TAG, "New activity; cap priority to 0;"
13246                             + " package: " + applicationInfo.packageName
13247                             + " activity: " + intent.activity.className
13248                             + " origPrio: " + intent.getPriority());
13249                 }
13250                 intent.setPriority(0);
13251                 return;
13252             }
13253
13254             // found activity, now check for filter equivalence
13255
13256             // a shallow copy is enough; we modify the list, not its contents
13257             final List<ActivityIntentInfo> intentListCopy =
13258                     new ArrayList<>(foundActivity.intents);
13259             final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13260
13261             // find matching action subsets
13262             final Iterator<String> actionsIterator = intent.actionsIterator();
13263             if (actionsIterator != null) {
13264                 getIntentListSubset(
13265                         intentListCopy, new ActionIterGenerator(), actionsIterator);
13266                 if (intentListCopy.size() == 0) {
13267                     // no more intents to match; we're not equivalent
13268                     if (DEBUG_FILTERS) {
13269                         Slog.i(TAG, "Mismatched action; cap priority to 0;"
13270                                 + " package: " + applicationInfo.packageName
13271                                 + " activity: " + intent.activity.className
13272                                 + " origPrio: " + intent.getPriority());
13273                     }
13274                     intent.setPriority(0);
13275                     return;
13276                 }
13277             }
13278
13279             // find matching category subsets
13280             final Iterator<String> categoriesIterator = intent.categoriesIterator();
13281             if (categoriesIterator != null) {
13282                 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13283                         categoriesIterator);
13284                 if (intentListCopy.size() == 0) {
13285                     // no more intents to match; we're not equivalent
13286                     if (DEBUG_FILTERS) {
13287                         Slog.i(TAG, "Mismatched category; cap priority to 0;"
13288                                 + " package: " + applicationInfo.packageName
13289                                 + " activity: " + intent.activity.className
13290                                 + " origPrio: " + intent.getPriority());
13291                     }
13292                     intent.setPriority(0);
13293                     return;
13294                 }
13295             }
13296
13297             // find matching schemes subsets
13298             final Iterator<String> schemesIterator = intent.schemesIterator();
13299             if (schemesIterator != null) {
13300                 getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13301                         schemesIterator);
13302                 if (intentListCopy.size() == 0) {
13303                     // no more intents to match; we're not equivalent
13304                     if (DEBUG_FILTERS) {
13305                         Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13306                                 + " package: " + applicationInfo.packageName
13307                                 + " activity: " + intent.activity.className
13308                                 + " origPrio: " + intent.getPriority());
13309                     }
13310                     intent.setPriority(0);
13311                     return;
13312                 }
13313             }
13314
13315             // find matching authorities subsets
13316             final Iterator<IntentFilter.AuthorityEntry>
13317                     authoritiesIterator = intent.authoritiesIterator();
13318             if (authoritiesIterator != null) {
13319                 getIntentListSubset(intentListCopy,
13320                         new AuthoritiesIterGenerator(),
13321                         authoritiesIterator);
13322                 if (intentListCopy.size() == 0) {
13323                     // no more intents to match; we're not equivalent
13324                     if (DEBUG_FILTERS) {
13325                         Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13326                                 + " package: " + applicationInfo.packageName
13327                                 + " activity: " + intent.activity.className
13328                                 + " origPrio: " + intent.getPriority());
13329                     }
13330                     intent.setPriority(0);
13331                     return;
13332                 }
13333             }
13334
13335             // we found matching filter(s); app gets the max priority of all intents
13336             int cappedPriority = 0;
13337             for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13338                 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13339             }
13340             if (intent.getPriority() > cappedPriority) {
13341                 if (DEBUG_FILTERS) {
13342                     Slog.i(TAG, "Found matching filter(s);"
13343                             + " cap priority to " + cappedPriority + ";"
13344                             + " package: " + applicationInfo.packageName
13345                             + " activity: " + intent.activity.className
13346                             + " origPrio: " + intent.getPriority());
13347                 }
13348                 intent.setPriority(cappedPriority);
13349                 return;
13350             }
13351             // all this for nothing; the requested priority was <= what was on the system
13352         }
13353
13354         public final void addActivity(PackageParser.Activity a, String type) {
13355             mActivities.put(a.getComponentName(), a);
13356             if (DEBUG_SHOW_INFO)
13357                 Log.v(
13358                 TAG, "  " + type + " " +
13359                 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13360             if (DEBUG_SHOW_INFO)
13361                 Log.v(TAG, "    Class=" + a.info.name);
13362             final int NI = a.intents.size();
13363             for (int j=0; j<NI; j++) {
13364                 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13365                 if ("activity".equals(type)) {
13366                     final PackageSetting ps =
13367                             mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13368                     final List<PackageParser.Activity> systemActivities =
13369                             ps != null && ps.pkg != null ? ps.pkg.activities : null;
13370                     adjustPriority(systemActivities, intent);
13371                 }
13372                 if (DEBUG_SHOW_INFO) {
13373                     Log.v(TAG, "    IntentFilter:");
13374                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13375                 }
13376                 if (!intent.debugCheck()) {
13377                     Log.w(TAG, "==> For Activity " + a.info.name);
13378                 }
13379                 addFilter(intent);
13380             }
13381         }
13382
13383         public final void removeActivity(PackageParser.Activity a, String type) {
13384             mActivities.remove(a.getComponentName());
13385             if (DEBUG_SHOW_INFO) {
13386                 Log.v(TAG, "  " + type + " "
13387                         + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13388                                 : a.info.name) + ":");
13389                 Log.v(TAG, "    Class=" + a.info.name);
13390             }
13391             final int NI = a.intents.size();
13392             for (int j=0; j<NI; j++) {
13393                 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13394                 if (DEBUG_SHOW_INFO) {
13395                     Log.v(TAG, "    IntentFilter:");
13396                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13397                 }
13398                 removeFilter(intent);
13399             }
13400         }
13401
13402         @Override
13403         protected boolean allowFilterResult(
13404                 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13405             ActivityInfo filterAi = filter.activity.info;
13406             for (int i=dest.size()-1; i>=0; i--) {
13407                 ActivityInfo destAi = dest.get(i).activityInfo;
13408                 if (destAi.name == filterAi.name
13409                         && destAi.packageName == filterAi.packageName) {
13410                     return false;
13411                 }
13412             }
13413             return true;
13414         }
13415
13416         @Override
13417         protected ActivityIntentInfo[] newArray(int size) {
13418             return new ActivityIntentInfo[size];
13419         }
13420
13421         @Override
13422         protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13423             if (!sUserManager.exists(userId)) return true;
13424             PackageParser.Package p = filter.activity.owner;
13425             if (p != null) {
13426                 PackageSetting ps = (PackageSetting)p.mExtras;
13427                 if (ps != null) {
13428                     // System apps are never considered stopped for purposes of
13429                     // filtering, because there may be no way for the user to
13430                     // actually re-launch them.
13431                     return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13432                             && ps.getStopped(userId);
13433                 }
13434             }
13435             return false;
13436         }
13437
13438         @Override
13439         protected boolean isPackageForFilter(String packageName,
13440                 PackageParser.ActivityIntentInfo info) {
13441             return packageName.equals(info.activity.owner.packageName);
13442         }
13443
13444         @Override
13445         protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13446                 int match, int userId) {
13447             if (!sUserManager.exists(userId)) return null;
13448             if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13449                 return null;
13450             }
13451             final PackageParser.Activity activity = info.activity;
13452             PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13453             if (ps == null) {
13454                 return null;
13455             }
13456             final PackageUserState userState = ps.readUserState(userId);
13457             ActivityInfo ai =
13458                     PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13459             if (ai == null) {
13460                 return null;
13461             }
13462             final boolean matchExplicitlyVisibleOnly =
13463                     (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13464             final boolean matchVisibleToInstantApp =
13465                     (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13466             final boolean componentVisible =
13467                     matchVisibleToInstantApp
13468                     && info.isVisibleToInstantApp()
13469                     && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13470             final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13471             // throw out filters that aren't visible to ephemeral apps
13472             if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13473                 return null;
13474             }
13475             // throw out instant app filters if we're not explicitly requesting them
13476             if (!matchInstantApp && userState.instantApp) {
13477                 return null;
13478             }
13479             // throw out instant app filters if updates are available; will trigger
13480             // instant app resolution
13481             if (userState.instantApp && ps.isUpdateAvailable()) {
13482                 return null;
13483             }
13484             final ResolveInfo res = new ResolveInfo();
13485             res.activityInfo = ai;
13486             if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13487                 res.filter = info;
13488             }
13489             if (info != null) {
13490                 res.handleAllWebDataURI = info.handleAllWebDataURI();
13491             }
13492             res.priority = info.getPriority();
13493             res.preferredOrder = activity.owner.mPreferredOrder;
13494             //System.out.println("Result: " + res.activityInfo.className +
13495             //                   " = " + res.priority);
13496             res.match = match;
13497             res.isDefault = info.hasDefault;
13498             res.labelRes = info.labelRes;
13499             res.nonLocalizedLabel = info.nonLocalizedLabel;
13500             if (userNeedsBadging(userId)) {
13501                 res.noResourceId = true;
13502             } else {
13503                 res.icon = info.icon;
13504             }
13505             res.iconResourceId = info.icon;
13506             res.system = res.activityInfo.applicationInfo.isSystemApp();
13507             res.isInstantAppAvailable = userState.instantApp;
13508             return res;
13509         }
13510
13511         @Override
13512         protected void sortResults(List<ResolveInfo> results) {
13513             Collections.sort(results, mResolvePrioritySorter);
13514         }
13515
13516         @Override
13517         protected void dumpFilter(PrintWriter out, String prefix,
13518                 PackageParser.ActivityIntentInfo filter) {
13519             out.print(prefix); out.print(
13520                     Integer.toHexString(System.identityHashCode(filter.activity)));
13521                     out.print(' ');
13522                     filter.activity.printComponentShortName(out);
13523                     out.print(" filter ");
13524                     out.println(Integer.toHexString(System.identityHashCode(filter)));
13525         }
13526
13527         @Override
13528         protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13529             return filter.activity;
13530         }
13531
13532         protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13533             PackageParser.Activity activity = (PackageParser.Activity)label;
13534             out.print(prefix); out.print(
13535                     Integer.toHexString(System.identityHashCode(activity)));
13536                     out.print(' ');
13537                     activity.printComponentShortName(out);
13538             if (count > 1) {
13539                 out.print(" ("); out.print(count); out.print(" filters)");
13540             }
13541             out.println();
13542         }
13543
13544         // Keys are String (activity class name), values are Activity.
13545         private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13546                 = new ArrayMap<ComponentName, PackageParser.Activity>();
13547         private int mFlags;
13548     }
13549
13550     private final class ServiceIntentResolver
13551             extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13552         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13553                 boolean defaultOnly, int userId) {
13554             mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13555             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13556         }
13557
13558         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13559                 int userId) {
13560             if (!sUserManager.exists(userId)) return null;
13561             mFlags = flags;
13562             return super.queryIntent(intent, resolvedType,
13563                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13564                     userId);
13565         }
13566
13567         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13568                 int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13569             if (!sUserManager.exists(userId)) return null;
13570             if (packageServices == null) {
13571                 return null;
13572             }
13573             mFlags = flags;
13574             final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13575             final int N = packageServices.size();
13576             ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13577                 new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13578
13579             ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13580             for (int i = 0; i < N; ++i) {
13581                 intentFilters = packageServices.get(i).intents;
13582                 if (intentFilters != null && intentFilters.size() > 0) {
13583                     PackageParser.ServiceIntentInfo[] array =
13584                             new PackageParser.ServiceIntentInfo[intentFilters.size()];
13585                     intentFilters.toArray(array);
13586                     listCut.add(array);
13587                 }
13588             }
13589             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13590         }
13591
13592         public final void addService(PackageParser.Service s) {
13593             mServices.put(s.getComponentName(), s);
13594             if (DEBUG_SHOW_INFO) {
13595                 Log.v(TAG, "  "
13596                         + (s.info.nonLocalizedLabel != null
13597                         ? s.info.nonLocalizedLabel : s.info.name) + ":");
13598                 Log.v(TAG, "    Class=" + s.info.name);
13599             }
13600             final int NI = s.intents.size();
13601             int j;
13602             for (j=0; j<NI; j++) {
13603                 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13604                 if (DEBUG_SHOW_INFO) {
13605                     Log.v(TAG, "    IntentFilter:");
13606                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13607                 }
13608                 if (!intent.debugCheck()) {
13609                     Log.w(TAG, "==> For Service " + s.info.name);
13610                 }
13611                 addFilter(intent);
13612             }
13613         }
13614
13615         public final void removeService(PackageParser.Service s) {
13616             mServices.remove(s.getComponentName());
13617             if (DEBUG_SHOW_INFO) {
13618                 Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13619                         ? s.info.nonLocalizedLabel : s.info.name) + ":");
13620                 Log.v(TAG, "    Class=" + s.info.name);
13621             }
13622             final int NI = s.intents.size();
13623             int j;
13624             for (j=0; j<NI; j++) {
13625                 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13626                 if (DEBUG_SHOW_INFO) {
13627                     Log.v(TAG, "    IntentFilter:");
13628                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13629                 }
13630                 removeFilter(intent);
13631             }
13632         }
13633
13634         @Override
13635         protected boolean allowFilterResult(
13636                 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13637             ServiceInfo filterSi = filter.service.info;
13638             for (int i=dest.size()-1; i>=0; i--) {
13639                 ServiceInfo destAi = dest.get(i).serviceInfo;
13640                 if (destAi.name == filterSi.name
13641                         && destAi.packageName == filterSi.packageName) {
13642                     return false;
13643                 }
13644             }
13645             return true;
13646         }
13647
13648         @Override
13649         protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13650             return new PackageParser.ServiceIntentInfo[size];
13651         }
13652
13653         @Override
13654         protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13655             if (!sUserManager.exists(userId)) return true;
13656             PackageParser.Package p = filter.service.owner;
13657             if (p != null) {
13658                 PackageSetting ps = (PackageSetting)p.mExtras;
13659                 if (ps != null) {
13660                     // System apps are never considered stopped for purposes of
13661                     // filtering, because there may be no way for the user to
13662                     // actually re-launch them.
13663                     return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13664                             && ps.getStopped(userId);
13665                 }
13666             }
13667             return false;
13668         }
13669
13670         @Override
13671         protected boolean isPackageForFilter(String packageName,
13672                 PackageParser.ServiceIntentInfo info) {
13673             return packageName.equals(info.service.owner.packageName);
13674         }
13675
13676         @Override
13677         protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13678                 int match, int userId) {
13679             if (!sUserManager.exists(userId)) return null;
13680             final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13681             if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13682                 return null;
13683             }
13684             final PackageParser.Service service = info.service;
13685             PackageSetting ps = (PackageSetting) service.owner.mExtras;
13686             if (ps == null) {
13687                 return null;
13688             }
13689             final PackageUserState userState = ps.readUserState(userId);
13690             ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13691                     userState, userId);
13692             if (si == null) {
13693                 return null;
13694             }
13695             final boolean matchVisibleToInstantApp =
13696                     (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13697             final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13698             // throw out filters that aren't visible to ephemeral apps
13699             if (matchVisibleToInstantApp
13700                     && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13701                 return null;
13702             }
13703             // throw out ephemeral filters if we're not explicitly requesting them
13704             if (!isInstantApp && userState.instantApp) {
13705                 return null;
13706             }
13707             // throw out instant app filters if updates are available; will trigger
13708             // instant app resolution
13709             if (userState.instantApp && ps.isUpdateAvailable()) {
13710                 return null;
13711             }
13712             final ResolveInfo res = new ResolveInfo();
13713             res.serviceInfo = si;
13714             if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13715                 res.filter = filter;
13716             }
13717             res.priority = info.getPriority();
13718             res.preferredOrder = service.owner.mPreferredOrder;
13719             res.match = match;
13720             res.isDefault = info.hasDefault;
13721             res.labelRes = info.labelRes;
13722             res.nonLocalizedLabel = info.nonLocalizedLabel;
13723             res.icon = info.icon;
13724             res.system = res.serviceInfo.applicationInfo.isSystemApp();
13725             return res;
13726         }
13727
13728         @Override
13729         protected void sortResults(List<ResolveInfo> results) {
13730             Collections.sort(results, mResolvePrioritySorter);
13731         }
13732
13733         @Override
13734         protected void dumpFilter(PrintWriter out, String prefix,
13735                 PackageParser.ServiceIntentInfo filter) {
13736             out.print(prefix); out.print(
13737                     Integer.toHexString(System.identityHashCode(filter.service)));
13738                     out.print(' ');
13739                     filter.service.printComponentShortName(out);
13740                     out.print(" filter ");
13741                     out.println(Integer.toHexString(System.identityHashCode(filter)));
13742         }
13743
13744         @Override
13745         protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13746             return filter.service;
13747         }
13748
13749         protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13750             PackageParser.Service service = (PackageParser.Service)label;
13751             out.print(prefix); out.print(
13752                     Integer.toHexString(System.identityHashCode(service)));
13753                     out.print(' ');
13754                     service.printComponentShortName(out);
13755             if (count > 1) {
13756                 out.print(" ("); out.print(count); out.print(" filters)");
13757             }
13758             out.println();
13759         }
13760
13761 //        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13762 //            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13763 //            final List<ResolveInfo> retList = Lists.newArrayList();
13764 //            while (i.hasNext()) {
13765 //                final ResolveInfo resolveInfo = (ResolveInfo) i;
13766 //                if (isEnabledLP(resolveInfo.serviceInfo)) {
13767 //                    retList.add(resolveInfo);
13768 //                }
13769 //            }
13770 //            return retList;
13771 //        }
13772
13773         // Keys are String (activity class name), values are Activity.
13774         private final ArrayMap<ComponentName, PackageParser.Service> mServices
13775                 = new ArrayMap<ComponentName, PackageParser.Service>();
13776         private int mFlags;
13777     }
13778
13779     private final class ProviderIntentResolver
13780             extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13781         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13782                 boolean defaultOnly, int userId) {
13783             mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13784             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13785         }
13786
13787         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13788                 int userId) {
13789             if (!sUserManager.exists(userId))
13790                 return null;
13791             mFlags = flags;
13792             return super.queryIntent(intent, resolvedType,
13793                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13794                     userId);
13795         }
13796
13797         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13798                 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13799             if (!sUserManager.exists(userId))
13800                 return null;
13801             if (packageProviders == null) {
13802                 return null;
13803             }
13804             mFlags = flags;
13805             final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13806             final int N = packageProviders.size();
13807             ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13808                     new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13809
13810             ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13811             for (int i = 0; i < N; ++i) {
13812                 intentFilters = packageProviders.get(i).intents;
13813                 if (intentFilters != null && intentFilters.size() > 0) {
13814                     PackageParser.ProviderIntentInfo[] array =
13815                             new PackageParser.ProviderIntentInfo[intentFilters.size()];
13816                     intentFilters.toArray(array);
13817                     listCut.add(array);
13818                 }
13819             }
13820             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13821         }
13822
13823         public final void addProvider(PackageParser.Provider p) {
13824             if (mProviders.containsKey(p.getComponentName())) {
13825                 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13826                 return;
13827             }
13828
13829             mProviders.put(p.getComponentName(), p);
13830             if (DEBUG_SHOW_INFO) {
13831                 Log.v(TAG, "  "
13832                         + (p.info.nonLocalizedLabel != null
13833                                 ? p.info.nonLocalizedLabel : p.info.name) + ":");
13834                 Log.v(TAG, "    Class=" + p.info.name);
13835             }
13836             final int NI = p.intents.size();
13837             int j;
13838             for (j = 0; j < NI; j++) {
13839                 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13840                 if (DEBUG_SHOW_INFO) {
13841                     Log.v(TAG, "    IntentFilter:");
13842                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13843                 }
13844                 if (!intent.debugCheck()) {
13845                     Log.w(TAG, "==> For Provider " + p.info.name);
13846                 }
13847                 addFilter(intent);
13848             }
13849         }
13850
13851         public final void removeProvider(PackageParser.Provider p) {
13852             mProviders.remove(p.getComponentName());
13853             if (DEBUG_SHOW_INFO) {
13854                 Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13855                         ? p.info.nonLocalizedLabel : p.info.name) + ":");
13856                 Log.v(TAG, "    Class=" + p.info.name);
13857             }
13858             final int NI = p.intents.size();
13859             int j;
13860             for (j = 0; j < NI; j++) {
13861                 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13862                 if (DEBUG_SHOW_INFO) {
13863                     Log.v(TAG, "    IntentFilter:");
13864                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13865                 }
13866                 removeFilter(intent);
13867             }
13868         }
13869
13870         @Override
13871         protected boolean allowFilterResult(
13872                 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13873             ProviderInfo filterPi = filter.provider.info;
13874             for (int i = dest.size() - 1; i >= 0; i--) {
13875                 ProviderInfo destPi = dest.get(i).providerInfo;
13876                 if (destPi.name == filterPi.name
13877                         && destPi.packageName == filterPi.packageName) {
13878                     return false;
13879                 }
13880             }
13881             return true;
13882         }
13883
13884         @Override
13885         protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13886             return new PackageParser.ProviderIntentInfo[size];
13887         }
13888
13889         @Override
13890         protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13891             if (!sUserManager.exists(userId))
13892                 return true;
13893             PackageParser.Package p = filter.provider.owner;
13894             if (p != null) {
13895                 PackageSetting ps = (PackageSetting) p.mExtras;
13896                 if (ps != null) {
13897                     // System apps are never considered stopped for purposes of
13898                     // filtering, because there may be no way for the user to
13899                     // actually re-launch them.
13900                     return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13901                             && ps.getStopped(userId);
13902                 }
13903             }
13904             return false;
13905         }
13906
13907         @Override
13908         protected boolean isPackageForFilter(String packageName,
13909                 PackageParser.ProviderIntentInfo info) {
13910             return packageName.equals(info.provider.owner.packageName);
13911         }
13912
13913         @Override
13914         protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13915                 int match, int userId) {
13916             if (!sUserManager.exists(userId))
13917                 return null;
13918             final PackageParser.ProviderIntentInfo info = filter;
13919             if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13920                 return null;
13921             }
13922             final PackageParser.Provider provider = info.provider;
13923             PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13924             if (ps == null) {
13925                 return null;
13926             }
13927             final PackageUserState userState = ps.readUserState(userId);
13928             final boolean matchVisibleToInstantApp =
13929                     (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13930             final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13931             // throw out filters that aren't visible to instant applications
13932             if (matchVisibleToInstantApp
13933                     && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13934                 return null;
13935             }
13936             // throw out instant application filters if we're not explicitly requesting them
13937             if (!isInstantApp && userState.instantApp) {
13938                 return null;
13939             }
13940             // throw out instant application filters if updates are available; will trigger
13941             // instant application resolution
13942             if (userState.instantApp && ps.isUpdateAvailable()) {
13943                 return null;
13944             }
13945             ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13946                     userState, userId);
13947             if (pi == null) {
13948                 return null;
13949             }
13950             final ResolveInfo res = new ResolveInfo();
13951             res.providerInfo = pi;
13952             if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13953                 res.filter = filter;
13954             }
13955             res.priority = info.getPriority();
13956             res.preferredOrder = provider.owner.mPreferredOrder;
13957             res.match = match;
13958             res.isDefault = info.hasDefault;
13959             res.labelRes = info.labelRes;
13960             res.nonLocalizedLabel = info.nonLocalizedLabel;
13961             res.icon = info.icon;
13962             res.system = res.providerInfo.applicationInfo.isSystemApp();
13963             return res;
13964         }
13965
13966         @Override
13967         protected void sortResults(List<ResolveInfo> results) {
13968             Collections.sort(results, mResolvePrioritySorter);
13969         }
13970
13971         @Override
13972         protected void dumpFilter(PrintWriter out, String prefix,
13973                 PackageParser.ProviderIntentInfo filter) {
13974             out.print(prefix);
13975             out.print(
13976                     Integer.toHexString(System.identityHashCode(filter.provider)));
13977             out.print(' ');
13978             filter.provider.printComponentShortName(out);
13979             out.print(" filter ");
13980             out.println(Integer.toHexString(System.identityHashCode(filter)));
13981         }
13982
13983         @Override
13984         protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13985             return filter.provider;
13986         }
13987
13988         protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13989             PackageParser.Provider provider = (PackageParser.Provider)label;
13990             out.print(prefix); out.print(
13991                     Integer.toHexString(System.identityHashCode(provider)));
13992                     out.print(' ');
13993                     provider.printComponentShortName(out);
13994             if (count > 1) {
13995                 out.print(" ("); out.print(count); out.print(" filters)");
13996             }
13997             out.println();
13998         }
13999
14000         private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14001                 = new ArrayMap<ComponentName, PackageParser.Provider>();
14002         private int mFlags;
14003     }
14004
14005     static final class EphemeralIntentResolver
14006             extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14007         /**
14008          * The result that has the highest defined order. Ordering applies on a
14009          * per-package basis. Mapping is from package name to Pair of order and
14010          * EphemeralResolveInfo.
14011          * <p>
14012          * NOTE: This is implemented as a field variable for convenience and efficiency.
14013          * By having a field variable, we're able to track filter ordering as soon as
14014          * a non-zero order is defined. Otherwise, multiple loops across the result set
14015          * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14016          * this needs to be contained entirely within {@link #filterResults}.
14017          */
14018         final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14019
14020         @Override
14021         protected AuxiliaryResolveInfo[] newArray(int size) {
14022             return new AuxiliaryResolveInfo[size];
14023         }
14024
14025         @Override
14026         protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14027             return true;
14028         }
14029
14030         @Override
14031         protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14032                 int userId) {
14033             if (!sUserManager.exists(userId)) {
14034                 return null;
14035             }
14036             final String packageName = responseObj.resolveInfo.getPackageName();
14037             final Integer order = responseObj.getOrder();
14038             final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14039                     mOrderResult.get(packageName);
14040             // ordering is enabled and this item's order isn't high enough
14041             if (lastOrderResult != null && lastOrderResult.first >= order) {
14042                 return null;
14043             }
14044             final InstantAppResolveInfo res = responseObj.resolveInfo;
14045             if (order > 0) {
14046                 // non-zero order, enable ordering
14047                 mOrderResult.put(packageName, new Pair<>(order, res));
14048             }
14049             return responseObj;
14050         }
14051
14052         @Override
14053         protected void filterResults(List<AuxiliaryResolveInfo> results) {
14054             // only do work if ordering is enabled [most of the time it won't be]
14055             if (mOrderResult.size() == 0) {
14056                 return;
14057             }
14058             int resultSize = results.size();
14059             for (int i = 0; i < resultSize; i++) {
14060                 final InstantAppResolveInfo info = results.get(i).resolveInfo;
14061                 final String packageName = info.getPackageName();
14062                 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14063                 if (savedInfo == null) {
14064                     // package doesn't having ordering
14065                     continue;
14066                 }
14067                 if (savedInfo.second == info) {
14068                     // circled back to the highest ordered item; remove from order list
14069                     mOrderResult.remove(savedInfo);
14070                     if (mOrderResult.size() == 0) {
14071                         // no more ordered items
14072                         break;
14073                     }
14074                     continue;
14075                 }
14076                 // item has a worse order, remove it from the result list
14077                 results.remove(i);
14078                 resultSize--;
14079                 i--;
14080             }
14081         }
14082     }
14083
14084     private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14085             new Comparator<ResolveInfo>() {
14086         public int compare(ResolveInfo r1, ResolveInfo r2) {
14087             int v1 = r1.priority;
14088             int v2 = r2.priority;
14089             //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14090             if (v1 != v2) {
14091                 return (v1 > v2) ? -1 : 1;
14092             }
14093             v1 = r1.preferredOrder;
14094             v2 = r2.preferredOrder;
14095             if (v1 != v2) {
14096                 return (v1 > v2) ? -1 : 1;
14097             }
14098             if (r1.isDefault != r2.isDefault) {
14099                 return r1.isDefault ? -1 : 1;
14100             }
14101             v1 = r1.match;
14102             v2 = r2.match;
14103             //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14104             if (v1 != v2) {
14105                 return (v1 > v2) ? -1 : 1;
14106             }
14107             if (r1.system != r2.system) {
14108                 return r1.system ? -1 : 1;
14109             }
14110             if (r1.activityInfo != null) {
14111                 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14112             }
14113             if (r1.serviceInfo != null) {
14114                 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14115             }
14116             if (r1.providerInfo != null) {
14117                 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14118             }
14119             return 0;
14120         }
14121     };
14122
14123     private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14124             new Comparator<ProviderInfo>() {
14125         public int compare(ProviderInfo p1, ProviderInfo p2) {
14126             final int v1 = p1.initOrder;
14127             final int v2 = p2.initOrder;
14128             return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14129         }
14130     };
14131
14132     public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14133             final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14134             final int[] userIds) {
14135         mHandler.post(new Runnable() {
14136             @Override
14137             public void run() {
14138                 try {
14139                     final IActivityManager am = ActivityManager.getService();
14140                     if (am == null) return;
14141                     final int[] resolvedUserIds;
14142                     if (userIds == null) {
14143                         resolvedUserIds = am.getRunningUserIds();
14144                     } else {
14145                         resolvedUserIds = userIds;
14146                     }
14147                     for (int id : resolvedUserIds) {
14148                         final Intent intent = new Intent(action,
14149                                 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14150                         if (extras != null) {
14151                             intent.putExtras(extras);
14152                         }
14153                         if (targetPkg != null) {
14154                             intent.setPackage(targetPkg);
14155                         }
14156                         // Modify the UID when posting to other users
14157                         int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14158                         if (uid > 0 && UserHandle.getUserId(uid) != id) {
14159                             uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14160                             intent.putExtra(Intent.EXTRA_UID, uid);
14161                         }
14162                         intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14163                         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14164                         if (DEBUG_BROADCASTS) {
14165                             RuntimeException here = new RuntimeException("here");
14166                             here.fillInStackTrace();
14167                             Slog.d(TAG, "Sending to user " + id + ": "
14168                                     + intent.toShortString(false, true, false, false)
14169                                     + " " + intent.getExtras(), here);
14170                         }
14171                         am.broadcastIntent(null, intent, null, finishedReceiver,
14172                                 0, null, null, null, android.app.AppOpsManager.OP_NONE,
14173                                 null, finishedReceiver != null, false, id);
14174                     }
14175                 } catch (RemoteException ex) {
14176                 }
14177             }
14178         });
14179     }
14180
14181     /**
14182      * Check if the external storage media is available. This is true if there
14183      * is a mounted external storage medium or if the external storage is
14184      * emulated.
14185      */
14186     private boolean isExternalMediaAvailable() {
14187         return mMediaMounted || Environment.isExternalStorageEmulated();
14188     }
14189
14190     @Override
14191     public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14192         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14193             return null;
14194         }
14195         // writer
14196         synchronized (mPackages) {
14197             if (!isExternalMediaAvailable()) {
14198                 // If the external storage is no longer mounted at this point,
14199                 // the caller may not have been able to delete all of this
14200                 // packages files and can not delete any more.  Bail.
14201                 return null;
14202             }
14203             final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14204             if (lastPackage != null) {
14205                 pkgs.remove(lastPackage);
14206             }
14207             if (pkgs.size() > 0) {
14208                 return pkgs.get(0);
14209             }
14210         }
14211         return null;
14212     }
14213
14214     void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14215         final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14216                 userId, andCode ? 1 : 0, packageName);
14217         if (mSystemReady) {
14218             msg.sendToTarget();
14219         } else {
14220             if (mPostSystemReadyMessages == null) {
14221                 mPostSystemReadyMessages = new ArrayList<>();
14222             }
14223             mPostSystemReadyMessages.add(msg);
14224         }
14225     }
14226
14227     void startCleaningPackages() {
14228         // reader
14229         if (!isExternalMediaAvailable()) {
14230             return;
14231         }
14232         synchronized (mPackages) {
14233             if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14234                 return;
14235             }
14236         }
14237         Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14238         intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14239         IActivityManager am = ActivityManager.getService();
14240         if (am != null) {
14241             int dcsUid = -1;
14242             synchronized (mPackages) {
14243                 if (!mDefaultContainerWhitelisted) {
14244                     mDefaultContainerWhitelisted = true;
14245                     PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14246                     dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14247                 }
14248             }
14249             try {
14250                 if (dcsUid > 0) {
14251                     am.backgroundWhitelistUid(dcsUid);
14252                 }
14253                 am.startService(null, intent, null, false, mContext.getOpPackageName(),
14254                         UserHandle.USER_SYSTEM);
14255             } catch (RemoteException e) {
14256             }
14257         }
14258     }
14259
14260     @Override
14261     public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14262             int installFlags, String installerPackageName, int userId) {
14263         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14264
14265         final int callingUid = Binder.getCallingUid();
14266         enforceCrossUserPermission(callingUid, userId,
14267                 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14268
14269         if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14270             try {
14271                 if (observer != null) {
14272                     observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14273                 }
14274             } catch (RemoteException re) {
14275             }
14276             return;
14277         }
14278
14279         if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14280             installFlags |= PackageManager.INSTALL_FROM_ADB;
14281
14282         } else {
14283             // Caller holds INSTALL_PACKAGES permission, so we're less strict
14284             // about installerPackageName.
14285
14286             installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14287             installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14288         }
14289
14290         UserHandle user;
14291         if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14292             user = UserHandle.ALL;
14293         } else {
14294             user = new UserHandle(userId);
14295         }
14296
14297         // Only system components can circumvent runtime permissions when installing.
14298         if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14299                 && mContext.checkCallingOrSelfPermission(Manifest.permission
14300                 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14301             throw new SecurityException("You need the "
14302                     + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14303                     + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14304         }
14305
14306         if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14307                 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14308             throw new IllegalArgumentException(
14309                     "New installs into ASEC containers no longer supported");
14310         }
14311
14312         final File originFile = new File(originPath);
14313         final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14314
14315         final Message msg = mHandler.obtainMessage(INIT_COPY);
14316         final VerificationInfo verificationInfo = new VerificationInfo(
14317                 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14318         final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14319                 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14320                 null /*packageAbiOverride*/, null /*grantedPermissions*/,
14321                 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14322         params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14323         msg.obj = params;
14324
14325         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14326                 System.identityHashCode(msg.obj));
14327         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14328                 System.identityHashCode(msg.obj));
14329
14330         mHandler.sendMessage(msg);
14331     }
14332
14333
14334     /**
14335      * Ensure that the install reason matches what we know about the package installer (e.g. whether
14336      * it is acting on behalf on an enterprise or the user).
14337      *
14338      * Note that the ordering of the conditionals in this method is important. The checks we perform
14339      * are as follows, in this order:
14340      *
14341      * 1) If the install is being performed by a system app, we can trust the app to have set the
14342      *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14343      *    what it is.
14344      * 2) If the install is being performed by a device or profile owner app, the install reason
14345      *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14346      *    set the install reason correctly. If the app targets an older SDK version where install
14347      *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14348      *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14349      * 3) In all other cases, the install is being performed by a regular app that is neither part
14350      *    of the system nor a device or profile owner. We have no reason to believe that this app is
14351      *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14352      *    set to enterprise policy and if so, change it to unknown instead.
14353      */
14354     private int fixUpInstallReason(String installerPackageName, int installerUid,
14355             int installReason) {
14356         if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14357                 == PERMISSION_GRANTED) {
14358             // If the install is being performed by a system app, we trust that app to have set the
14359             // install reason correctly.
14360             return installReason;
14361         }
14362
14363         final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14364             ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14365         if (dpm != null) {
14366             ComponentName owner = null;
14367             try {
14368                 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14369                 if (owner == null) {
14370                     owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14371                 }
14372             } catch (RemoteException e) {
14373             }
14374             if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14375                 // If the install is being performed by a device or profile owner, the install
14376                 // reason should be enterprise policy.
14377                 return PackageManager.INSTALL_REASON_POLICY;
14378             }
14379         }
14380
14381         if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14382             // If the install is being performed by a regular app (i.e. neither system app nor
14383             // device or profile owner), we have no reason to believe that the app is acting on
14384             // behalf of an enterprise. If the app set the install reason to enterprise policy,
14385             // change it to unknown instead.
14386             return PackageManager.INSTALL_REASON_UNKNOWN;
14387         }
14388
14389         // If the install is being performed by a regular app and the install reason was set to any
14390         // value but enterprise policy, leave the install reason unchanged.
14391         return installReason;
14392     }
14393
14394     void installStage(String packageName, File stagedDir, String stagedCid,
14395             IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14396             String installerPackageName, int installerUid, UserHandle user,
14397             Certificate[][] certificates) {
14398         if (DEBUG_EPHEMERAL) {
14399             if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14400                 Slog.d(TAG, "Ephemeral install of " + packageName);
14401             }
14402         }
14403         final VerificationInfo verificationInfo = new VerificationInfo(
14404                 sessionParams.originatingUri, sessionParams.referrerUri,
14405                 sessionParams.originatingUid, installerUid);
14406
14407         final OriginInfo origin;
14408         if (stagedDir != null) {
14409             origin = OriginInfo.fromStagedFile(stagedDir);
14410         } else {
14411             origin = OriginInfo.fromStagedContainer(stagedCid);
14412         }
14413
14414         final Message msg = mHandler.obtainMessage(INIT_COPY);
14415         final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14416                 sessionParams.installReason);
14417         final InstallParams params = new InstallParams(origin, null, observer,
14418                 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14419                 verificationInfo, user, sessionParams.abiOverride,
14420                 sessionParams.grantedRuntimePermissions, certificates, installReason);
14421         params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14422         msg.obj = params;
14423
14424         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14425                 System.identityHashCode(msg.obj));
14426         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14427                 System.identityHashCode(msg.obj));
14428
14429         mHandler.sendMessage(msg);
14430     }
14431
14432     private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14433             int userId) {
14434         final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14435         sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14436
14437         // Send a session commit broadcast
14438         final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14439         info.installReason = pkgSetting.getInstallReason(userId);
14440         info.appPackageName = packageName;
14441         sendSessionCommitBroadcast(info, userId);
14442     }
14443
14444     public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14445         if (ArrayUtils.isEmpty(userIds)) {
14446             return;
14447         }
14448         Bundle extras = new Bundle(1);
14449         // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14450         extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14451
14452         sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14453                 packageName, extras, 0, null, null, userIds);
14454         if (isSystem) {
14455             mHandler.post(() -> {
14456                         for (int userId : userIds) {
14457                             sendBootCompletedBroadcastToSystemApp(packageName, userId);
14458                         }
14459                     }
14460             );
14461         }
14462     }
14463
14464     /**
14465      * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14466      * automatically without needing an explicit launch.
14467      * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14468      */
14469     private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14470         // If user is not running, the app didn't miss any broadcast
14471         if (!mUserManagerInternal.isUserRunning(userId)) {
14472             return;
14473         }
14474         final IActivityManager am = ActivityManager.getService();
14475         try {
14476             // Deliver LOCKED_BOOT_COMPLETED first
14477             Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14478                     .setPackage(packageName);
14479             final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14480             am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14481                     android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14482
14483             // Deliver BOOT_COMPLETED only if user is unlocked
14484             if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14485                 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14486                 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14487                         android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14488             }
14489         } catch (RemoteException e) {
14490             throw e.rethrowFromSystemServer();
14491         }
14492     }
14493
14494     @Override
14495     public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14496             int userId) {
14497         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14498         PackageSetting pkgSetting;
14499         final int callingUid = Binder.getCallingUid();
14500         enforceCrossUserPermission(callingUid, userId,
14501                 true /* requireFullPermission */, true /* checkShell */,
14502                 "setApplicationHiddenSetting for user " + userId);
14503
14504         if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14505             Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14506             return false;
14507         }
14508
14509         long callingId = Binder.clearCallingIdentity();
14510         try {
14511             boolean sendAdded = false;
14512             boolean sendRemoved = false;
14513             // writer
14514             synchronized (mPackages) {
14515                 pkgSetting = mSettings.mPackages.get(packageName);
14516                 if (pkgSetting == null) {
14517                     return false;
14518                 }
14519                 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14520                     return false;
14521                 }
14522                 // Do not allow "android" is being disabled
14523                 if ("android".equals(packageName)) {
14524                     Slog.w(TAG, "Cannot hide package: android");
14525                     return false;
14526                 }
14527                 // Cannot hide static shared libs as they are considered
14528                 // a part of the using app (emulating static linking). Also
14529                 // static libs are installed always on internal storage.
14530                 PackageParser.Package pkg = mPackages.get(packageName);
14531                 if (pkg != null && pkg.staticSharedLibName != null) {
14532                     Slog.w(TAG, "Cannot hide package: " + packageName
14533                             + " providing static shared library: "
14534                             + pkg.staticSharedLibName);
14535                     return false;
14536                 }
14537                 // Only allow protected packages to hide themselves.
14538                 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14539                         && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14540                     Slog.w(TAG, "Not hiding protected package: " + packageName);
14541                     return false;
14542                 }
14543
14544                 if (pkgSetting.getHidden(userId) != hidden) {
14545                     pkgSetting.setHidden(hidden, userId);
14546                     mSettings.writePackageRestrictionsLPr(userId);
14547                     if (hidden) {
14548                         sendRemoved = true;
14549                     } else {
14550                         sendAdded = true;
14551                     }
14552                 }
14553             }
14554             if (sendAdded) {
14555                 sendPackageAddedForUser(packageName, pkgSetting, userId);
14556                 return true;
14557             }
14558             if (sendRemoved) {
14559                 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14560                         "hiding pkg");
14561                 sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14562                 return true;
14563             }
14564         } finally {
14565             Binder.restoreCallingIdentity(callingId);
14566         }
14567         return false;
14568     }
14569
14570     private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14571             int userId) {
14572         final PackageRemovedInfo info = new PackageRemovedInfo(this);
14573         info.removedPackage = packageName;
14574         info.installerPackageName = pkgSetting.installerPackageName;
14575         info.removedUsers = new int[] {userId};
14576         info.broadcastUsers = new int[] {userId};
14577         info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14578         info.sendPackageRemovedBroadcasts(true /*killApp*/);
14579     }
14580
14581     private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14582         if (pkgList.length > 0) {
14583             Bundle extras = new Bundle(1);
14584             extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14585
14586             sendPackageBroadcast(
14587                     suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14588                             : Intent.ACTION_PACKAGES_UNSUSPENDED,
14589                     null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14590                     new int[] {userId});
14591         }
14592     }
14593
14594     /**
14595      * Returns true if application is not found or there was an error. Otherwise it returns
14596      * the hidden state of the package for the given user.
14597      */
14598     @Override
14599     public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14600         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14601         final int callingUid = Binder.getCallingUid();
14602         enforceCrossUserPermission(callingUid, userId,
14603                 true /* requireFullPermission */, false /* checkShell */,
14604                 "getApplicationHidden for user " + userId);
14605         PackageSetting ps;
14606         long callingId = Binder.clearCallingIdentity();
14607         try {
14608             // writer
14609             synchronized (mPackages) {
14610                 ps = mSettings.mPackages.get(packageName);
14611                 if (ps == null) {
14612                     return true;
14613                 }
14614                 if (filterAppAccessLPr(ps, callingUid, userId)) {
14615                     return true;
14616                 }
14617                 return ps.getHidden(userId);
14618             }
14619         } finally {
14620             Binder.restoreCallingIdentity(callingId);
14621         }
14622     }
14623
14624     /**
14625      * @hide
14626      */
14627     @Override
14628     public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14629             int installReason) {
14630         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14631                 null);
14632         PackageSetting pkgSetting;
14633         final int callingUid = Binder.getCallingUid();
14634         enforceCrossUserPermission(callingUid, userId,
14635                 true /* requireFullPermission */, true /* checkShell */,
14636                 "installExistingPackage for user " + userId);
14637         if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14638             return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14639         }
14640
14641         long callingId = Binder.clearCallingIdentity();
14642         try {
14643             boolean installed = false;
14644             final boolean instantApp =
14645                     (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14646             final boolean fullApp =
14647                     (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14648
14649             // writer
14650             synchronized (mPackages) {
14651                 pkgSetting = mSettings.mPackages.get(packageName);
14652                 if (pkgSetting == null) {
14653                     return PackageManager.INSTALL_FAILED_INVALID_URI;
14654                 }
14655                 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14656                     // only allow the existing package to be used if it's installed as a full
14657                     // application for at least one user
14658                     boolean installAllowed = false;
14659                     for (int checkUserId : sUserManager.getUserIds()) {
14660                         installAllowed = !pkgSetting.getInstantApp(checkUserId);
14661                         if (installAllowed) {
14662                             break;
14663                         }
14664                     }
14665                     if (!installAllowed) {
14666                         return PackageManager.INSTALL_FAILED_INVALID_URI;
14667                     }
14668                 }
14669                 if (!pkgSetting.getInstalled(userId)) {
14670                     pkgSetting.setInstalled(true, userId);
14671                     pkgSetting.setHidden(false, userId);
14672                     pkgSetting.setInstallReason(installReason, userId);
14673                     mSettings.writePackageRestrictionsLPr(userId);
14674                     mSettings.writeKernelMappingLPr(pkgSetting);
14675                     installed = true;
14676                 } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14677                     // upgrade app from instant to full; we don't allow app downgrade
14678                     installed = true;
14679                 }
14680                 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14681             }
14682
14683             if (installed) {
14684                 if (pkgSetting.pkg != null) {
14685                     synchronized (mInstallLock) {
14686                         // We don't need to freeze for a brand new install
14687                         prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14688                     }
14689                 }
14690                 sendPackageAddedForUser(packageName, pkgSetting, userId);
14691                 synchronized (mPackages) {
14692                     updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14693                 }
14694             }
14695         } finally {
14696             Binder.restoreCallingIdentity(callingId);
14697         }
14698
14699         return PackageManager.INSTALL_SUCCEEDED;
14700     }
14701
14702     void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14703             boolean instantApp, boolean fullApp) {
14704         // no state specified; do nothing
14705         if (!instantApp && !fullApp) {
14706             return;
14707         }
14708         if (userId != UserHandle.USER_ALL) {
14709             if (instantApp && !pkgSetting.getInstantApp(userId)) {
14710                 pkgSetting.setInstantApp(true /*instantApp*/, userId);
14711             } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14712                 pkgSetting.setInstantApp(false /*instantApp*/, userId);
14713             }
14714         } else {
14715             for (int currentUserId : sUserManager.getUserIds()) {
14716                 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14717                     pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14718                 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14719                     pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14720                 }
14721             }
14722         }
14723     }
14724
14725     boolean isUserRestricted(int userId, String restrictionKey) {
14726         Bundle restrictions = sUserManager.getUserRestrictions(userId);
14727         if (restrictions.getBoolean(restrictionKey, false)) {
14728             Log.w(TAG, "User is restricted: " + restrictionKey);
14729             return true;
14730         }
14731         return false;
14732     }
14733
14734     @Override
14735     public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14736             int userId) {
14737         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14738         final int callingUid = Binder.getCallingUid();
14739         enforceCrossUserPermission(callingUid, userId,
14740                 true /* requireFullPermission */, true /* checkShell */,
14741                 "setPackagesSuspended for user " + userId);
14742
14743         if (ArrayUtils.isEmpty(packageNames)) {
14744             return packageNames;
14745         }
14746
14747         // List of package names for whom the suspended state has changed.
14748         List<String> changedPackages = new ArrayList<>(packageNames.length);
14749         // List of package names for whom the suspended state is not set as requested in this
14750         // method.
14751         List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14752         long callingId = Binder.clearCallingIdentity();
14753         try {
14754             for (int i = 0; i < packageNames.length; i++) {
14755                 String packageName = packageNames[i];
14756                 boolean changed = false;
14757                 final int appId;
14758                 synchronized (mPackages) {
14759                     final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14760                     if (pkgSetting == null
14761                             || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14762                         Slog.w(TAG, "Could not find package setting for package \"" + packageName
14763                                 + "\". Skipping suspending/un-suspending.");
14764                         unactionedPackages.add(packageName);
14765                         continue;
14766                     }
14767                     appId = pkgSetting.appId;
14768                     if (pkgSetting.getSuspended(userId) != suspended) {
14769                         if (!canSuspendPackageForUserLocked(packageName, userId)) {
14770                             unactionedPackages.add(packageName);
14771                             continue;
14772                         }
14773                         pkgSetting.setSuspended(suspended, userId);
14774                         mSettings.writePackageRestrictionsLPr(userId);
14775                         changed = true;
14776                         changedPackages.add(packageName);
14777                     }
14778                 }
14779
14780                 if (changed && suspended) {
14781                     killApplication(packageName, UserHandle.getUid(userId, appId),
14782                             "suspending package");
14783                 }
14784             }
14785         } finally {
14786             Binder.restoreCallingIdentity(callingId);
14787         }
14788
14789         if (!changedPackages.isEmpty()) {
14790             sendPackagesSuspendedForUser(changedPackages.toArray(
14791                     new String[changedPackages.size()]), userId, suspended);
14792         }
14793
14794         return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14795     }
14796
14797     @Override
14798     public boolean isPackageSuspendedForUser(String packageName, int userId) {
14799         final int callingUid = Binder.getCallingUid();
14800         enforceCrossUserPermission(callingUid, userId,
14801                 true /* requireFullPermission */, false /* checkShell */,
14802                 "isPackageSuspendedForUser for user " + userId);
14803         synchronized (mPackages) {
14804             final PackageSetting ps = mSettings.mPackages.get(packageName);
14805             if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14806                 throw new IllegalArgumentException("Unknown target package: " + packageName);
14807             }
14808             return ps.getSuspended(userId);
14809         }
14810     }
14811
14812     private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14813         if (isPackageDeviceAdmin(packageName, userId)) {
14814             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14815                     + "\": has an active device admin");
14816             return false;
14817         }
14818
14819         String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14820         if (packageName.equals(activeLauncherPackageName)) {
14821             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14822                     + "\": contains the active launcher");
14823             return false;
14824         }
14825
14826         if (packageName.equals(mRequiredInstallerPackage)) {
14827             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14828                     + "\": required for package installation");
14829             return false;
14830         }
14831
14832         if (packageName.equals(mRequiredUninstallerPackage)) {
14833             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14834                     + "\": required for package uninstallation");
14835             return false;
14836         }
14837
14838         if (packageName.equals(mRequiredVerifierPackage)) {
14839             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14840                     + "\": required for package verification");
14841             return false;
14842         }
14843
14844         if (packageName.equals(getDefaultDialerPackageName(userId))) {
14845             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14846                     + "\": is the default dialer");
14847             return false;
14848         }
14849
14850         if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14851             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14852                     + "\": protected package");
14853             return false;
14854         }
14855
14856         // Cannot suspend static shared libs as they are considered
14857         // a part of the using app (emulating static linking). Also
14858         // static libs are installed always on internal storage.
14859         PackageParser.Package pkg = mPackages.get(packageName);
14860         if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14861             Slog.w(TAG, "Cannot suspend package: " + packageName
14862                     + " providing static shared library: "
14863                     + pkg.staticSharedLibName);
14864             return false;
14865         }
14866
14867         return true;
14868     }
14869
14870     private String getActiveLauncherPackageName(int userId) {
14871         Intent intent = new Intent(Intent.ACTION_MAIN);
14872         intent.addCategory(Intent.CATEGORY_HOME);
14873         ResolveInfo resolveInfo = resolveIntent(
14874                 intent,
14875                 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14876                 PackageManager.MATCH_DEFAULT_ONLY,
14877                 userId);
14878
14879         return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14880     }
14881
14882     private String getDefaultDialerPackageName(int userId) {
14883         synchronized (mPackages) {
14884             return mSettings.getDefaultDialerPackageNameLPw(userId);
14885         }
14886     }
14887
14888     @Override
14889     public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14890         mContext.enforceCallingOrSelfPermission(
14891                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14892                 "Only package verification agents can verify applications");
14893
14894         final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14895         final PackageVerificationResponse response = new PackageVerificationResponse(
14896                 verificationCode, Binder.getCallingUid());
14897         msg.arg1 = id;
14898         msg.obj = response;
14899         mHandler.sendMessage(msg);
14900     }
14901
14902     @Override
14903     public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14904             long millisecondsToDelay) {
14905         mContext.enforceCallingOrSelfPermission(
14906                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14907                 "Only package verification agents can extend verification timeouts");
14908
14909         final PackageVerificationState state = mPendingVerification.get(id);
14910         final PackageVerificationResponse response = new PackageVerificationResponse(
14911                 verificationCodeAtTimeout, Binder.getCallingUid());
14912
14913         if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14914             millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14915         }
14916         if (millisecondsToDelay < 0) {
14917             millisecondsToDelay = 0;
14918         }
14919         if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14920                 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14921             verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14922         }
14923
14924         if ((state != null) && !state.timeoutExtended()) {
14925             state.extendTimeout();
14926
14927             final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14928             msg.arg1 = id;
14929             msg.obj = response;
14930             mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14931         }
14932     }
14933
14934     private void broadcastPackageVerified(int verificationId, Uri packageUri,
14935             int verificationCode, UserHandle user) {
14936         final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14937         intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14938         intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14939         intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14940         intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14941
14942         mContext.sendBroadcastAsUser(intent, user,
14943                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14944     }
14945
14946     private ComponentName matchComponentForVerifier(String packageName,
14947             List<ResolveInfo> receivers) {
14948         ActivityInfo targetReceiver = null;
14949
14950         final int NR = receivers.size();
14951         for (int i = 0; i < NR; i++) {
14952             final ResolveInfo info = receivers.get(i);
14953             if (info.activityInfo == null) {
14954                 continue;
14955             }
14956
14957             if (packageName.equals(info.activityInfo.packageName)) {
14958                 targetReceiver = info.activityInfo;
14959                 break;
14960             }
14961         }
14962
14963         if (targetReceiver == null) {
14964             return null;
14965         }
14966
14967         return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14968     }
14969
14970     private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14971             List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14972         if (pkgInfo.verifiers.length == 0) {
14973             return null;
14974         }
14975
14976         final int N = pkgInfo.verifiers.length;
14977         final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14978         for (int i = 0; i < N; i++) {
14979             final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14980
14981             final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14982                     receivers);
14983             if (comp == null) {
14984                 continue;
14985             }
14986
14987             final int verifierUid = getUidForVerifier(verifierInfo);
14988             if (verifierUid == -1) {
14989                 continue;
14990             }
14991
14992             if (DEBUG_VERIFY) {
14993                 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14994                         + " with the correct signature");
14995             }
14996             sufficientVerifiers.add(comp);
14997             verificationState.addSufficientVerifier(verifierUid);
14998         }
14999
15000         return sufficientVerifiers;
15001     }
15002
15003     private int getUidForVerifier(VerifierInfo verifierInfo) {
15004         synchronized (mPackages) {
15005             final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15006             if (pkg == null) {
15007                 return -1;
15008             } else if (pkg.mSignatures.length != 1) {
15009                 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15010                         + " has more than one signature; ignoring");
15011                 return -1;
15012             }
15013
15014             /*
15015              * If the public key of the package's signature does not match
15016              * our expected public key, then this is a different package and
15017              * we should skip.
15018              */
15019
15020             final byte[] expectedPublicKey;
15021             try {
15022                 final Signature verifierSig = pkg.mSignatures[0];
15023                 final PublicKey publicKey = verifierSig.getPublicKey();
15024                 expectedPublicKey = publicKey.getEncoded();
15025             } catch (CertificateException e) {
15026                 return -1;
15027             }
15028
15029             final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15030
15031             if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15032                 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15033                         + " does not have the expected public key; ignoring");
15034                 return -1;
15035             }
15036
15037             return pkg.applicationInfo.uid;
15038         }
15039     }
15040
15041     @Override
15042     public void finishPackageInstall(int token, boolean didLaunch) {
15043         enforceSystemOrRoot("Only the system is allowed to finish installs");
15044
15045         if (DEBUG_INSTALL) {
15046             Slog.v(TAG, "BM finishing package install for " + token);
15047         }
15048         Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15049
15050         final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15051         mHandler.sendMessage(msg);
15052     }
15053
15054     /**
15055      * Get the verification agent timeout.  Used for both the APK verifier and the
15056      * intent filter verifier.
15057      *
15058      * @return verification timeout in milliseconds
15059      */
15060     private long getVerificationTimeout() {
15061         return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15062                 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15063                 DEFAULT_VERIFICATION_TIMEOUT);
15064     }
15065
15066     /**
15067      * Get the default verification agent response code.
15068      *
15069      * @return default verification response code
15070      */
15071     private int getDefaultVerificationResponse(UserHandle user) {
15072         if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15073             return PackageManager.VERIFICATION_REJECT;
15074         }
15075         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15076                 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15077                 DEFAULT_VERIFICATION_RESPONSE);
15078     }
15079
15080     /**
15081      * Check whether or not package verification has been enabled.
15082      *
15083      * @return true if verification should be performed
15084      */
15085     private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15086         if (!DEFAULT_VERIFY_ENABLE) {
15087             return false;
15088         }
15089
15090         boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15091
15092         // Check if installing from ADB
15093         if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15094             // Do not run verification in a test harness environment
15095             if (ActivityManager.isRunningInTestHarness()) {
15096                 return false;
15097             }
15098             if (ensureVerifyAppsEnabled) {
15099                 return true;
15100             }
15101             // Check if the developer does not want package verification for ADB installs
15102             if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15103                     android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15104                 return false;
15105             }
15106         } else {
15107             // only when not installed from ADB, skip verification for instant apps when
15108             // the installer and verifier are the same.
15109             if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15110                 if (mInstantAppInstallerActivity != null
15111                         && mInstantAppInstallerActivity.packageName.equals(
15112                                 mRequiredVerifierPackage)) {
15113                     try {
15114                         mContext.getSystemService(AppOpsManager.class)
15115                                 .checkPackage(installerUid, mRequiredVerifierPackage);
15116                         if (DEBUG_VERIFY) {
15117                             Slog.i(TAG, "disable verification for instant app");
15118                         }
15119                         return false;
15120                     } catch (SecurityException ignore) { }
15121                 }
15122             }
15123         }
15124
15125         if (ensureVerifyAppsEnabled) {
15126             return true;
15127         }
15128
15129         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15130                 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15131     }
15132
15133     @Override
15134     public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15135             throws RemoteException {
15136         mContext.enforceCallingOrSelfPermission(
15137                 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15138                 "Only intentfilter verification agents can verify applications");
15139
15140         final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15141         final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15142                 Binder.getCallingUid(), verificationCode, failedDomains);
15143         msg.arg1 = id;
15144         msg.obj = response;
15145         mHandler.sendMessage(msg);
15146     }
15147
15148     @Override
15149     public int getIntentVerificationStatus(String packageName, int userId) {
15150         final int callingUid = Binder.getCallingUid();
15151         if (getInstantAppPackageName(callingUid) != null) {
15152             return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15153         }
15154         synchronized (mPackages) {
15155             final PackageSetting ps = mSettings.mPackages.get(packageName);
15156             if (ps == null
15157                     || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15158                 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15159             }
15160             return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15161         }
15162     }
15163
15164     @Override
15165     public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15166         mContext.enforceCallingOrSelfPermission(
15167                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15168
15169         boolean result = false;
15170         synchronized (mPackages) {
15171             final PackageSetting ps = mSettings.mPackages.get(packageName);
15172             if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15173                 return false;
15174             }
15175             result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15176         }
15177         if (result) {
15178             scheduleWritePackageRestrictionsLocked(userId);
15179         }
15180         return result;
15181     }
15182
15183     @Override
15184     public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15185             String packageName) {
15186         final int callingUid = Binder.getCallingUid();
15187         if (getInstantAppPackageName(callingUid) != null) {
15188             return ParceledListSlice.emptyList();
15189         }
15190         synchronized (mPackages) {
15191             final PackageSetting ps = mSettings.mPackages.get(packageName);
15192             if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15193                 return ParceledListSlice.emptyList();
15194             }
15195             return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15196         }
15197     }
15198
15199     @Override
15200     public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15201         if (TextUtils.isEmpty(packageName)) {
15202             return ParceledListSlice.emptyList();
15203         }
15204         final int callingUid = Binder.getCallingUid();
15205         final int callingUserId = UserHandle.getUserId(callingUid);
15206         synchronized (mPackages) {
15207             PackageParser.Package pkg = mPackages.get(packageName);
15208             if (pkg == null || pkg.activities == null) {
15209                 return ParceledListSlice.emptyList();
15210             }
15211             if (pkg.mExtras == null) {
15212                 return ParceledListSlice.emptyList();
15213             }
15214             final PackageSetting ps = (PackageSetting) pkg.mExtras;
15215             if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15216                 return ParceledListSlice.emptyList();
15217             }
15218             final int count = pkg.activities.size();
15219             ArrayList<IntentFilter> result = new ArrayList<>();
15220             for (int n=0; n<count; n++) {
15221                 PackageParser.Activity activity = pkg.activities.get(n);
15222                 if (activity.intents != null && activity.intents.size() > 0) {
15223                     result.addAll(activity.intents);
15224                 }
15225             }
15226             return new ParceledListSlice<>(result);
15227         }
15228     }
15229
15230     @Override
15231     public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15232         mContext.enforceCallingOrSelfPermission(
15233                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15234
15235         synchronized (mPackages) {
15236             boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15237             if (packageName != null) {
15238                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15239                         packageName, userId);
15240             }
15241             return result;
15242         }
15243     }
15244
15245     @Override
15246     public String getDefaultBrowserPackageName(int userId) {
15247         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15248             return null;
15249         }
15250         synchronized (mPackages) {
15251             return mSettings.getDefaultBrowserPackageNameLPw(userId);
15252         }
15253     }
15254
15255     /**
15256      * Get the "allow unknown sources" setting.
15257      *
15258      * @return the current "allow unknown sources" setting
15259      */
15260     private int getUnknownSourcesSettings() {
15261         return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15262                 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15263                 -1);
15264     }
15265
15266     @Override
15267     public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15268         final int callingUid = Binder.getCallingUid();
15269         if (getInstantAppPackageName(callingUid) != null) {
15270             return;
15271         }
15272         // writer
15273         synchronized (mPackages) {
15274             PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15275             if (targetPackageSetting == null
15276                     || filterAppAccessLPr(
15277                             targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15278                 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15279             }
15280
15281             PackageSetting installerPackageSetting;
15282             if (installerPackageName != null) {
15283                 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15284                 if (installerPackageSetting == null) {
15285                     throw new IllegalArgumentException("Unknown installer package: "
15286                             + installerPackageName);
15287                 }
15288             } else {
15289                 installerPackageSetting = null;
15290             }
15291
15292             Signature[] callerSignature;
15293             Object obj = mSettings.getUserIdLPr(callingUid);
15294             if (obj != null) {
15295                 if (obj instanceof SharedUserSetting) {
15296                     callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15297                 } else if (obj instanceof PackageSetting) {
15298                     callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15299                 } else {
15300                     throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15301                 }
15302             } else {
15303                 throw new SecurityException("Unknown calling UID: " + callingUid);
15304             }
15305
15306             // Verify: can't set installerPackageName to a package that is
15307             // not signed with the same cert as the caller.
15308             if (installerPackageSetting != null) {
15309                 if (compareSignatures(callerSignature,
15310                         installerPackageSetting.signatures.mSignatures)
15311                         != PackageManager.SIGNATURE_MATCH) {
15312                     throw new SecurityException(
15313                             "Caller does not have same cert as new installer package "
15314                             + installerPackageName);
15315                 }
15316             }
15317
15318             // Verify: if target already has an installer package, it must
15319             // be signed with the same cert as the caller.
15320             if (targetPackageSetting.installerPackageName != null) {
15321                 PackageSetting setting = mSettings.mPackages.get(
15322                         targetPackageSetting.installerPackageName);
15323                 // If the currently set package isn't valid, then it's always
15324                 // okay to change it.
15325                 if (setting != null) {
15326                     if (compareSignatures(callerSignature,
15327                             setting.signatures.mSignatures)
15328                             != PackageManager.SIGNATURE_MATCH) {
15329                         throw new SecurityException(
15330                                 "Caller does not have same cert as old installer package "
15331                                 + targetPackageSetting.installerPackageName);
15332                     }
15333                 }
15334             }
15335
15336             // Okay!
15337             targetPackageSetting.installerPackageName = installerPackageName;
15338             if (installerPackageName != null) {
15339                 mSettings.mInstallerPackages.add(installerPackageName);
15340             }
15341             scheduleWriteSettingsLocked();
15342         }
15343     }
15344
15345     @Override
15346     public void setApplicationCategoryHint(String packageName, int categoryHint,
15347             String callerPackageName) {
15348         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15349             throw new SecurityException("Instant applications don't have access to this method");
15350         }
15351         mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15352                 callerPackageName);
15353         synchronized (mPackages) {
15354             PackageSetting ps = mSettings.mPackages.get(packageName);
15355             if (ps == null) {
15356                 throw new IllegalArgumentException("Unknown target package " + packageName);
15357             }
15358             if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15359                 throw new IllegalArgumentException("Unknown target package " + packageName);
15360             }
15361             if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15362                 throw new IllegalArgumentException("Calling package " + callerPackageName
15363                         + " is not installer for " + packageName);
15364             }
15365
15366             if (ps.categoryHint != categoryHint) {
15367                 ps.categoryHint = categoryHint;
15368                 scheduleWriteSettingsLocked();
15369             }
15370         }
15371     }
15372
15373     private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15374         // Queue up an async operation since the package installation may take a little while.
15375         mHandler.post(new Runnable() {
15376             public void run() {
15377                 mHandler.removeCallbacks(this);
15378                  // Result object to be returned
15379                 PackageInstalledInfo res = new PackageInstalledInfo();
15380                 res.setReturnCode(currentStatus);
15381                 res.uid = -1;
15382                 res.pkg = null;
15383                 res.removedInfo = null;
15384                 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15385                     args.doPreInstall(res.returnCode);
15386                     synchronized (mInstallLock) {
15387                         installPackageTracedLI(args, res);
15388                     }
15389                     args.doPostInstall(res.returnCode, res.uid);
15390                 }
15391
15392                 // A restore should be performed at this point if (a) the install
15393                 // succeeded, (b) the operation is not an update, and (c) the new
15394                 // package has not opted out of backup participation.
15395                 final boolean update = res.removedInfo != null
15396                         && res.removedInfo.removedPackage != null;
15397                 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15398                 boolean doRestore = !update
15399                         && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15400
15401                 // Set up the post-install work request bookkeeping.  This will be used
15402                 // and cleaned up by the post-install event handling regardless of whether
15403                 // there's a restore pass performed.  Token values are >= 1.
15404                 int token;
15405                 if (mNextInstallToken < 0) mNextInstallToken = 1;
15406                 token = mNextInstallToken++;
15407
15408                 PostInstallData data = new PostInstallData(args, res);
15409                 mRunningInstalls.put(token, data);
15410                 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15411
15412                 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15413                     // Pass responsibility to the Backup Manager.  It will perform a
15414                     // restore if appropriate, then pass responsibility back to the
15415                     // Package Manager to run the post-install observer callbacks
15416                     // and broadcasts.
15417                     IBackupManager bm = IBackupManager.Stub.asInterface(
15418                             ServiceManager.getService(Context.BACKUP_SERVICE));
15419                     if (bm != null) {
15420                         if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15421                                 + " to BM for possible restore");
15422                         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15423                         try {
15424                             // TODO: http://b/22388012
15425                             if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15426                                 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15427                             } else {
15428                                 doRestore = false;
15429                             }
15430                         } catch (RemoteException e) {
15431                             // can't happen; the backup manager is local
15432                         } catch (Exception e) {
15433                             Slog.e(TAG, "Exception trying to enqueue restore", e);
15434                             doRestore = false;
15435                         }
15436                     } else {
15437                         Slog.e(TAG, "Backup Manager not found!");
15438                         doRestore = false;
15439                     }
15440                 }
15441
15442                 if (!doRestore) {
15443                     // No restore possible, or the Backup Manager was mysteriously not
15444                     // available -- just fire the post-install work request directly.
15445                     if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15446
15447                     Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15448
15449                     Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15450                     mHandler.sendMessage(msg);
15451                 }
15452             }
15453         });
15454     }
15455
15456     /**
15457      * Callback from PackageSettings whenever an app is first transitioned out of the
15458      * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15459      * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15460      * here whether the app is the target of an ongoing install, and only send the
15461      * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15462      * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15463      * handling.
15464      */
15465     void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15466         // Serialize this with the rest of the install-process message chain.  In the
15467         // restore-at-install case, this Runnable will necessarily run before the
15468         // POST_INSTALL message is processed, so the contents of mRunningInstalls
15469         // are coherent.  In the non-restore case, the app has already completed install
15470         // and been launched through some other means, so it is not in a problematic
15471         // state for observers to see the FIRST_LAUNCH signal.
15472         mHandler.post(new Runnable() {
15473             @Override
15474             public void run() {
15475                 for (int i = 0; i < mRunningInstalls.size(); i++) {
15476                     final PostInstallData data = mRunningInstalls.valueAt(i);
15477                     if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15478                         continue;
15479                     }
15480                     if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15481                         // right package; but is it for the right user?
15482                         for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15483                             if (userId == data.res.newUsers[uIndex]) {
15484                                 if (DEBUG_BACKUP) {
15485                                     Slog.i(TAG, "Package " + pkgName
15486                                             + " being restored so deferring FIRST_LAUNCH");
15487                                 }
15488                                 return;
15489                             }
15490                         }
15491                     }
15492                 }
15493                 // didn't find it, so not being restored
15494                 if (DEBUG_BACKUP) {
15495                     Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15496                 }
15497                 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15498             }
15499         });
15500     }
15501
15502     private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15503         sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15504                 installerPkg, null, userIds);
15505     }
15506
15507     private abstract class HandlerParams {
15508         private static final int MAX_RETRIES = 4;
15509
15510         /**
15511          * Number of times startCopy() has been attempted and had a non-fatal
15512          * error.
15513          */
15514         private int mRetries = 0;
15515
15516         /** User handle for the user requesting the information or installation. */
15517         private final UserHandle mUser;
15518         String traceMethod;
15519         int traceCookie;
15520
15521         HandlerParams(UserHandle user) {
15522             mUser = user;
15523         }
15524
15525         UserHandle getUser() {
15526             return mUser;
15527         }
15528
15529         HandlerParams setTraceMethod(String traceMethod) {
15530             this.traceMethod = traceMethod;
15531             return this;
15532         }
15533
15534         HandlerParams setTraceCookie(int traceCookie) {
15535             this.traceCookie = traceCookie;
15536             return this;
15537         }
15538
15539         final boolean startCopy() {
15540             boolean res;
15541             try {
15542                 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15543
15544                 if (++mRetries > MAX_RETRIES) {
15545                     Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15546                     mHandler.sendEmptyMessage(MCS_GIVE_UP);
15547                     handleServiceError();
15548                     return false;
15549                 } else {
15550                     handleStartCopy();
15551                     res = true;
15552                 }
15553             } catch (RemoteException e) {
15554                 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15555                 mHandler.sendEmptyMessage(MCS_RECONNECT);
15556                 res = false;
15557             }
15558             handleReturnCode();
15559             return res;
15560         }
15561
15562         final void serviceError() {
15563             if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15564             handleServiceError();
15565             handleReturnCode();
15566         }
15567
15568         abstract void handleStartCopy() throws RemoteException;
15569         abstract void handleServiceError();
15570         abstract void handleReturnCode();
15571     }
15572
15573     private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15574         for (File path : paths) {
15575             try {
15576                 mcs.clearDirectory(path.getAbsolutePath());
15577             } catch (RemoteException e) {
15578             }
15579         }
15580     }
15581
15582     static class OriginInfo {
15583         /**
15584          * Location where install is coming from, before it has been
15585          * copied/renamed into place. This could be a single monolithic APK
15586          * file, or a cluster directory. This location may be untrusted.
15587          */
15588         final File file;
15589         final String cid;
15590
15591         /**
15592          * Flag indicating that {@link #file} or {@link #cid} has already been
15593          * staged, meaning downstream users don't need to defensively copy the
15594          * contents.
15595          */
15596         final boolean staged;
15597
15598         /**
15599          * Flag indicating that {@link #file} or {@link #cid} is an already
15600          * installed app that is being moved.
15601          */
15602         final boolean existing;
15603
15604         final String resolvedPath;
15605         final File resolvedFile;
15606
15607         static OriginInfo fromNothing() {
15608             return new OriginInfo(null, null, false, false);
15609         }
15610
15611         static OriginInfo fromUntrustedFile(File file) {
15612             return new OriginInfo(file, null, false, false);
15613         }
15614
15615         static OriginInfo fromExistingFile(File file) {
15616             return new OriginInfo(file, null, false, true);
15617         }
15618
15619         static OriginInfo fromStagedFile(File file) {
15620             return new OriginInfo(file, null, true, false);
15621         }
15622
15623         static OriginInfo fromStagedContainer(String cid) {
15624             return new OriginInfo(null, cid, true, false);
15625         }
15626
15627         private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15628             this.file = file;
15629             this.cid = cid;
15630             this.staged = staged;
15631             this.existing = existing;
15632
15633             if (cid != null) {
15634                 resolvedPath = PackageHelper.getSdDir(cid);
15635                 resolvedFile = new File(resolvedPath);
15636             } else if (file != null) {
15637                 resolvedPath = file.getAbsolutePath();
15638                 resolvedFile = file;
15639             } else {
15640                 resolvedPath = null;
15641                 resolvedFile = null;
15642             }
15643         }
15644     }
15645
15646     static class MoveInfo {
15647         final int moveId;
15648         final String fromUuid;
15649         final String toUuid;
15650         final String packageName;
15651         final String dataAppName;
15652         final int appId;
15653         final String seinfo;
15654         final int targetSdkVersion;
15655
15656         public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15657                 String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15658             this.moveId = moveId;
15659             this.fromUuid = fromUuid;
15660             this.toUuid = toUuid;
15661             this.packageName = packageName;
15662             this.dataAppName = dataAppName;
15663             this.appId = appId;
15664             this.seinfo = seinfo;
15665             this.targetSdkVersion = targetSdkVersion;
15666         }
15667     }
15668
15669     static class VerificationInfo {
15670         /** A constant used to indicate that a uid value is not present. */
15671         public static final int NO_UID = -1;
15672
15673         /** URI referencing where the package was downloaded from. */
15674         final Uri originatingUri;
15675
15676         /** HTTP referrer URI associated with the originatingURI. */
15677         final Uri referrer;
15678
15679         /** UID of the application that the install request originated from. */
15680         final int originatingUid;
15681
15682         /** UID of application requesting the install */
15683         final int installerUid;
15684
15685         VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15686             this.originatingUri = originatingUri;
15687             this.referrer = referrer;
15688             this.originatingUid = originatingUid;
15689             this.installerUid = installerUid;
15690         }
15691     }
15692
15693     class InstallParams extends HandlerParams {
15694         final OriginInfo origin;
15695         final MoveInfo move;
15696         final IPackageInstallObserver2 observer;
15697         int installFlags;
15698         final String installerPackageName;
15699         final String volumeUuid;
15700         private InstallArgs mArgs;
15701         private int mRet;
15702         final String packageAbiOverride;
15703         final String[] grantedRuntimePermissions;
15704         final VerificationInfo verificationInfo;
15705         final Certificate[][] certificates;
15706         final int installReason;
15707
15708         InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15709                 int installFlags, String installerPackageName, String volumeUuid,
15710                 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15711                 String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15712             super(user);
15713             this.origin = origin;
15714             this.move = move;
15715             this.observer = observer;
15716             this.installFlags = installFlags;
15717             this.installerPackageName = installerPackageName;
15718             this.volumeUuid = volumeUuid;
15719             this.verificationInfo = verificationInfo;
15720             this.packageAbiOverride = packageAbiOverride;
15721             this.grantedRuntimePermissions = grantedPermissions;
15722             this.certificates = certificates;
15723             this.installReason = installReason;
15724         }
15725
15726         @Override
15727         public String toString() {
15728             return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15729                     + " file=" + origin.file + " cid=" + origin.cid + "}";
15730         }
15731
15732         private int installLocationPolicy(PackageInfoLite pkgLite) {
15733             String packageName = pkgLite.packageName;
15734             int installLocation = pkgLite.installLocation;
15735             boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15736             // reader
15737             synchronized (mPackages) {
15738                 // Currently installed package which the new package is attempting to replace or
15739                 // null if no such package is installed.
15740                 PackageParser.Package installedPkg = mPackages.get(packageName);
15741                 // Package which currently owns the data which the new package will own if installed.
15742                 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15743                 // will be null whereas dataOwnerPkg will contain information about the package
15744                 // which was uninstalled while keeping its data.
15745                 PackageParser.Package dataOwnerPkg = installedPkg;
15746                 if (dataOwnerPkg  == null) {
15747                     PackageSetting ps = mSettings.mPackages.get(packageName);
15748                     if (ps != null) {
15749                         dataOwnerPkg = ps.pkg;
15750                     }
15751                 }
15752
15753                 if (dataOwnerPkg != null) {
15754                     // If installed, the package will get access to data left on the device by its
15755                     // predecessor. As a security measure, this is permited only if this is not a
15756                     // version downgrade or if the predecessor package is marked as debuggable and
15757                     // a downgrade is explicitly requested.
15758                     //
15759                     // On debuggable platform builds, downgrades are permitted even for
15760                     // non-debuggable packages to make testing easier. Debuggable platform builds do
15761                     // not offer security guarantees and thus it's OK to disable some security
15762                     // mechanisms to make debugging/testing easier on those builds. However, even on
15763                     // debuggable builds downgrades of packages are permitted only if requested via
15764                     // installFlags. This is because we aim to keep the behavior of debuggable
15765                     // platform builds as close as possible to the behavior of non-debuggable
15766                     // platform builds.
15767                     final boolean downgradeRequested =
15768                             (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15769                     final boolean packageDebuggable =
15770                                 (dataOwnerPkg.applicationInfo.flags
15771                                         & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15772                     final boolean downgradePermitted =
15773                             (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15774                     if (!downgradePermitted) {
15775                         try {
15776                             checkDowngrade(dataOwnerPkg, pkgLite);
15777                         } catch (PackageManagerException e) {
15778                             Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15779                             return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15780                         }
15781                     }
15782                 }
15783
15784                 if (installedPkg != null) {
15785                     if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15786                         // Check for updated system application.
15787                         if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15788                             if (onSd) {
15789                                 Slog.w(TAG, "Cannot install update to system app on sdcard");
15790                                 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15791                             }
15792                             return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15793                         } else {
15794                             if (onSd) {
15795                                 // Install flag overrides everything.
15796                                 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15797                             }
15798                             // If current upgrade specifies particular preference
15799                             if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15800                                 // Application explicitly specified internal.
15801                                 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15802                             } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15803                                 // App explictly prefers external. Let policy decide
15804                             } else {
15805                                 // Prefer previous location
15806                                 if (isExternal(installedPkg)) {
15807                                     return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15808                                 }
15809                                 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15810                             }
15811                         }
15812                     } else {
15813                         // Invalid install. Return error code
15814                         return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15815                     }
15816                 }
15817             }
15818             // All the special cases have been taken care of.
15819             // Return result based on recommended install location.
15820             if (onSd) {
15821                 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15822             }
15823             return pkgLite.recommendedInstallLocation;
15824         }
15825
15826         /*
15827          * Invoke remote method to get package information and install
15828          * location values. Override install location based on default
15829          * policy if needed and then create install arguments based
15830          * on the install location.
15831          */
15832         public void handleStartCopy() throws RemoteException {
15833             int ret = PackageManager.INSTALL_SUCCEEDED;
15834
15835             // If we're already staged, we've firmly committed to an install location
15836             if (origin.staged) {
15837                 if (origin.file != null) {
15838                     installFlags |= PackageManager.INSTALL_INTERNAL;
15839                     installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15840                 } else if (origin.cid != null) {
15841                     installFlags |= PackageManager.INSTALL_EXTERNAL;
15842                     installFlags &= ~PackageManager.INSTALL_INTERNAL;
15843                 } else {
15844                     throw new IllegalStateException("Invalid stage location");
15845                 }
15846             }
15847
15848             final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15849             final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15850             final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15851             PackageInfoLite pkgLite = null;
15852
15853             if (onInt && onSd) {
15854                 // Check if both bits are set.
15855                 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15856                 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15857             } else if (onSd && ephemeral) {
15858                 Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15859                 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15860             } else {
15861                 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15862                         packageAbiOverride);
15863
15864                 if (DEBUG_EPHEMERAL && ephemeral) {
15865                     Slog.v(TAG, "pkgLite for install: " + pkgLite);
15866                 }
15867
15868                 /*
15869                  * If we have too little free space, try to free cache
15870                  * before giving up.
15871                  */
15872                 if (!origin.staged && pkgLite.recommendedInstallLocation
15873                         == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15874                     // TODO: focus freeing disk space on the target device
15875                     final StorageManager storage = StorageManager.from(mContext);
15876                     final long lowThreshold = storage.getStorageLowBytes(
15877                             Environment.getDataDirectory());
15878
15879                     final long sizeBytes = mContainerService.calculateInstalledSize(
15880                             origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15881
15882                     try {
15883                         mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15884                         pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15885                                 installFlags, packageAbiOverride);
15886                     } catch (InstallerException e) {
15887                         Slog.w(TAG, "Failed to free cache", e);
15888                     }
15889
15890                     /*
15891                      * The cache free must have deleted the file we
15892                      * downloaded to install.
15893                      *
15894                      * TODO: fix the "freeCache" call to not delete
15895                      *       the file we care about.
15896                      */
15897                     if (pkgLite.recommendedInstallLocation
15898                             == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15899                         pkgLite.recommendedInstallLocation
15900                             = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15901                     }
15902                 }
15903             }
15904
15905             if (ret == PackageManager.INSTALL_SUCCEEDED) {
15906                 int loc = pkgLite.recommendedInstallLocation;
15907                 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15908                     ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15909                 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15910                     ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15911                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15912                     ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15913                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15914                     ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15915                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15916                     ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15917                 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15918                     ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15919                 } else {
15920                     // Override with defaults if needed.
15921                     loc = installLocationPolicy(pkgLite);
15922                     if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15923                         ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15924                     } else if (!onSd && !onInt) {
15925                         // Override install location with flags
15926                         if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15927                             // Set the flag to install on external media.
15928                             installFlags |= PackageManager.INSTALL_EXTERNAL;
15929                             installFlags &= ~PackageManager.INSTALL_INTERNAL;
15930                         } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15931                             if (DEBUG_EPHEMERAL) {
15932                                 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15933                             }
15934                             installFlags |= PackageManager.INSTALL_INSTANT_APP;
15935                             installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15936                                     |PackageManager.INSTALL_INTERNAL);
15937                         } else {
15938                             // Make sure the flag for installing on external
15939                             // media is unset
15940                             installFlags |= PackageManager.INSTALL_INTERNAL;
15941                             installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15942                         }
15943                     }
15944                 }
15945             }
15946
15947             final InstallArgs args = createInstallArgs(this);
15948             mArgs = args;
15949
15950             if (ret == PackageManager.INSTALL_SUCCEEDED) {
15951                 // TODO: http://b/22976637
15952                 // Apps installed for "all" users use the device owner to verify the app
15953                 UserHandle verifierUser = getUser();
15954                 if (verifierUser == UserHandle.ALL) {
15955                     verifierUser = UserHandle.SYSTEM;
15956                 }
15957
15958                 /*
15959                  * Determine if we have any installed package verifiers. If we
15960                  * do, then we'll defer to them to verify the packages.
15961                  */
15962                 final int requiredUid = mRequiredVerifierPackage == null ? -1
15963                         : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15964                                 verifierUser.getIdentifier());
15965                 final int installerUid =
15966                         verificationInfo == null ? -1 : verificationInfo.installerUid;
15967                 if (!origin.existing && requiredUid != -1
15968                         && isVerificationEnabled(
15969                                 verifierUser.getIdentifier(), installFlags, installerUid)) {
15970                     final Intent verification = new Intent(
15971                             Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15972                     verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15973                     verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15974                             PACKAGE_MIME_TYPE);
15975                     verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15976
15977                     // Query all live verifiers based on current user state
15978                     final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15979                             PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15980
15981                     if (DEBUG_VERIFY) {
15982                         Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15983                                 + verification.toString() + " with " + pkgLite.verifiers.length
15984                                 + " optional verifiers");
15985                     }
15986
15987                     final int verificationId = mPendingVerificationToken++;
15988
15989                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15990
15991                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15992                             installerPackageName);
15993
15994                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15995                             installFlags);
15996
15997                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15998                             pkgLite.packageName);
15999
16000                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16001                             pkgLite.versionCode);
16002
16003                     if (verificationInfo != null) {
16004                         if (verificationInfo.originatingUri != null) {
16005                             verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16006                                     verificationInfo.originatingUri);
16007                         }
16008                         if (verificationInfo.referrer != null) {
16009                             verification.putExtra(Intent.EXTRA_REFERRER,
16010                                     verificationInfo.referrer);
16011                         }
16012                         if (verificationInfo.originatingUid >= 0) {
16013                             verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16014                                     verificationInfo.originatingUid);
16015                         }
16016                         if (verificationInfo.installerUid >= 0) {
16017                             verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16018                                     verificationInfo.installerUid);
16019                         }
16020                     }
16021
16022                     final PackageVerificationState verificationState = new PackageVerificationState(
16023                             requiredUid, args);
16024
16025                     mPendingVerification.append(verificationId, verificationState);
16026
16027                     final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16028                             receivers, verificationState);
16029
16030                     DeviceIdleController.LocalService idleController = getDeviceIdleController();
16031                     final long idleDuration = getVerificationTimeout();
16032
16033                     /*
16034                      * If any sufficient verifiers were listed in the package
16035                      * manifest, attempt to ask them.
16036                      */
16037                     if (sufficientVerifiers != null) {
16038                         final int N = sufficientVerifiers.size();
16039                         if (N == 0) {
16040                             Slog.i(TAG, "Additional verifiers required, but none installed.");
16041                             ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16042                         } else {
16043                             for (int i = 0; i < N; i++) {
16044                                 final ComponentName verifierComponent = sufficientVerifiers.get(i);
16045                                 idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16046                                         verifierComponent.getPackageName(), idleDuration,
16047                                         verifierUser.getIdentifier(), false, "package verifier");
16048
16049                                 final Intent sufficientIntent = new Intent(verification);
16050                                 sufficientIntent.setComponent(verifierComponent);
16051                                 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16052                             }
16053                         }
16054                     }
16055
16056                     final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16057                             mRequiredVerifierPackage, receivers);
16058                     if (ret == PackageManager.INSTALL_SUCCEEDED
16059                             && mRequiredVerifierPackage != null) {
16060                         Trace.asyncTraceBegin(
16061                                 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16062                         /*
16063                          * Send the intent to the required verification agent,
16064                          * but only start the verification timeout after the
16065                          * target BroadcastReceivers have run.
16066                          */
16067                         verification.setComponent(requiredVerifierComponent);
16068                         idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16069                                 mRequiredVerifierPackage, idleDuration,
16070                                 verifierUser.getIdentifier(), false, "package verifier");
16071                         mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16072                                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16073                                 new BroadcastReceiver() {
16074                                     @Override
16075                                     public void onReceive(Context context, Intent intent) {
16076                                         final Message msg = mHandler
16077                                                 .obtainMessage(CHECK_PENDING_VERIFICATION);
16078                                         msg.arg1 = verificationId;
16079                                         mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16080                                     }
16081                                 }, null, 0, null, null);
16082
16083                         /*
16084                          * We don't want the copy to proceed until verification
16085                          * succeeds, so null out this field.
16086                          */
16087                         mArgs = null;
16088                     }
16089                 } else {
16090                     /*
16091                      * No package verification is enabled, so immediately start
16092                      * the remote call to initiate copy using temporary file.
16093                      */
16094                     ret = args.copyApk(mContainerService, true);
16095                 }
16096             }
16097
16098             mRet = ret;
16099         }
16100
16101         @Override
16102         void handleReturnCode() {
16103             // If mArgs is null, then MCS couldn't be reached. When it
16104             // reconnects, it will try again to install. At that point, this
16105             // will succeed.
16106             if (mArgs != null) {
16107                 processPendingInstall(mArgs, mRet);
16108             }
16109         }
16110
16111         @Override
16112         void handleServiceError() {
16113             mArgs = createInstallArgs(this);
16114             mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16115         }
16116
16117         public boolean isForwardLocked() {
16118             return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16119         }
16120     }
16121
16122     /**
16123      * Used during creation of InstallArgs
16124      *
16125      * @param installFlags package installation flags
16126      * @return true if should be installed on external storage
16127      */
16128     private static boolean installOnExternalAsec(int installFlags) {
16129         if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16130             return false;
16131         }
16132         if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16133             return true;
16134         }
16135         return false;
16136     }
16137
16138     /**
16139      * Used during creation of InstallArgs
16140      *
16141      * @param installFlags package installation flags
16142      * @return true if should be installed as forward locked
16143      */
16144     private static boolean installForwardLocked(int installFlags) {
16145         return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16146     }
16147
16148     private InstallArgs createInstallArgs(InstallParams params) {
16149         if (params.move != null) {
16150             return new MoveInstallArgs(params);
16151         } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16152             return new AsecInstallArgs(params);
16153         } else {
16154             return new FileInstallArgs(params);
16155         }
16156     }
16157
16158     /**
16159      * Create args that describe an existing installed package. Typically used
16160      * when cleaning up old installs, or used as a move source.
16161      */
16162     private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16163             String resourcePath, String[] instructionSets) {
16164         final boolean isInAsec;
16165         if (installOnExternalAsec(installFlags)) {
16166             /* Apps on SD card are always in ASEC containers. */
16167             isInAsec = true;
16168         } else if (installForwardLocked(installFlags)
16169                 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16170             /*
16171              * Forward-locked apps are only in ASEC containers if they're the
16172              * new style
16173              */
16174             isInAsec = true;
16175         } else {
16176             isInAsec = false;
16177         }
16178
16179         if (isInAsec) {
16180             return new AsecInstallArgs(codePath, instructionSets,
16181                     installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16182         } else {
16183             return new FileInstallArgs(codePath, resourcePath, instructionSets);
16184         }
16185     }
16186
16187     static abstract class InstallArgs {
16188         /** @see InstallParams#origin */
16189         final OriginInfo origin;
16190         /** @see InstallParams#move */
16191         final MoveInfo move;
16192
16193         final IPackageInstallObserver2 observer;
16194         // Always refers to PackageManager flags only
16195         final int installFlags;
16196         final String installerPackageName;
16197         final String volumeUuid;
16198         final UserHandle user;
16199         final String abiOverride;
16200         final String[] installGrantPermissions;
16201         /** If non-null, drop an async trace when the install completes */
16202         final String traceMethod;
16203         final int traceCookie;
16204         final Certificate[][] certificates;
16205         final int installReason;
16206
16207         // The list of instruction sets supported by this app. This is currently
16208         // only used during the rmdex() phase to clean up resources. We can get rid of this
16209         // if we move dex files under the common app path.
16210         /* nullable */ String[] instructionSets;
16211
16212         InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16213                 int installFlags, String installerPackageName, String volumeUuid,
16214                 UserHandle user, String[] instructionSets,
16215                 String abiOverride, String[] installGrantPermissions,
16216                 String traceMethod, int traceCookie, Certificate[][] certificates,
16217                 int installReason) {
16218             this.origin = origin;
16219             this.move = move;
16220             this.installFlags = installFlags;
16221             this.observer = observer;
16222             this.installerPackageName = installerPackageName;
16223             this.volumeUuid = volumeUuid;
16224             this.user = user;
16225             this.instructionSets = instructionSets;
16226             this.abiOverride = abiOverride;
16227             this.installGrantPermissions = installGrantPermissions;
16228             this.traceMethod = traceMethod;
16229             this.traceCookie = traceCookie;
16230             this.certificates = certificates;
16231             this.installReason = installReason;
16232         }
16233
16234         abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16235         abstract int doPreInstall(int status);
16236
16237         /**
16238          * Rename package into final resting place. All paths on the given
16239          * scanned package should be updated to reflect the rename.
16240          */
16241         abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16242         abstract int doPostInstall(int status, int uid);
16243
16244         /** @see PackageSettingBase#codePathString */
16245         abstract String getCodePath();
16246         /** @see PackageSettingBase#resourcePathString */
16247         abstract String getResourcePath();
16248
16249         // Need installer lock especially for dex file removal.
16250         abstract void cleanUpResourcesLI();
16251         abstract boolean doPostDeleteLI(boolean delete);
16252
16253         /**
16254          * Called before the source arguments are copied. This is used mostly
16255          * for MoveParams when it needs to read the source file to put it in the
16256          * destination.
16257          */
16258         int doPreCopy() {
16259             return PackageManager.INSTALL_SUCCEEDED;
16260         }
16261
16262         /**
16263          * Called after the source arguments are copied. This is used mostly for
16264          * MoveParams when it needs to read the source file to put it in the
16265          * destination.
16266          */
16267         int doPostCopy(int uid) {
16268             return PackageManager.INSTALL_SUCCEEDED;
16269         }
16270
16271         protected boolean isFwdLocked() {
16272             return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16273         }
16274
16275         protected boolean isExternalAsec() {
16276             return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16277         }
16278
16279         protected boolean isEphemeral() {
16280             return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16281         }
16282
16283         UserHandle getUser() {
16284             return user;
16285         }
16286     }
16287
16288     private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16289         if (!allCodePaths.isEmpty()) {
16290             if (instructionSets == null) {
16291                 throw new IllegalStateException("instructionSet == null");
16292             }
16293             String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16294             for (String codePath : allCodePaths) {
16295                 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16296                     try {
16297                         mInstaller.rmdex(codePath, dexCodeInstructionSet);
16298                     } catch (InstallerException ignored) {
16299                     }
16300                 }
16301             }
16302         }
16303     }
16304
16305     /**
16306      * Logic to handle installation of non-ASEC applications, including copying
16307      * and renaming logic.
16308      */
16309     class FileInstallArgs extends InstallArgs {
16310         private File codeFile;
16311         private File resourceFile;
16312
16313         // Example topology:
16314         // /data/app/com.example/base.apk
16315         // /data/app/com.example/split_foo.apk
16316         // /data/app/com.example/lib/arm/libfoo.so
16317         // /data/app/com.example/lib/arm64/libfoo.so
16318         // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16319
16320         /** New install */
16321         FileInstallArgs(InstallParams params) {
16322             super(params.origin, params.move, params.observer, params.installFlags,
16323                     params.installerPackageName, params.volumeUuid,
16324                     params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16325                     params.grantedRuntimePermissions,
16326                     params.traceMethod, params.traceCookie, params.certificates,
16327                     params.installReason);
16328             if (isFwdLocked()) {
16329                 throw new IllegalArgumentException("Forward locking only supported in ASEC");
16330             }
16331         }
16332
16333         /** Existing install */
16334         FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16335             super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16336                     null, null, null, 0, null /*certificates*/,
16337                     PackageManager.INSTALL_REASON_UNKNOWN);
16338             this.codeFile = (codePath != null) ? new File(codePath) : null;
16339             this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16340         }
16341
16342         int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16343             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16344             try {
16345                 return doCopyApk(imcs, temp);
16346             } finally {
16347                 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16348             }
16349         }
16350
16351         private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16352             if (origin.staged) {
16353                 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16354                 codeFile = origin.file;
16355                 resourceFile = origin.file;
16356                 return PackageManager.INSTALL_SUCCEEDED;
16357             }
16358
16359             try {
16360                 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16361                 final File tempDir =
16362                         mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16363                 codeFile = tempDir;
16364                 resourceFile = tempDir;
16365             } catch (IOException e) {
16366                 Slog.w(TAG, "Failed to create copy file: " + e);
16367                 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16368             }
16369
16370             final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16371                 @Override
16372                 public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16373                     if (!FileUtils.isValidExtFilename(name)) {
16374                         throw new IllegalArgumentException("Invalid filename: " + name);
16375                     }
16376                     try {
16377                         final File file = new File(codeFile, name);
16378                         final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16379                                 O_RDWR | O_CREAT, 0644);
16380                         Os.chmod(file.getAbsolutePath(), 0644);
16381                         return new ParcelFileDescriptor(fd);
16382                     } catch (ErrnoException e) {
16383                         throw new RemoteException("Failed to open: " + e.getMessage());
16384                     }
16385                 }
16386             };
16387
16388             int ret = PackageManager.INSTALL_SUCCEEDED;
16389             ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16390             if (ret != PackageManager.INSTALL_SUCCEEDED) {
16391                 Slog.e(TAG, "Failed to copy package");
16392                 return ret;
16393             }
16394
16395             final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16396             NativeLibraryHelper.Handle handle = null;
16397             try {
16398                 handle = NativeLibraryHelper.Handle.create(codeFile);
16399                 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16400                         abiOverride);
16401             } catch (IOException e) {
16402                 Slog.e(TAG, "Copying native libraries failed", e);
16403                 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16404             } finally {
16405                 IoUtils.closeQuietly(handle);
16406             }
16407
16408             return ret;
16409         }
16410
16411         int doPreInstall(int status) {
16412             if (status != PackageManager.INSTALL_SUCCEEDED) {
16413                 cleanUp();
16414             }
16415             return status;
16416         }
16417
16418         boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16419             if (status != PackageManager.INSTALL_SUCCEEDED) {
16420                 cleanUp();
16421                 return false;
16422             }
16423
16424             final File targetDir = codeFile.getParentFile();
16425             final File beforeCodeFile = codeFile;
16426             final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16427
16428             if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16429             try {
16430                 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16431             } catch (ErrnoException e) {
16432                 Slog.w(TAG, "Failed to rename", e);
16433                 return false;
16434             }
16435
16436             if (!SELinux.restoreconRecursive(afterCodeFile)) {
16437                 Slog.w(TAG, "Failed to restorecon");
16438                 return false;
16439             }
16440
16441             // Reflect the rename internally
16442             codeFile = afterCodeFile;
16443             resourceFile = afterCodeFile;
16444
16445             // Reflect the rename in scanned details
16446             pkg.setCodePath(afterCodeFile.getAbsolutePath());
16447             pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16448                     afterCodeFile, pkg.baseCodePath));
16449             pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16450                     afterCodeFile, pkg.splitCodePaths));
16451
16452             // Reflect the rename in app info
16453             pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16454             pkg.setApplicationInfoCodePath(pkg.codePath);
16455             pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16456             pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16457             pkg.setApplicationInfoResourcePath(pkg.codePath);
16458             pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16459             pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16460
16461             return true;
16462         }
16463
16464         int doPostInstall(int status, int uid) {
16465             if (status != PackageManager.INSTALL_SUCCEEDED) {
16466                 cleanUp();
16467             }
16468             return status;
16469         }
16470
16471         @Override
16472         String getCodePath() {
16473             return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16474         }
16475
16476         @Override
16477         String getResourcePath() {
16478             return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16479         }
16480
16481         private boolean cleanUp() {
16482             if (codeFile == null || !codeFile.exists()) {
16483                 return false;
16484             }
16485
16486             removeCodePathLI(codeFile);
16487
16488             if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16489                 resourceFile.delete();
16490             }
16491
16492             return true;
16493         }
16494
16495         void cleanUpResourcesLI() {
16496             // Try enumerating all code paths before deleting
16497             List<String> allCodePaths = Collections.EMPTY_LIST;
16498             if (codeFile != null && codeFile.exists()) {
16499                 try {
16500                     final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16501                     allCodePaths = pkg.getAllCodePaths();
16502                 } catch (PackageParserException e) {
16503                     // Ignored; we tried our best
16504                 }
16505             }
16506
16507             cleanUp();
16508             removeDexFiles(allCodePaths, instructionSets);
16509         }
16510
16511         boolean doPostDeleteLI(boolean delete) {
16512             // XXX err, shouldn't we respect the delete flag?
16513             cleanUpResourcesLI();
16514             return true;
16515         }
16516     }
16517
16518     private boolean isAsecExternal(String cid) {
16519         final String asecPath = PackageHelper.getSdFilesystem(cid);
16520         return !asecPath.startsWith(mAsecInternalPath);
16521     }
16522
16523     private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16524             PackageManagerException {
16525         if (copyRet < 0) {
16526             if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16527                     copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16528                 throw new PackageManagerException(copyRet, message);
16529             }
16530         }
16531     }
16532
16533     /**
16534      * Extract the StorageManagerService "container ID" from the full code path of an
16535      * .apk.
16536      */
16537     static String cidFromCodePath(String fullCodePath) {
16538         int eidx = fullCodePath.lastIndexOf("/");
16539         String subStr1 = fullCodePath.substring(0, eidx);
16540         int sidx = subStr1.lastIndexOf("/");
16541         return subStr1.substring(sidx+1, eidx);
16542     }
16543
16544     /**
16545      * Logic to handle installation of ASEC applications, including copying and
16546      * renaming logic.
16547      */
16548     class AsecInstallArgs extends InstallArgs {
16549         static final String RES_FILE_NAME = "pkg.apk";
16550         static final String PUBLIC_RES_FILE_NAME = "res.zip";
16551
16552         String cid;
16553         String packagePath;
16554         String resourcePath;
16555
16556         /** New install */
16557         AsecInstallArgs(InstallParams params) {
16558             super(params.origin, params.move, params.observer, params.installFlags,
16559                     params.installerPackageName, params.volumeUuid,
16560                     params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16561                     params.grantedRuntimePermissions,
16562                     params.traceMethod, params.traceCookie, params.certificates,
16563                     params.installReason);
16564         }
16565
16566         /** Existing install */
16567         AsecInstallArgs(String fullCodePath, String[] instructionSets,
16568                         boolean isExternal, boolean isForwardLocked) {
16569             super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16570                     | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16571                     instructionSets, null, null, null, 0, null /*certificates*/,
16572                     PackageManager.INSTALL_REASON_UNKNOWN);
16573             // Hackily pretend we're still looking at a full code path
16574             if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16575                 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16576             }
16577
16578             // Extract cid from fullCodePath
16579             int eidx = fullCodePath.lastIndexOf("/");
16580             String subStr1 = fullCodePath.substring(0, eidx);
16581             int sidx = subStr1.lastIndexOf("/");
16582             cid = subStr1.substring(sidx+1, eidx);
16583             setMountPath(subStr1);
16584         }
16585
16586         AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16587             super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16588                     | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16589                     instructionSets, null, null, null, 0, null /*certificates*/,
16590                     PackageManager.INSTALL_REASON_UNKNOWN);
16591             this.cid = cid;
16592             setMountPath(PackageHelper.getSdDir(cid));
16593         }
16594
16595         void createCopyFile() {
16596             cid = mInstallerService.allocateExternalStageCidLegacy();
16597         }
16598
16599         int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16600             if (origin.staged && origin.cid != null) {
16601                 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16602                 cid = origin.cid;
16603                 setMountPath(PackageHelper.getSdDir(cid));
16604                 return PackageManager.INSTALL_SUCCEEDED;
16605             }
16606
16607             if (temp) {
16608                 createCopyFile();
16609             } else {
16610                 /*
16611                  * Pre-emptively destroy the container since it's destroyed if
16612                  * copying fails due to it existing anyway.
16613                  */
16614                 PackageHelper.destroySdDir(cid);
16615             }
16616
16617             final String newMountPath = imcs.copyPackageToContainer(
16618                     origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16619                     isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16620
16621             if (newMountPath != null) {
16622                 setMountPath(newMountPath);
16623                 return PackageManager.INSTALL_SUCCEEDED;
16624             } else {
16625                 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16626             }
16627         }
16628
16629         @Override
16630         String getCodePath() {
16631             return packagePath;
16632         }
16633
16634         @Override
16635         String getResourcePath() {
16636             return resourcePath;
16637         }
16638
16639         int doPreInstall(int status) {
16640             if (status != PackageManager.INSTALL_SUCCEEDED) {
16641                 // Destroy container
16642                 PackageHelper.destroySdDir(cid);
16643             } else {
16644                 boolean mounted = PackageHelper.isContainerMounted(cid);
16645                 if (!mounted) {
16646                     String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16647                             Process.SYSTEM_UID);
16648                     if (newMountPath != null) {
16649                         setMountPath(newMountPath);
16650                     } else {
16651                         return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16652                     }
16653                 }
16654             }
16655             return status;
16656         }
16657
16658         boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16659             String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16660             String newMountPath = null;
16661             if (PackageHelper.isContainerMounted(cid)) {
16662                 // Unmount the container
16663                 if (!PackageHelper.unMountSdDir(cid)) {
16664                     Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16665                     return false;
16666                 }
16667             }
16668             if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16669                 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16670                         " which might be stale. Will try to clean up.");
16671                 // Clean up the stale container and proceed to recreate.
16672                 if (!PackageHelper.destroySdDir(newCacheId)) {
16673                     Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16674                     return false;
16675                 }
16676                 // Successfully cleaned up stale container. Try to rename again.
16677                 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16678                     Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16679                             + " inspite of cleaning it up.");
16680                     return false;
16681                 }
16682             }
16683             if (!PackageHelper.isContainerMounted(newCacheId)) {
16684                 Slog.w(TAG, "Mounting container " + newCacheId);
16685                 newMountPath = PackageHelper.mountSdDir(newCacheId,
16686                         getEncryptKey(), Process.SYSTEM_UID);
16687             } else {
16688                 newMountPath = PackageHelper.getSdDir(newCacheId);
16689             }
16690             if (newMountPath == null) {
16691                 Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16692                 return false;
16693             }
16694             Log.i(TAG, "Succesfully renamed " + cid +
16695                     " to " + newCacheId +
16696                     " at new path: " + newMountPath);
16697             cid = newCacheId;
16698
16699             final File beforeCodeFile = new File(packagePath);
16700             setMountPath(newMountPath);
16701             final File afterCodeFile = new File(packagePath);
16702
16703             // Reflect the rename in scanned details
16704             pkg.setCodePath(afterCodeFile.getAbsolutePath());
16705             pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16706                     afterCodeFile, pkg.baseCodePath));
16707             pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16708                     afterCodeFile, pkg.splitCodePaths));
16709
16710             // Reflect the rename in app info
16711             pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16712             pkg.setApplicationInfoCodePath(pkg.codePath);
16713             pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16714             pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16715             pkg.setApplicationInfoResourcePath(pkg.codePath);
16716             pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16717             pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16718
16719             return true;
16720         }
16721
16722         private void setMountPath(String mountPath) {
16723             final File mountFile = new File(mountPath);
16724
16725             final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16726             if (monolithicFile.exists()) {
16727                 packagePath = monolithicFile.getAbsolutePath();
16728                 if (isFwdLocked()) {
16729                     resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16730                 } else {
16731                     resourcePath = packagePath;
16732                 }
16733             } else {
16734                 packagePath = mountFile.getAbsolutePath();
16735                 resourcePath = packagePath;
16736             }
16737         }
16738
16739         int doPostInstall(int status, int uid) {
16740             if (status != PackageManager.INSTALL_SUCCEEDED) {
16741                 cleanUp();
16742             } else {
16743                 final int groupOwner;
16744                 final String protectedFile;
16745                 if (isFwdLocked()) {
16746                     groupOwner = UserHandle.getSharedAppGid(uid);
16747                     protectedFile = RES_FILE_NAME;
16748                 } else {
16749                     groupOwner = -1;
16750                     protectedFile = null;
16751                 }
16752
16753                 if (uid < Process.FIRST_APPLICATION_UID
16754                         || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16755                     Slog.e(TAG, "Failed to finalize " + cid);
16756                     PackageHelper.destroySdDir(cid);
16757                     return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16758                 }
16759
16760                 boolean mounted = PackageHelper.isContainerMounted(cid);
16761                 if (!mounted) {
16762                     PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16763                 }
16764             }
16765             return status;
16766         }
16767
16768         private void cleanUp() {
16769             if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16770
16771             // Destroy secure container
16772             PackageHelper.destroySdDir(cid);
16773         }
16774
16775         private List<String> getAllCodePaths() {
16776             final File codeFile = new File(getCodePath());
16777             if (codeFile != null && codeFile.exists()) {
16778                 try {
16779                     final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16780                     return pkg.getAllCodePaths();
16781                 } catch (PackageParserException e) {
16782                     // Ignored; we tried our best
16783                 }
16784             }
16785             return Collections.EMPTY_LIST;
16786         }
16787
16788         void cleanUpResourcesLI() {
16789             // Enumerate all code paths before deleting
16790             cleanUpResourcesLI(getAllCodePaths());
16791         }
16792
16793         private void cleanUpResourcesLI(List<String> allCodePaths) {
16794             cleanUp();
16795             removeDexFiles(allCodePaths, instructionSets);
16796         }
16797
16798         String getPackageName() {
16799             return getAsecPackageName(cid);
16800         }
16801
16802         boolean doPostDeleteLI(boolean delete) {
16803             if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16804             final List<String> allCodePaths = getAllCodePaths();
16805             boolean mounted = PackageHelper.isContainerMounted(cid);
16806             if (mounted) {
16807                 // Unmount first
16808                 if (PackageHelper.unMountSdDir(cid)) {
16809                     mounted = false;
16810                 }
16811             }
16812             if (!mounted && delete) {
16813                 cleanUpResourcesLI(allCodePaths);
16814             }
16815             return !mounted;
16816         }
16817
16818         @Override
16819         int doPreCopy() {
16820             if (isFwdLocked()) {
16821                 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16822                         MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16823                     return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16824                 }
16825             }
16826
16827             return PackageManager.INSTALL_SUCCEEDED;
16828         }
16829
16830         @Override
16831         int doPostCopy(int uid) {
16832             if (isFwdLocked()) {
16833                 if (uid < Process.FIRST_APPLICATION_UID
16834                         || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16835                                 RES_FILE_NAME)) {
16836                     Slog.e(TAG, "Failed to finalize " + cid);
16837                     PackageHelper.destroySdDir(cid);
16838                     return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16839                 }
16840             }
16841
16842             return PackageManager.INSTALL_SUCCEEDED;
16843         }
16844     }
16845
16846     /**
16847      * Logic to handle movement of existing installed applications.
16848      */
16849     class MoveInstallArgs extends InstallArgs {
16850         private File codeFile;
16851         private File resourceFile;
16852
16853         /** New install */
16854         MoveInstallArgs(InstallParams params) {
16855             super(params.origin, params.move, params.observer, params.installFlags,
16856                     params.installerPackageName, params.volumeUuid,
16857                     params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16858                     params.grantedRuntimePermissions,
16859                     params.traceMethod, params.traceCookie, params.certificates,
16860                     params.installReason);
16861         }
16862
16863         int copyApk(IMediaContainerService imcs, boolean temp) {
16864             if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16865                     + move.fromUuid + " to " + move.toUuid);
16866             synchronized (mInstaller) {
16867                 try {
16868                     mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16869                             move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16870                 } catch (InstallerException e) {
16871                     Slog.w(TAG, "Failed to move app", e);
16872                     return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16873                 }
16874             }
16875
16876             codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16877             resourceFile = codeFile;
16878             if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16879
16880             return PackageManager.INSTALL_SUCCEEDED;
16881         }
16882
16883         int doPreInstall(int status) {
16884             if (status != PackageManager.INSTALL_SUCCEEDED) {
16885                 cleanUp(move.toUuid);
16886             }
16887             return status;
16888         }
16889
16890         boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16891             if (status != PackageManager.INSTALL_SUCCEEDED) {
16892                 cleanUp(move.toUuid);
16893                 return false;
16894             }
16895
16896             // Reflect the move in app info
16897             pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16898             pkg.setApplicationInfoCodePath(pkg.codePath);
16899             pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16900             pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16901             pkg.setApplicationInfoResourcePath(pkg.codePath);
16902             pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16903             pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16904
16905             return true;
16906         }
16907
16908         int doPostInstall(int status, int uid) {
16909             if (status == PackageManager.INSTALL_SUCCEEDED) {
16910                 cleanUp(move.fromUuid);
16911             } else {
16912                 cleanUp(move.toUuid);
16913             }
16914             return status;
16915         }
16916
16917         @Override
16918         String getCodePath() {
16919             return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16920         }
16921
16922         @Override
16923         String getResourcePath() {
16924             return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16925         }
16926
16927         private boolean cleanUp(String volumeUuid) {
16928             final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16929                     move.dataAppName);
16930             Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16931             final int[] userIds = sUserManager.getUserIds();
16932             synchronized (mInstallLock) {
16933                 // Clean up both app data and code
16934                 // All package moves are frozen until finished
16935                 for (int userId : userIds) {
16936                     try {
16937                         mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16938                                 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16939                     } catch (InstallerException e) {
16940                         Slog.w(TAG, String.valueOf(e));
16941                     }
16942                 }
16943                 removeCodePathLI(codeFile);
16944             }
16945             return true;
16946         }
16947
16948         void cleanUpResourcesLI() {
16949             throw new UnsupportedOperationException();
16950         }
16951
16952         boolean doPostDeleteLI(boolean delete) {
16953             throw new UnsupportedOperationException();
16954         }
16955     }
16956
16957     static String getAsecPackageName(String packageCid) {
16958         int idx = packageCid.lastIndexOf("-");
16959         if (idx == -1) {
16960             return packageCid;
16961         }
16962         return packageCid.substring(0, idx);
16963     }
16964
16965     // Utility method used to create code paths based on package name and available index.
16966     private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16967         String idxStr = "";
16968         int idx = 1;
16969         // Fall back to default value of idx=1 if prefix is not
16970         // part of oldCodePath
16971         if (oldCodePath != null) {
16972             String subStr = oldCodePath;
16973             // Drop the suffix right away
16974             if (suffix != null && subStr.endsWith(suffix)) {
16975                 subStr = subStr.substring(0, subStr.length() - suffix.length());
16976             }
16977             // If oldCodePath already contains prefix find out the
16978             // ending index to either increment or decrement.
16979             int sidx = subStr.lastIndexOf(prefix);
16980             if (sidx != -1) {
16981                 subStr = subStr.substring(sidx + prefix.length());
16982                 if (subStr != null) {
16983                     if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16984                         subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16985                     }
16986                     try {
16987                         idx = Integer.parseInt(subStr);
16988                         if (idx <= 1) {
16989                             idx++;
16990                         } else {
16991                             idx--;
16992                         }
16993                     } catch(NumberFormatException e) {
16994                     }
16995                 }
16996             }
16997         }
16998         idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16999         return prefix + idxStr;
17000     }
17001
17002     private File getNextCodePath(File targetDir, String packageName) {
17003         File result;
17004         SecureRandom random = new SecureRandom();
17005         byte[] bytes = new byte[16];
17006         do {
17007             random.nextBytes(bytes);
17008             String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17009             result = new File(targetDir, packageName + "-" + suffix);
17010         } while (result.exists());
17011         return result;
17012     }
17013
17014     // Utility method that returns the relative package path with respect
17015     // to the installation directory. Like say for /data/data/com.test-1.apk
17016     // string com.test-1 is returned.
17017     static String deriveCodePathName(String codePath) {
17018         if (codePath == null) {
17019             return null;
17020         }
17021         final File codeFile = new File(codePath);
17022         final String name = codeFile.getName();
17023         if (codeFile.isDirectory()) {
17024             return name;
17025         } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17026             final int lastDot = name.lastIndexOf('.');
17027             return name.substring(0, lastDot);
17028         } else {
17029             Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17030             return null;
17031         }
17032     }
17033
17034     static class PackageInstalledInfo {
17035         String name;
17036         int uid;
17037         // The set of users that originally had this package installed.
17038         int[] origUsers;
17039         // The set of users that now have this package installed.
17040         int[] newUsers;
17041         PackageParser.Package pkg;
17042         int returnCode;
17043         String returnMsg;
17044         PackageRemovedInfo removedInfo;
17045         ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17046
17047         public void setError(int code, String msg) {
17048             setReturnCode(code);
17049             setReturnMessage(msg);
17050             Slog.w(TAG, msg);
17051         }
17052
17053         public void setError(String msg, PackageParserException e) {
17054             setReturnCode(e.error);
17055             setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17056             Slog.w(TAG, msg, e);
17057         }
17058
17059         public void setError(String msg, PackageManagerException e) {
17060             returnCode = e.error;
17061             setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17062             Slog.w(TAG, msg, e);
17063         }
17064
17065         public void setReturnCode(int returnCode) {
17066             this.returnCode = returnCode;
17067             final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17068             for (int i = 0; i < childCount; i++) {
17069                 addedChildPackages.valueAt(i).returnCode = returnCode;
17070             }
17071         }
17072
17073         private void setReturnMessage(String returnMsg) {
17074             this.returnMsg = returnMsg;
17075             final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17076             for (int i = 0; i < childCount; i++) {
17077                 addedChildPackages.valueAt(i).returnMsg = returnMsg;
17078             }
17079         }
17080
17081         // In some error cases we want to convey more info back to the observer
17082         String origPackage;
17083         String origPermission;
17084     }
17085
17086     /*
17087      * Install a non-existing package.
17088      */
17089     private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17090             int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17091             PackageInstalledInfo res, int installReason) {
17092         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17093
17094         // Remember this for later, in case we need to rollback this install
17095         String pkgName = pkg.packageName;
17096
17097         if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17098
17099         synchronized(mPackages) {
17100             final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17101             if (renamedPackage != null) {
17102                 // A package with the same name is already installed, though
17103                 // it has been renamed to an older name.  The package we
17104                 // are trying to install should be installed as an update to
17105                 // the existing one, but that has not been requested, so bail.
17106                 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17107                         + " without first uninstalling package running as "
17108                         + renamedPackage);
17109                 return;
17110             }
17111             if (mPackages.containsKey(pkgName)) {
17112                 // Don't allow installation over an existing package with the same name.
17113                 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17114                         + " without first uninstalling.");
17115                 return;
17116             }
17117         }
17118
17119         try {
17120             PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17121                     System.currentTimeMillis(), user);
17122
17123             updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17124
17125             if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17126                 prepareAppDataAfterInstallLIF(newPackage);
17127
17128             } else {
17129                 // Remove package from internal structures, but keep around any
17130                 // data that might have already existed
17131                 deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17132                         PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17133             }
17134         } catch (PackageManagerException e) {
17135             res.setError("Package couldn't be installed in " + pkg.codePath, e);
17136         }
17137
17138         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17139     }
17140
17141     private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17142         // Can't rotate keys during boot or if sharedUser.
17143         if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17144                 || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17145             return false;
17146         }
17147         // app is using upgradeKeySets; make sure all are valid
17148         KeySetManagerService ksms = mSettings.mKeySetManagerService;
17149         long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17150         for (int i = 0; i < upgradeKeySets.length; i++) {
17151             if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17152                 Slog.wtf(TAG, "Package "
17153                          + (oldPs.name != null ? oldPs.name : "<null>")
17154                          + " contains upgrade-key-set reference to unknown key-set: "
17155                          + upgradeKeySets[i]
17156                          + " reverting to signatures check.");
17157                 return false;
17158             }
17159         }
17160         return true;
17161     }
17162
17163     private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17164         // Upgrade keysets are being used.  Determine if new package has a superset of the
17165         // required keys.
17166         long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17167         KeySetManagerService ksms = mSettings.mKeySetManagerService;
17168         for (int i = 0; i < upgradeKeySets.length; i++) {
17169             Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17170             if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17171                 return true;
17172             }
17173         }
17174         return false;
17175     }
17176
17177     private static void updateDigest(MessageDigest digest, File file) throws IOException {
17178         try (DigestInputStream digestStream =
17179                 new DigestInputStream(new FileInputStream(file), digest)) {
17180             while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17181         }
17182     }
17183
17184     private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17185             UserHandle user, String installerPackageName, PackageInstalledInfo res,
17186             int installReason) {
17187         final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17188
17189         final PackageParser.Package oldPackage;
17190         final PackageSetting ps;
17191         final String pkgName = pkg.packageName;
17192         final int[] allUsers;
17193         final int[] installedUsers;
17194
17195         synchronized(mPackages) {
17196             oldPackage = mPackages.get(pkgName);
17197             if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17198
17199             // don't allow upgrade to target a release SDK from a pre-release SDK
17200             final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17201                     == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17202             final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17203                     == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17204             if (oldTargetsPreRelease
17205                     && !newTargetsPreRelease
17206                     && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17207                 Slog.w(TAG, "Can't install package targeting released sdk");
17208                 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17209                 return;
17210             }
17211
17212             ps = mSettings.mPackages.get(pkgName);
17213
17214             // verify signatures are valid
17215             if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17216                 if (!checkUpgradeKeySetLP(ps, pkg)) {
17217                     res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17218                             "New package not signed by keys specified by upgrade-keysets: "
17219                                     + pkgName);
17220                     return;
17221                 }
17222             } else {
17223                 // default to original signature matching
17224                 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17225                         != PackageManager.SIGNATURE_MATCH) {
17226                     res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17227                             "New package has a different signature: " + pkgName);
17228                     return;
17229                 }
17230             }
17231
17232             // don't allow a system upgrade unless the upgrade hash matches
17233             if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17234                 byte[] digestBytes = null;
17235                 try {
17236                     final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17237                     updateDigest(digest, new File(pkg.baseCodePath));
17238                     if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17239                         for (String path : pkg.splitCodePaths) {
17240                             updateDigest(digest, new File(path));
17241                         }
17242                     }
17243                     digestBytes = digest.digest();
17244                 } catch (NoSuchAlgorithmException | IOException e) {
17245                     res.setError(INSTALL_FAILED_INVALID_APK,
17246                             "Could not compute hash: " + pkgName);
17247                     return;
17248                 }
17249                 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17250                     res.setError(INSTALL_FAILED_INVALID_APK,
17251                             "New package fails restrict-update check: " + pkgName);
17252                     return;
17253                 }
17254                 // retain upgrade restriction
17255                 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17256             }
17257
17258             // Check for shared user id changes
17259             String invalidPackageName =
17260                     getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17261             if (invalidPackageName != null) {
17262                 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17263                         "Package " + invalidPackageName + " tried to change user "
17264                                 + oldPackage.mSharedUserId);
17265                 return;
17266             }
17267
17268             // In case of rollback, remember per-user/profile install state
17269             allUsers = sUserManager.getUserIds();
17270             installedUsers = ps.queryInstalledUsers(allUsers, true);
17271
17272             // don't allow an upgrade from full to ephemeral
17273             if (isInstantApp) {
17274                 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17275                     for (int currentUser : allUsers) {
17276                         if (!ps.getInstantApp(currentUser)) {
17277                             // can't downgrade from full to instant
17278                             Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17279                                     + " for user: " + currentUser);
17280                             res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17281                             return;
17282                         }
17283                     }
17284                 } else if (!ps.getInstantApp(user.getIdentifier())) {
17285                     // can't downgrade from full to instant
17286                     Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17287                             + " for user: " + user.getIdentifier());
17288                     res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17289                     return;
17290                 }
17291             }
17292         }
17293
17294         // Update what is removed
17295         res.removedInfo = new PackageRemovedInfo(this);
17296         res.removedInfo.uid = oldPackage.applicationInfo.uid;
17297         res.removedInfo.removedPackage = oldPackage.packageName;
17298         res.removedInfo.installerPackageName = ps.installerPackageName;
17299         res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17300         res.removedInfo.isUpdate = true;
17301         res.removedInfo.origUsers = installedUsers;
17302         res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17303         for (int i = 0; i < installedUsers.length; i++) {
17304             final int userId = installedUsers[i];
17305             res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17306         }
17307
17308         final int childCount = (oldPackage.childPackages != null)
17309                 ? oldPackage.childPackages.size() : 0;
17310         for (int i = 0; i < childCount; i++) {
17311             boolean childPackageUpdated = false;
17312             PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17313             final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17314             if (res.addedChildPackages != null) {
17315                 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17316                 if (childRes != null) {
17317                     childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17318                     childRes.removedInfo.removedPackage = childPkg.packageName;
17319                     if (childPs != null) {
17320                         childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17321                     }
17322                     childRes.removedInfo.isUpdate = true;
17323                     childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17324                     childPackageUpdated = true;
17325                 }
17326             }
17327             if (!childPackageUpdated) {
17328                 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17329                 childRemovedRes.removedPackage = childPkg.packageName;
17330                 if (childPs != null) {
17331                     childRemovedRes.installerPackageName = childPs.installerPackageName;
17332                 }
17333                 childRemovedRes.isUpdate = false;
17334                 childRemovedRes.dataRemoved = true;
17335                 synchronized (mPackages) {
17336                     if (childPs != null) {
17337                         childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17338                     }
17339                 }
17340                 if (res.removedInfo.removedChildPackages == null) {
17341                     res.removedInfo.removedChildPackages = new ArrayMap<>();
17342                 }
17343                 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17344             }
17345         }
17346
17347         boolean sysPkg = (isSystemApp(oldPackage));
17348         if (sysPkg) {
17349             // Set the system/privileged flags as needed
17350             final boolean privileged =
17351                     (oldPackage.applicationInfo.privateFlags
17352                             & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17353             final int systemPolicyFlags = policyFlags
17354                     | PackageParser.PARSE_IS_SYSTEM
17355                     | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17356
17357             replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17358                     user, allUsers, installerPackageName, res, installReason);
17359         } else {
17360             replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17361                     user, allUsers, installerPackageName, res, installReason);
17362         }
17363     }
17364
17365     @Override
17366     public List<String> getPreviousCodePaths(String packageName) {
17367         final int callingUid = Binder.getCallingUid();
17368         final List<String> result = new ArrayList<>();
17369         if (getInstantAppPackageName(callingUid) != null) {
17370             return result;
17371         }
17372         final PackageSetting ps = mSettings.mPackages.get(packageName);
17373         if (ps != null
17374                 && ps.oldCodePaths != null
17375                 && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17376             result.addAll(ps.oldCodePaths);
17377         }
17378         return result;
17379     }
17380
17381     private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17382             PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17383             int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17384             int installReason) {
17385         if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17386                 + deletedPackage);
17387
17388         String pkgName = deletedPackage.packageName;
17389         boolean deletedPkg = true;
17390         boolean addedPkg = false;
17391         boolean updatedSettings = false;
17392         final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17393         final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17394                 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17395
17396         final long origUpdateTime = (pkg.mExtras != null)
17397                 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17398
17399         // First delete the existing package while retaining the data directory
17400         if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17401                 res.removedInfo, true, pkg)) {
17402             // If the existing package wasn't successfully deleted
17403             res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17404             deletedPkg = false;
17405         } else {
17406             // Successfully deleted the old package; proceed with replace.
17407
17408             // If deleted package lived in a container, give users a chance to
17409             // relinquish resources before killing.
17410             if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17411                 if (DEBUG_INSTALL) {
17412                     Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17413                 }
17414                 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17415                 final ArrayList<String> pkgList = new ArrayList<String>(1);
17416                 pkgList.add(deletedPackage.applicationInfo.packageName);
17417                 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17418             }
17419
17420             clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17421                     | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17422             clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17423
17424             try {
17425                 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17426                         scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17427                 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17428                         installReason);
17429
17430                 // Update the in-memory copy of the previous code paths.
17431                 PackageSetting ps = mSettings.mPackages.get(pkgName);
17432                 if (!killApp) {
17433                     if (ps.oldCodePaths == null) {
17434                         ps.oldCodePaths = new ArraySet<>();
17435                     }
17436                     Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17437                     if (deletedPackage.splitCodePaths != null) {
17438                         Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17439                     }
17440                 } else {
17441                     ps.oldCodePaths = null;
17442                 }
17443                 if (ps.childPackageNames != null) {
17444                     for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17445                         final String childPkgName = ps.childPackageNames.get(i);
17446                         final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17447                         childPs.oldCodePaths = ps.oldCodePaths;
17448                     }
17449                 }
17450                 // set instant app status, but, only if it's explicitly specified
17451                 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17452                 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17453                 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17454                 prepareAppDataAfterInstallLIF(newPackage);
17455                 addedPkg = true;
17456                 mDexManager.notifyPackageUpdated(newPackage.packageName,
17457                         newPackage.baseCodePath, newPackage.splitCodePaths);
17458             } catch (PackageManagerException e) {
17459                 res.setError("Package couldn't be installed in " + pkg.codePath, e);
17460             }
17461         }
17462
17463         if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17464             if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17465
17466             // Revert all internal state mutations and added folders for the failed install
17467             if (addedPkg) {
17468                 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17469                         res.removedInfo, true, null);
17470             }
17471
17472             // Restore the old package
17473             if (deletedPkg) {
17474                 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17475                 File restoreFile = new File(deletedPackage.codePath);
17476                 // Parse old package
17477                 boolean oldExternal = isExternal(deletedPackage);
17478                 int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17479                         (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17480                         (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17481                 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17482                 try {
17483                     scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17484                             null);
17485                 } catch (PackageManagerException e) {
17486                     Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17487                             + e.getMessage());
17488                     return;
17489                 }
17490
17491                 synchronized (mPackages) {
17492                     // Ensure the installer package name up to date
17493                     setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17494
17495                     // Update permissions for restored package
17496                     updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17497
17498                     mSettings.writeLPr();
17499                 }
17500
17501                 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17502             }
17503         } else {
17504             synchronized (mPackages) {
17505                 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17506                 if (ps != null) {
17507                     res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17508                     if (res.removedInfo.removedChildPackages != null) {
17509                         final int childCount = res.removedInfo.removedChildPackages.size();
17510                         // Iterate in reverse as we may modify the collection
17511                         for (int i = childCount - 1; i >= 0; i--) {
17512                             String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17513                             if (res.addedChildPackages.containsKey(childPackageName)) {
17514                                 res.removedInfo.removedChildPackages.removeAt(i);
17515                             } else {
17516                                 PackageRemovedInfo childInfo = res.removedInfo
17517                                         .removedChildPackages.valueAt(i);
17518                                 childInfo.removedForAllUsers = mPackages.get(
17519                                         childInfo.removedPackage) == null;
17520                             }
17521                         }
17522                     }
17523                 }
17524             }
17525         }
17526     }
17527
17528     private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17529             PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17530             int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17531             int installReason) {
17532         if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17533                 + ", old=" + deletedPackage);
17534
17535         final boolean disabledSystem;
17536
17537         // Remove existing system package
17538         removePackageLI(deletedPackage, true);
17539
17540         synchronized (mPackages) {
17541             disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17542         }
17543         if (!disabledSystem) {
17544             // We didn't need to disable the .apk as a current system package,
17545             // which means we are replacing another update that is already
17546             // installed.  We need to make sure to delete the older one's .apk.
17547             res.removedInfo.args = createInstallArgsForExisting(0,
17548                     deletedPackage.applicationInfo.getCodePath(),
17549                     deletedPackage.applicationInfo.getResourcePath(),
17550                     getAppDexInstructionSets(deletedPackage.applicationInfo));
17551         } else {
17552             res.removedInfo.args = null;
17553         }
17554
17555         // Successfully disabled the old package. Now proceed with re-installation
17556         clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17557                 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17558         clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17559
17560         res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17561         pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17562                 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17563
17564         PackageParser.Package newPackage = null;
17565         try {
17566             // Add the package to the internal data structures
17567             newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17568
17569             // Set the update and install times
17570             PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17571             setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17572                     System.currentTimeMillis());
17573
17574             // Update the package dynamic state if succeeded
17575             if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17576                 // Now that the install succeeded make sure we remove data
17577                 // directories for any child package the update removed.
17578                 final int deletedChildCount = (deletedPackage.childPackages != null)
17579                         ? deletedPackage.childPackages.size() : 0;
17580                 final int newChildCount = (newPackage.childPackages != null)
17581                         ? newPackage.childPackages.size() : 0;
17582                 for (int i = 0; i < deletedChildCount; i++) {
17583                     PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17584                     boolean childPackageDeleted = true;
17585                     for (int j = 0; j < newChildCount; j++) {
17586                         PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17587                         if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17588                             childPackageDeleted = false;
17589                             break;
17590                         }
17591                     }
17592                     if (childPackageDeleted) {
17593                         PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17594                                 deletedChildPkg.packageName);
17595                         if (ps != null && res.removedInfo.removedChildPackages != null) {
17596                             PackageRemovedInfo removedChildRes = res.removedInfo
17597                                     .removedChildPackages.get(deletedChildPkg.packageName);
17598                             removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17599                             removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17600                         }
17601                     }
17602                 }
17603
17604                 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17605                         installReason);
17606                 prepareAppDataAfterInstallLIF(newPackage);
17607
17608                 mDexManager.notifyPackageUpdated(newPackage.packageName,
17609                             newPackage.baseCodePath, newPackage.splitCodePaths);
17610             }
17611         } catch (PackageManagerException e) {
17612             res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17613             res.setError("Package couldn't be installed in " + pkg.codePath, e);
17614         }
17615
17616         if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17617             // Re installation failed. Restore old information
17618             // Remove new pkg information
17619             if (newPackage != null) {
17620                 removeInstalledPackageLI(newPackage, true);
17621             }
17622             // Add back the old system package
17623             try {
17624                 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17625             } catch (PackageManagerException e) {
17626                 Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17627             }
17628
17629             synchronized (mPackages) {
17630                 if (disabledSystem) {
17631                     enableSystemPackageLPw(deletedPackage);
17632                 }
17633
17634                 // Ensure the installer package name up to date
17635                 setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17636
17637                 // Update permissions for restored package
17638                 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17639
17640                 mSettings.writeLPr();
17641             }
17642
17643             Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17644                     + " after failed upgrade");
17645         }
17646     }
17647
17648     /**
17649      * Checks whether the parent or any of the child packages have a change shared
17650      * user. For a package to be a valid update the shred users of the parent and
17651      * the children should match. We may later support changing child shared users.
17652      * @param oldPkg The updated package.
17653      * @param newPkg The update package.
17654      * @return The shared user that change between the versions.
17655      */
17656     private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17657             PackageParser.Package newPkg) {
17658         // Check parent shared user
17659         if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17660             return newPkg.packageName;
17661         }
17662         // Check child shared users
17663         final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17664         final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17665         for (int i = 0; i < newChildCount; i++) {
17666             PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17667             // If this child was present, did it have the same shared user?
17668             for (int j = 0; j < oldChildCount; j++) {
17669                 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17670                 if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17671                         && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17672                     return newChildPkg.packageName;
17673                 }
17674             }
17675         }
17676         return null;
17677     }
17678
17679     private void removeNativeBinariesLI(PackageSetting ps) {
17680         // Remove the lib path for the parent package
17681         if (ps != null) {
17682             NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17683             // Remove the lib path for the child packages
17684             final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17685             for (int i = 0; i < childCount; i++) {
17686                 PackageSetting childPs = null;
17687                 synchronized (mPackages) {
17688                     childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17689                 }
17690                 if (childPs != null) {
17691                     NativeLibraryHelper.removeNativeBinariesLI(childPs
17692                             .legacyNativeLibraryPathString);
17693                 }
17694             }
17695         }
17696     }
17697
17698     private void enableSystemPackageLPw(PackageParser.Package pkg) {
17699         // Enable the parent package
17700         mSettings.enableSystemPackageLPw(pkg.packageName);
17701         // Enable the child packages
17702         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17703         for (int i = 0; i < childCount; i++) {
17704             PackageParser.Package childPkg = pkg.childPackages.get(i);
17705             mSettings.enableSystemPackageLPw(childPkg.packageName);
17706         }
17707     }
17708
17709     private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17710             PackageParser.Package newPkg) {
17711         // Disable the parent package (parent always replaced)
17712         boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17713         // Disable the child packages
17714         final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17715         for (int i = 0; i < childCount; i++) {
17716             PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17717             final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17718             disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17719         }
17720         return disabled;
17721     }
17722
17723     private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17724             String installerPackageName) {
17725         // Enable the parent package
17726         mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17727         // Enable the child packages
17728         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17729         for (int i = 0; i < childCount; i++) {
17730             PackageParser.Package childPkg = pkg.childPackages.get(i);
17731             mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17732         }
17733     }
17734
17735     private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17736         // Collect all used permissions in the UID
17737         ArraySet<String> usedPermissions = new ArraySet<>();
17738         final int packageCount = su.packages.size();
17739         for (int i = 0; i < packageCount; i++) {
17740             PackageSetting ps = su.packages.valueAt(i);
17741             if (ps.pkg == null) {
17742                 continue;
17743             }
17744             final int requestedPermCount = ps.pkg.requestedPermissions.size();
17745             for (int j = 0; j < requestedPermCount; j++) {
17746                 String permission = ps.pkg.requestedPermissions.get(j);
17747                 BasePermission bp = mSettings.mPermissions.get(permission);
17748                 if (bp != null) {
17749                     usedPermissions.add(permission);
17750                 }
17751             }
17752         }
17753
17754         PermissionsState permissionsState = su.getPermissionsState();
17755         // Prune install permissions
17756         List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17757         final int installPermCount = installPermStates.size();
17758         for (int i = installPermCount - 1; i >= 0;  i--) {
17759             PermissionState permissionState = installPermStates.get(i);
17760             if (!usedPermissions.contains(permissionState.getName())) {
17761                 BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17762                 if (bp != null) {
17763                     permissionsState.revokeInstallPermission(bp);
17764                     permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17765                             PackageManager.MASK_PERMISSION_FLAGS, 0);
17766                 }
17767             }
17768         }
17769
17770         int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17771
17772         // Prune runtime permissions
17773         for (int userId : allUserIds) {
17774             List<PermissionState> runtimePermStates = permissionsState
17775                     .getRuntimePermissionStates(userId);
17776             final int runtimePermCount = runtimePermStates.size();
17777             for (int i = runtimePermCount - 1; i >= 0; i--) {
17778                 PermissionState permissionState = runtimePermStates.get(i);
17779                 if (!usedPermissions.contains(permissionState.getName())) {
17780                     BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17781                     if (bp != null) {
17782                         permissionsState.revokeRuntimePermission(bp, userId);
17783                         permissionsState.updatePermissionFlags(bp, userId,
17784                                 PackageManager.MASK_PERMISSION_FLAGS, 0);
17785                         runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17786                                 runtimePermissionChangedUserIds, userId);
17787                     }
17788                 }
17789             }
17790         }
17791
17792         return runtimePermissionChangedUserIds;
17793     }
17794
17795     private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17796             int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17797         // Update the parent package setting
17798         updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17799                 res, user, installReason);
17800         // Update the child packages setting
17801         final int childCount = (newPackage.childPackages != null)
17802                 ? newPackage.childPackages.size() : 0;
17803         for (int i = 0; i < childCount; i++) {
17804             PackageParser.Package childPackage = newPackage.childPackages.get(i);
17805             PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17806             updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17807                     childRes.origUsers, childRes, user, installReason);
17808         }
17809     }
17810
17811     private void updateSettingsInternalLI(PackageParser.Package newPackage,
17812             String installerPackageName, int[] allUsers, int[] installedForUsers,
17813             PackageInstalledInfo res, UserHandle user, int installReason) {
17814         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17815
17816         String pkgName = newPackage.packageName;
17817         synchronized (mPackages) {
17818             //write settings. the installStatus will be incomplete at this stage.
17819             //note that the new package setting would have already been
17820             //added to mPackages. It hasn't been persisted yet.
17821             mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17822             // TODO: Remove this write? It's also written at the end of this method
17823             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17824             mSettings.writeLPr();
17825             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17826         }
17827
17828         if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17829         synchronized (mPackages) {
17830             updatePermissionsLPw(newPackage.packageName, newPackage,
17831                     UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17832                             ? UPDATE_PERMISSIONS_ALL : 0));
17833             // For system-bundled packages, we assume that installing an upgraded version
17834             // of the package implies that the user actually wants to run that new code,
17835             // so we enable the package.
17836             PackageSetting ps = mSettings.mPackages.get(pkgName);
17837             final int userId = user.getIdentifier();
17838             if (ps != null) {
17839                 if (isSystemApp(newPackage)) {
17840                     if (DEBUG_INSTALL) {
17841                         Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17842                     }
17843                     // Enable system package for requested users
17844                     if (res.origUsers != null) {
17845                         for (int origUserId : res.origUsers) {
17846                             if (userId == UserHandle.USER_ALL || userId == origUserId) {
17847                                 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17848                                         origUserId, installerPackageName);
17849                             }
17850                         }
17851                     }
17852                     // Also convey the prior install/uninstall state
17853                     if (allUsers != null && installedForUsers != null) {
17854                         for (int currentUserId : allUsers) {
17855                             final boolean installed = ArrayUtils.contains(
17856                                     installedForUsers, currentUserId);
17857                             if (DEBUG_INSTALL) {
17858                                 Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17859                             }
17860                             ps.setInstalled(installed, currentUserId);
17861                         }
17862                         // these install state changes will be persisted in the
17863                         // upcoming call to mSettings.writeLPr().
17864                     }
17865                 }
17866                 // It's implied that when a user requests installation, they want the app to be
17867                 // installed and enabled.
17868                 if (userId != UserHandle.USER_ALL) {
17869                     ps.setInstalled(true, userId);
17870                     ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17871                 }
17872
17873                 // When replacing an existing package, preserve the original install reason for all
17874                 // users that had the package installed before.
17875                 final Set<Integer> previousUserIds = new ArraySet<>();
17876                 if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17877                     final int installReasonCount = res.removedInfo.installReasons.size();
17878                     for (int i = 0; i < installReasonCount; i++) {
17879                         final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17880                         final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17881                         ps.setInstallReason(previousInstallReason, previousUserId);
17882                         previousUserIds.add(previousUserId);
17883                     }
17884                 }
17885
17886                 // Set install reason for users that are having the package newly installed.
17887                 if (userId == UserHandle.USER_ALL) {
17888                     for (int currentUserId : sUserManager.getUserIds()) {
17889                         if (!previousUserIds.contains(currentUserId)) {
17890                             ps.setInstallReason(installReason, currentUserId);
17891                         }
17892                     }
17893                 } else if (!previousUserIds.contains(userId)) {
17894                     ps.setInstallReason(installReason, userId);
17895                 }
17896                 mSettings.writeKernelMappingLPr(ps);
17897             }
17898             res.name = pkgName;
17899             res.uid = newPackage.applicationInfo.uid;
17900             res.pkg = newPackage;
17901             mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17902             mSettings.setInstallerPackageName(pkgName, installerPackageName);
17903             res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17904             //to update install status
17905             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17906             mSettings.writeLPr();
17907             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17908         }
17909
17910         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17911     }
17912
17913     private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17914         try {
17915             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17916             installPackageLI(args, res);
17917         } finally {
17918             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17919         }
17920     }
17921
17922     private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17923         final int installFlags = args.installFlags;
17924         final String installerPackageName = args.installerPackageName;
17925         final String volumeUuid = args.volumeUuid;
17926         final File tmpPackageFile = new File(args.getCodePath());
17927         final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17928         final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17929                 || (args.volumeUuid != null));
17930         final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17931         final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17932         final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17933         boolean replace = false;
17934         int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17935         if (args.move != null) {
17936             // moving a complete application; perform an initial scan on the new install location
17937             scanFlags |= SCAN_INITIAL;
17938         }
17939         if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17940             scanFlags |= SCAN_DONT_KILL_APP;
17941         }
17942         if (instantApp) {
17943             scanFlags |= SCAN_AS_INSTANT_APP;
17944         }
17945         if (fullApp) {
17946             scanFlags |= SCAN_AS_FULL_APP;
17947         }
17948
17949         // Result object to be returned
17950         res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17951
17952         if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17953
17954         // Sanity check
17955         if (instantApp && (forwardLocked || onExternal)) {
17956             Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17957                     + " external=" + onExternal);
17958             res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17959             return;
17960         }
17961
17962         // Retrieve PackageSettings and parse package
17963         final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17964                 | PackageParser.PARSE_ENFORCE_CODE
17965                 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17966                 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17967                 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17968                 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17969         PackageParser pp = new PackageParser();
17970         pp.setSeparateProcesses(mSeparateProcesses);
17971         pp.setDisplayMetrics(mMetrics);
17972         pp.setCallback(mPackageParserCallback);
17973
17974         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17975         final PackageParser.Package pkg;
17976         try {
17977             pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17978         } catch (PackageParserException e) {
17979             res.setError("Failed parse during installPackageLI", e);
17980             return;
17981         } finally {
17982             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17983         }
17984
17985         // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17986         if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17987             Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17988             res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17989                     "Instant app package must target O");
17990             return;
17991         }
17992         if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17993             Slog.w(TAG, "Instant app package " + pkg.packageName
17994                     + " does not target targetSandboxVersion 2");
17995             res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17996                     "Instant app package must use targetSanboxVersion 2");
17997             return;
17998         }
17999
18000         if (pkg.applicationInfo.isStaticSharedLibrary()) {
18001             // Static shared libraries have synthetic package names
18002             renameStaticSharedLibraryPackage(pkg);
18003
18004             // No static shared libs on external storage
18005             if (onExternal) {
18006                 Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18007                 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18008                         "Packages declaring static-shared libs cannot be updated");
18009                 return;
18010             }
18011         }
18012
18013         // If we are installing a clustered package add results for the children
18014         if (pkg.childPackages != null) {
18015             synchronized (mPackages) {
18016                 final int childCount = pkg.childPackages.size();
18017                 for (int i = 0; i < childCount; i++) {
18018                     PackageParser.Package childPkg = pkg.childPackages.get(i);
18019                     PackageInstalledInfo childRes = new PackageInstalledInfo();
18020                     childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18021                     childRes.pkg = childPkg;
18022                     childRes.name = childPkg.packageName;
18023                     PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18024                     if (childPs != null) {
18025                         childRes.origUsers = childPs.queryInstalledUsers(
18026                                 sUserManager.getUserIds(), true);
18027                     }
18028                     if ((mPackages.containsKey(childPkg.packageName))) {
18029                         childRes.removedInfo = new PackageRemovedInfo(this);
18030                         childRes.removedInfo.removedPackage = childPkg.packageName;
18031                         childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18032                     }
18033                     if (res.addedChildPackages == null) {
18034                         res.addedChildPackages = new ArrayMap<>();
18035                     }
18036                     res.addedChildPackages.put(childPkg.packageName, childRes);
18037                 }
18038             }
18039         }
18040
18041         // If package doesn't declare API override, mark that we have an install
18042         // time CPU ABI override.
18043         if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18044             pkg.cpuAbiOverride = args.abiOverride;
18045         }
18046
18047         String pkgName = res.name = pkg.packageName;
18048         if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18049             if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18050                 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18051                 return;
18052             }
18053         }
18054
18055         try {
18056             // either use what we've been given or parse directly from the APK
18057             if (args.certificates != null) {
18058                 try {
18059                     PackageParser.populateCertificates(pkg, args.certificates);
18060                 } catch (PackageParserException e) {
18061                     // there was something wrong with the certificates we were given;
18062                     // try to pull them from the APK
18063                     PackageParser.collectCertificates(pkg, parseFlags);
18064                 }
18065             } else {
18066                 PackageParser.collectCertificates(pkg, parseFlags);
18067             }
18068         } catch (PackageParserException e) {
18069             res.setError("Failed collect during installPackageLI", e);
18070             return;
18071         }
18072
18073         // Get rid of all references to package scan path via parser.
18074         pp = null;
18075         String oldCodePath = null;
18076         boolean systemApp = false;
18077         synchronized (mPackages) {
18078             // Check if installing already existing package
18079             if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18080                 String oldName = mSettings.getRenamedPackageLPr(pkgName);
18081                 if (pkg.mOriginalPackages != null
18082                         && pkg.mOriginalPackages.contains(oldName)
18083                         && mPackages.containsKey(oldName)) {
18084                     // This package is derived from an original package,
18085                     // and this device has been updating from that original
18086                     // name.  We must continue using the original name, so
18087                     // rename the new package here.
18088                     pkg.setPackageName(oldName);
18089                     pkgName = pkg.packageName;
18090                     replace = true;
18091                     if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18092                             + oldName + " pkgName=" + pkgName);
18093                 } else if (mPackages.containsKey(pkgName)) {
18094                     // This package, under its official name, already exists
18095                     // on the device; we should replace it.
18096                     replace = true;
18097                     if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18098                 }
18099
18100                 // Child packages are installed through the parent package
18101                 if (pkg.parentPackage != null) {
18102                     res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18103                             "Package " + pkg.packageName + " is child of package "
18104                                     + pkg.parentPackage.parentPackage + ". Child packages "
18105                                     + "can be updated only through the parent package.");
18106                     return;
18107                 }
18108
18109                 if (replace) {
18110                     // Prevent apps opting out from runtime permissions
18111                     PackageParser.Package oldPackage = mPackages.get(pkgName);
18112                     final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18113                     final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18114                     if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18115                             && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18116                         res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18117                                 "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18118                                         + " doesn't support runtime permissions but the old"
18119                                         + " target SDK " + oldTargetSdk + " does.");
18120                         return;
18121                     }
18122                     // Prevent apps from downgrading their targetSandbox.
18123                     final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18124                     final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18125                     if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18126                         res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18127                                 "Package " + pkg.packageName + " new target sandbox "
18128                                 + newTargetSandbox + " is incompatible with the previous value of"
18129                                 + oldTargetSandbox + ".");
18130                         return;
18131                     }
18132
18133                     // Prevent installing of child packages
18134                     if (oldPackage.parentPackage != null) {
18135                         res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18136                                 "Package " + pkg.packageName + " is child of package "
18137                                         + oldPackage.parentPackage + ". Child packages "
18138                                         + "can be updated only through the parent package.");
18139                         return;
18140                     }
18141                 }
18142             }
18143
18144             PackageSetting ps = mSettings.mPackages.get(pkgName);
18145             if (ps != null) {
18146                 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18147
18148                 // Static shared libs have same package with different versions where
18149                 // we internally use a synthetic package name to allow multiple versions
18150                 // of the same package, therefore we need to compare signatures against
18151                 // the package setting for the latest library version.
18152                 PackageSetting signatureCheckPs = ps;
18153                 if (pkg.applicationInfo.isStaticSharedLibrary()) {
18154                     SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18155                     if (libraryEntry != null) {
18156                         signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18157                     }
18158                 }
18159
18160                 // Quick sanity check that we're signed correctly if updating;
18161                 // we'll check this again later when scanning, but we want to
18162                 // bail early here before tripping over redefined permissions.
18163                 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18164                     if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18165                         res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18166                                 + pkg.packageName + " upgrade keys do not match the "
18167                                 + "previously installed version");
18168                         return;
18169                     }
18170                 } else {
18171                     try {
18172                         verifySignaturesLP(signatureCheckPs, pkg);
18173                     } catch (PackageManagerException e) {
18174                         res.setError(e.error, e.getMessage());
18175                         return;
18176                     }
18177                 }
18178
18179                 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18180                 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18181                     systemApp = (ps.pkg.applicationInfo.flags &
18182                             ApplicationInfo.FLAG_SYSTEM) != 0;
18183                 }
18184                 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18185             }
18186
18187             int N = pkg.permissions.size();
18188             for (int i = N-1; i >= 0; i--) {
18189                 PackageParser.Permission perm = pkg.permissions.get(i);
18190                 BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18191
18192                 // Don't allow anyone but the system to define ephemeral permissions.
18193                 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18194                         && !systemApp) {
18195                     Slog.w(TAG, "Non-System package " + pkg.packageName
18196                             + " attempting to delcare ephemeral permission "
18197                             + perm.info.name + "; Removing ephemeral.");
18198                     perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18199                 }
18200                 // Check whether the newly-scanned package wants to define an already-defined perm
18201                 if (bp != null) {
18202                     // If the defining package is signed with our cert, it's okay.  This
18203                     // also includes the "updating the same package" case, of course.
18204                     // "updating same package" could also involve key-rotation.
18205                     final boolean sigsOk;
18206                     if (bp.sourcePackage.equals(pkg.packageName)
18207                             && (bp.packageSetting instanceof PackageSetting)
18208                             && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18209                                     scanFlags))) {
18210                         sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18211                     } else {
18212                         sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18213                                 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18214                     }
18215                     if (!sigsOk) {
18216                         // If the owning package is the system itself, we log but allow
18217                         // install to proceed; we fail the install on all other permission
18218                         // redefinitions.
18219                         if (!bp.sourcePackage.equals("android")) {
18220                             res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18221                                     + pkg.packageName + " attempting to redeclare permission "
18222                                     + perm.info.name + " already owned by " + bp.sourcePackage);
18223                             res.origPermission = perm.info.name;
18224                             res.origPackage = bp.sourcePackage;
18225                             return;
18226                         } else {
18227                             Slog.w(TAG, "Package " + pkg.packageName
18228                                     + " attempting to redeclare system permission "
18229                                     + perm.info.name + "; ignoring new declaration");
18230                             pkg.permissions.remove(i);
18231                         }
18232                     } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18233                         // Prevent apps to change protection level to dangerous from any other
18234                         // type as this would allow a privilege escalation where an app adds a
18235                         // normal/signature permission in other app's group and later redefines
18236                         // it as dangerous leading to the group auto-grant.
18237                         if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18238                                 == PermissionInfo.PROTECTION_DANGEROUS) {
18239                             if (bp != null && !bp.isRuntime()) {
18240                                 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18241                                         + "non-runtime permission " + perm.info.name
18242                                         + " to runtime; keeping old protection level");
18243                                 perm.info.protectionLevel = bp.protectionLevel;
18244                             }
18245                         }
18246                     }
18247                 }
18248             }
18249         }
18250
18251         if (systemApp) {
18252             if (onExternal) {
18253                 // Abort update; system app can't be replaced with app on sdcard
18254                 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18255                         "Cannot install updates to system apps on sdcard");
18256                 return;
18257             } else if (instantApp) {
18258                 // Abort update; system app can't be replaced with an instant app
18259                 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18260                         "Cannot update a system app with an instant app");
18261                 return;
18262             }
18263         }
18264
18265         if (args.move != null) {
18266             // We did an in-place move, so dex is ready to roll
18267             scanFlags |= SCAN_NO_DEX;
18268             scanFlags |= SCAN_MOVE;
18269
18270             synchronized (mPackages) {
18271                 final PackageSetting ps = mSettings.mPackages.get(pkgName);
18272                 if (ps == null) {
18273                     res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18274                             "Missing settings for moved package " + pkgName);
18275                 }
18276
18277                 // We moved the entire application as-is, so bring over the
18278                 // previously derived ABI information.
18279                 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18280                 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18281             }
18282
18283         } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18284             // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18285             scanFlags |= SCAN_NO_DEX;
18286
18287             try {
18288                 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18289                     args.abiOverride : pkg.cpuAbiOverride);
18290                 final boolean extractNativeLibs = !pkg.isLibrary();
18291                 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18292                         extractNativeLibs, mAppLib32InstallDir);
18293             } catch (PackageManagerException pme) {
18294                 Slog.e(TAG, "Error deriving application ABI", pme);
18295                 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18296                 return;
18297             }
18298
18299             // Shared libraries for the package need to be updated.
18300             synchronized (mPackages) {
18301                 try {
18302                     updateSharedLibrariesLPr(pkg, null);
18303                 } catch (PackageManagerException e) {
18304                     Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18305                 }
18306             }
18307
18308             // dexopt can take some time to complete, so, for instant apps, we skip this
18309             // step during installation. Instead, we'll take extra time the first time the
18310             // instant app starts. It's preferred to do it this way to provide continuous
18311             // progress to the user instead of mysteriously blocking somewhere in the
18312             // middle of running an instant app. The default behaviour can be overridden
18313             // via gservices.
18314             if (!instantApp || Global.getInt(
18315                         mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18316                 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18317                 // Do not run PackageDexOptimizer through the local performDexOpt
18318                 // method because `pkg` may not be in `mPackages` yet.
18319                 //
18320                 // Also, don't fail application installs if the dexopt step fails.
18321                 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18322                         null /* instructionSets */, false /* checkProfiles */,
18323                         getCompilerFilterForReason(REASON_INSTALL),
18324                         getOrCreateCompilerPackageStats(pkg),
18325                         mDexManager.isUsedByOtherApps(pkg.packageName));
18326                 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18327             }
18328
18329             // Notify BackgroundDexOptService that the package has been changed.
18330             // If this is an update of a package which used to fail to compile,
18331             // BDOS will remove it from its blacklist.
18332             // TODO: Layering violation
18333             BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18334         }
18335
18336         if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18337             res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18338             return;
18339         }
18340
18341         startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18342
18343         try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18344                 "installPackageLI")) {
18345             if (replace) {
18346                 if (pkg.applicationInfo.isStaticSharedLibrary()) {
18347                     // Static libs have a synthetic package name containing the version
18348                     // and cannot be updated as an update would get a new package name,
18349                     // unless this is the exact same version code which is useful for
18350                     // development.
18351                     PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18352                     if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18353                         res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18354                                 + "static-shared libs cannot be updated");
18355                         return;
18356                     }
18357                 }
18358                 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18359                         installerPackageName, res, args.installReason);
18360             } else {
18361                 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18362                         args.user, installerPackageName, volumeUuid, res, args.installReason);
18363             }
18364         }
18365
18366         synchronized (mPackages) {
18367             final PackageSetting ps = mSettings.mPackages.get(pkgName);
18368             if (ps != null) {
18369                 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18370                 ps.setUpdateAvailable(false /*updateAvailable*/);
18371             }
18372
18373             final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18374             for (int i = 0; i < childCount; i++) {
18375                 PackageParser.Package childPkg = pkg.childPackages.get(i);
18376                 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18377                 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18378                 if (childPs != null) {
18379                     childRes.newUsers = childPs.queryInstalledUsers(
18380                             sUserManager.getUserIds(), true);
18381                 }
18382             }
18383
18384             if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18385                 updateSequenceNumberLP(ps, res.newUsers);
18386                 updateInstantAppInstallerLocked(pkgName);
18387             }
18388         }
18389     }
18390
18391     private void startIntentFilterVerifications(int userId, boolean replacing,
18392             PackageParser.Package pkg) {
18393         if (mIntentFilterVerifierComponent == null) {
18394             Slog.w(TAG, "No IntentFilter verification will not be done as "
18395                     + "there is no IntentFilterVerifier available!");
18396             return;
18397         }
18398
18399         final int verifierUid = getPackageUid(
18400                 mIntentFilterVerifierComponent.getPackageName(),
18401                 MATCH_DEBUG_TRIAGED_MISSING,
18402                 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18403
18404         Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18405         msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18406         mHandler.sendMessage(msg);
18407
18408         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18409         for (int i = 0; i < childCount; i++) {
18410             PackageParser.Package childPkg = pkg.childPackages.get(i);
18411             msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18412             msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18413             mHandler.sendMessage(msg);
18414         }
18415     }
18416
18417     private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18418             PackageParser.Package pkg) {
18419         int size = pkg.activities.size();
18420         if (size == 0) {
18421             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18422                     "No activity, so no need to verify any IntentFilter!");
18423             return;
18424         }
18425
18426         final boolean hasDomainURLs = hasDomainURLs(pkg);
18427         if (!hasDomainURLs) {
18428             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18429                     "No domain URLs, so no need to verify any IntentFilter!");
18430             return;
18431         }
18432
18433         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18434                 + " if any IntentFilter from the " + size
18435                 + " Activities needs verification ...");
18436
18437         int count = 0;
18438         final String packageName = pkg.packageName;
18439
18440         synchronized (mPackages) {
18441             // If this is a new install and we see that we've already run verification for this
18442             // package, we have nothing to do: it means the state was restored from backup.
18443             if (!replacing) {
18444                 IntentFilterVerificationInfo ivi =
18445                         mSettings.getIntentFilterVerificationLPr(packageName);
18446                 if (ivi != null) {
18447                     if (DEBUG_DOMAIN_VERIFICATION) {
18448                         Slog.i(TAG, "Package " + packageName+ " already verified: status="
18449                                 + ivi.getStatusString());
18450                     }
18451                     return;
18452                 }
18453             }
18454
18455             // If any filters need to be verified, then all need to be.
18456             boolean needToVerify = false;
18457             for (PackageParser.Activity a : pkg.activities) {
18458                 for (ActivityIntentInfo filter : a.intents) {
18459                     if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18460                         if (DEBUG_DOMAIN_VERIFICATION) {
18461                             Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18462                         }
18463                         needToVerify = true;
18464                         break;
18465                     }
18466                 }
18467             }
18468
18469             if (needToVerify) {
18470                 final int verificationId = mIntentFilterVerificationToken++;
18471                 for (PackageParser.Activity a : pkg.activities) {
18472                     for (ActivityIntentInfo filter : a.intents) {
18473                         if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18474                             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18475                                     "Verification needed for IntentFilter:" + filter.toString());
18476                             mIntentFilterVerifier.addOneIntentFilterVerification(
18477                                     verifierUid, userId, verificationId, filter, packageName);
18478                             count++;
18479                         }
18480                     }
18481                 }
18482             }
18483         }
18484
18485         if (count > 0) {
18486             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18487                     + " IntentFilter verification" + (count > 1 ? "s" : "")
18488                     +  " for userId:" + userId);
18489             mIntentFilterVerifier.startVerifications(userId);
18490         } else {
18491             if (DEBUG_DOMAIN_VERIFICATION) {
18492                 Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18493             }
18494         }
18495     }
18496
18497     private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18498         final ComponentName cn  = filter.activity.getComponentName();
18499         final String packageName = cn.getPackageName();
18500
18501         IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18502                 packageName);
18503         if (ivi == null) {
18504             return true;
18505         }
18506         int status = ivi.getStatus();
18507         switch (status) {
18508             case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18509             case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18510                 return true;
18511
18512             default:
18513                 // Nothing to do
18514                 return false;
18515         }
18516     }
18517
18518     private static boolean isMultiArch(ApplicationInfo info) {
18519         return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18520     }
18521
18522     private static boolean isExternal(PackageParser.Package pkg) {
18523         return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18524     }
18525
18526     private static boolean isExternal(PackageSetting ps) {
18527         return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18528     }
18529
18530     private static boolean isSystemApp(PackageParser.Package pkg) {
18531         return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18532     }
18533
18534     private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18535         return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18536     }
18537
18538     private static boolean hasDomainURLs(PackageParser.Package pkg) {
18539         return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18540     }
18541
18542     private static boolean isSystemApp(PackageSetting ps) {
18543         return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18544     }
18545
18546     private static boolean isUpdatedSystemApp(PackageSetting ps) {
18547         return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18548     }
18549
18550     private int packageFlagsToInstallFlags(PackageSetting ps) {
18551         int installFlags = 0;
18552         if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18553             // This existing package was an external ASEC install when we have
18554             // the external flag without a UUID
18555             installFlags |= PackageManager.INSTALL_EXTERNAL;
18556         }
18557         if (ps.isForwardLocked()) {
18558             installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18559         }
18560         return installFlags;
18561     }
18562
18563     private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18564         if (isExternal(pkg)) {
18565             if (TextUtils.isEmpty(pkg.volumeUuid)) {
18566                 return StorageManager.UUID_PRIMARY_PHYSICAL;
18567             } else {
18568                 return pkg.volumeUuid;
18569             }
18570         } else {
18571             return StorageManager.UUID_PRIVATE_INTERNAL;
18572         }
18573     }
18574
18575     private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18576         if (isExternal(pkg)) {
18577             if (TextUtils.isEmpty(pkg.volumeUuid)) {
18578                 return mSettings.getExternalVersion();
18579             } else {
18580                 return mSettings.findOrCreateVersion(pkg.volumeUuid);
18581             }
18582         } else {
18583             return mSettings.getInternalVersion();
18584         }
18585     }
18586
18587     private void deleteTempPackageFiles() {
18588         final FilenameFilter filter = new FilenameFilter() {
18589             public boolean accept(File dir, String name) {
18590                 return name.startsWith("vmdl") && name.endsWith(".tmp");
18591             }
18592         };
18593         for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18594             file.delete();
18595         }
18596     }
18597
18598     @Override
18599     public void deletePackageAsUser(String packageName, int versionCode,
18600             IPackageDeleteObserver observer, int userId, int flags) {
18601         deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18602                 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18603     }
18604
18605     @Override
18606     public void deletePackageVersioned(VersionedPackage versionedPackage,
18607             final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18608         final int callingUid = Binder.getCallingUid();
18609         mContext.enforceCallingOrSelfPermission(
18610                 android.Manifest.permission.DELETE_PACKAGES, null);
18611         final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18612         Preconditions.checkNotNull(versionedPackage);
18613         Preconditions.checkNotNull(observer);
18614         Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18615                 PackageManager.VERSION_CODE_HIGHEST,
18616                 Integer.MAX_VALUE, "versionCode must be >= -1");
18617
18618         final String packageName = versionedPackage.getPackageName();
18619         final int versionCode = versionedPackage.getVersionCode();
18620         final String internalPackageName;
18621         synchronized (mPackages) {
18622             // Normalize package name to handle renamed packages and static libs
18623             internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18624                     versionedPackage.getVersionCode());
18625         }
18626
18627         final int uid = Binder.getCallingUid();
18628         if (!isOrphaned(internalPackageName)
18629                 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18630             try {
18631                 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18632                 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18633                 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18634                 observer.onUserActionRequired(intent);
18635             } catch (RemoteException re) {
18636             }
18637             return;
18638         }
18639         final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18640         final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18641         if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18642             mContext.enforceCallingOrSelfPermission(
18643                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18644                     "deletePackage for user " + userId);
18645         }
18646
18647         if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18648             try {
18649                 observer.onPackageDeleted(packageName,
18650                         PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18651             } catch (RemoteException re) {
18652             }
18653             return;
18654         }
18655
18656         if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18657             try {
18658                 observer.onPackageDeleted(packageName,
18659                         PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18660             } catch (RemoteException re) {
18661             }
18662             return;
18663         }
18664
18665         if (DEBUG_REMOVE) {
18666             Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18667                     + " deleteAllUsers: " + deleteAllUsers + " version="
18668                     + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18669                     ? "VERSION_CODE_HIGHEST" : versionCode));
18670         }
18671         // Queue up an async operation since the package deletion may take a little while.
18672         mHandler.post(new Runnable() {
18673             public void run() {
18674                 mHandler.removeCallbacks(this);
18675                 int returnCode;
18676                 final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18677                 boolean doDeletePackage = true;
18678                 if (ps != null) {
18679                     final boolean targetIsInstantApp =
18680                             ps.getInstantApp(UserHandle.getUserId(callingUid));
18681                     doDeletePackage = !targetIsInstantApp
18682                             || canViewInstantApps;
18683                 }
18684                 if (doDeletePackage) {
18685                     if (!deleteAllUsers) {
18686                         returnCode = deletePackageX(internalPackageName, versionCode,
18687                                 userId, deleteFlags);
18688                     } else {
18689                         int[] blockUninstallUserIds = getBlockUninstallForUsers(
18690                                 internalPackageName, users);
18691                         // If nobody is blocking uninstall, proceed with delete for all users
18692                         if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18693                             returnCode = deletePackageX(internalPackageName, versionCode,
18694                                     userId, deleteFlags);
18695                         } else {
18696                             // Otherwise uninstall individually for users with blockUninstalls=false
18697                             final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18698                             for (int userId : users) {
18699                                 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18700                                     returnCode = deletePackageX(internalPackageName, versionCode,
18701                                             userId, userFlags);
18702                                     if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18703                                         Slog.w(TAG, "Package delete failed for user " + userId
18704                                                 + ", returnCode " + returnCode);
18705                                     }
18706                                 }
18707                             }
18708                             // The app has only been marked uninstalled for certain users.
18709                             // We still need to report that delete was blocked
18710                             returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18711                         }
18712                     }
18713                 } else {
18714                     returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18715                 }
18716                 try {
18717                     observer.onPackageDeleted(packageName, returnCode, null);
18718                 } catch (RemoteException e) {
18719                     Log.i(TAG, "Observer no longer exists.");
18720                 } //end catch
18721             } //end run
18722         });
18723     }
18724
18725     private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18726         if (pkg.staticSharedLibName != null) {
18727             return pkg.manifestPackageName;
18728         }
18729         return pkg.packageName;
18730     }
18731
18732     private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18733         // Handle renamed packages
18734         String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18735         packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18736
18737         // Is this a static library?
18738         SparseArray<SharedLibraryEntry> versionedLib =
18739                 mStaticLibsByDeclaringPackage.get(packageName);
18740         if (versionedLib == null || versionedLib.size() <= 0) {
18741             return packageName;
18742         }
18743
18744         // Figure out which lib versions the caller can see
18745         SparseIntArray versionsCallerCanSee = null;
18746         final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18747         if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18748                 && callingAppId != Process.ROOT_UID) {
18749             versionsCallerCanSee = new SparseIntArray();
18750             String libName = versionedLib.valueAt(0).info.getName();
18751             String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18752             if (uidPackages != null) {
18753                 for (String uidPackage : uidPackages) {
18754                     PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18755                     final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18756                     if (libIdx >= 0) {
18757                         final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18758                         versionsCallerCanSee.append(libVersion, libVersion);
18759                     }
18760                 }
18761             }
18762         }
18763
18764         // Caller can see nothing - done
18765         if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18766             return packageName;
18767         }
18768
18769         // Find the version the caller can see and the app version code
18770         SharedLibraryEntry highestVersion = null;
18771         final int versionCount = versionedLib.size();
18772         for (int i = 0; i < versionCount; i++) {
18773             SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18774             if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18775                     libEntry.info.getVersion()) < 0) {
18776                 continue;
18777             }
18778             final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18779             if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18780                 if (libVersionCode == versionCode) {
18781                     return libEntry.apk;
18782                 }
18783             } else if (highestVersion == null) {
18784                 highestVersion = libEntry;
18785             } else if (libVersionCode  > highestVersion.info
18786                     .getDeclaringPackage().getVersionCode()) {
18787                 highestVersion = libEntry;
18788             }
18789         }
18790
18791         if (highestVersion != null) {
18792             return highestVersion.apk;
18793         }
18794
18795         return packageName;
18796     }
18797
18798     private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18799         if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18800               || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18801             return true;
18802         }
18803         final int callingUserId = UserHandle.getUserId(callingUid);
18804         // If the caller installed the pkgName, then allow it to silently uninstall.
18805         if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18806             return true;
18807         }
18808
18809         // Allow package verifier to silently uninstall.
18810         if (mRequiredVerifierPackage != null &&
18811                 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18812             return true;
18813         }
18814
18815         // Allow package uninstaller to silently uninstall.
18816         if (mRequiredUninstallerPackage != null &&
18817                 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18818             return true;
18819         }
18820
18821         // Allow storage manager to silently uninstall.
18822         if (mStorageManagerPackage != null &&
18823                 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18824             return true;
18825         }
18826         return false;
18827     }
18828
18829     private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18830         int[] result = EMPTY_INT_ARRAY;
18831         for (int userId : userIds) {
18832             if (getBlockUninstallForUser(packageName, userId)) {
18833                 result = ArrayUtils.appendInt(result, userId);
18834             }
18835         }
18836         return result;
18837     }
18838
18839     @Override
18840     public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18841         final int callingUid = Binder.getCallingUid();
18842         if (checkUidPermission(android.Manifest.permission.MANAGE_USERS, callingUid)
18843                 != PERMISSION_GRANTED) {
18844             EventLog.writeEvent(0x534e4554, "128599183", -1, "");
18845             throw new SecurityException(android.Manifest.permission.MANAGE_USERS
18846                     + " permission is required to call this API");
18847         }
18848         if (getInstantAppPackageName(callingUid) != null
18849                 && !isCallerSameApp(packageName, callingUid)) {
18850             return false;
18851         }
18852         return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18853     }
18854
18855     private boolean isPackageDeviceAdmin(String packageName, int userId) {
18856         IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18857                 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18858         try {
18859             if (dpm != null) {
18860                 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18861                         /* callingUserOnly =*/ false);
18862                 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18863                         : deviceOwnerComponentName.getPackageName();
18864                 // Does the package contains the device owner?
18865                 // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18866                 // this check is probably not needed, since DO should be registered as a device
18867                 // admin on some user too. (Original bug for this: b/17657954)
18868                 if (packageName.equals(deviceOwnerPackageName)) {
18869                     return true;
18870                 }
18871                 // Does it contain a device admin for any user?
18872                 int[] users;
18873                 if (userId == UserHandle.USER_ALL) {
18874                     users = sUserManager.getUserIds();
18875                 } else {
18876                     users = new int[]{userId};
18877                 }
18878                 for (int i = 0; i < users.length; ++i) {
18879                     if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18880                         return true;
18881                     }
18882                 }
18883             }
18884         } catch (RemoteException e) {
18885         }
18886         return false;
18887     }
18888
18889     private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18890         return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18891     }
18892
18893     /**
18894      *  This method is an internal method that could be get invoked either
18895      *  to delete an installed package or to clean up a failed installation.
18896      *  After deleting an installed package, a broadcast is sent to notify any
18897      *  listeners that the package has been removed. For cleaning up a failed
18898      *  installation, the broadcast is not necessary since the package's
18899      *  installation wouldn't have sent the initial broadcast either
18900      *  The key steps in deleting a package are
18901      *  deleting the package information in internal structures like mPackages,
18902      *  deleting the packages base directories through installd
18903      *  updating mSettings to reflect current status
18904      *  persisting settings for later use
18905      *  sending a broadcast if necessary
18906      */
18907     int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18908         final PackageRemovedInfo info = new PackageRemovedInfo(this);
18909         final boolean res;
18910
18911         final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18912                 ? UserHandle.USER_ALL : userId;
18913
18914         if (isPackageDeviceAdmin(packageName, removeUser)) {
18915             Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18916             return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18917         }
18918
18919         PackageSetting uninstalledPs = null;
18920         PackageParser.Package pkg = null;
18921
18922         // for the uninstall-updates case and restricted profiles, remember the per-
18923         // user handle installed state
18924         int[] allUsers;
18925         synchronized (mPackages) {
18926             uninstalledPs = mSettings.mPackages.get(packageName);
18927             if (uninstalledPs == null) {
18928                 Slog.w(TAG, "Not removing non-existent package " + packageName);
18929                 return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18930             }
18931
18932             if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18933                     && uninstalledPs.versionCode != versionCode) {
18934                 Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18935                         + uninstalledPs.versionCode + " != " + versionCode);
18936                 return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18937             }
18938
18939             // Static shared libs can be declared by any package, so let us not
18940             // allow removing a package if it provides a lib others depend on.
18941             pkg = mPackages.get(packageName);
18942
18943             allUsers = sUserManager.getUserIds();
18944
18945             if (pkg != null && pkg.staticSharedLibName != null) {
18946                 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18947                         pkg.staticSharedLibVersion);
18948                 if (libEntry != null) {
18949                     for (int currUserId : allUsers) {
18950                         if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18951                             continue;
18952                         }
18953                         List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18954                                 libEntry.info, 0, currUserId);
18955                         if (!ArrayUtils.isEmpty(libClientPackages)) {
18956                             Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18957                                     + " hosting lib " + libEntry.info.getName() + " version "
18958                                     + libEntry.info.getVersion() + " used by " + libClientPackages
18959                                     + " for user " + currUserId);
18960                             return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18961                         }
18962                     }
18963                 }
18964             }
18965
18966             info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18967         }
18968
18969         final int freezeUser;
18970         if (isUpdatedSystemApp(uninstalledPs)
18971                 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18972             // We're downgrading a system app, which will apply to all users, so
18973             // freeze them all during the downgrade
18974             freezeUser = UserHandle.USER_ALL;
18975         } else {
18976             freezeUser = removeUser;
18977         }
18978
18979         synchronized (mInstallLock) {
18980             if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18981             try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18982                     deleteFlags, "deletePackageX")) {
18983                 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18984                         deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18985             }
18986             synchronized (mPackages) {
18987                 if (res) {
18988                     if (pkg != null) {
18989                         mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18990                     }
18991                     updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18992                     updateInstantAppInstallerLocked(packageName);
18993                 }
18994             }
18995         }
18996
18997         if (res) {
18998             final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18999             info.sendPackageRemovedBroadcasts(killApp);
19000             info.sendSystemPackageUpdatedBroadcasts();
19001             info.sendSystemPackageAppearedBroadcasts();
19002         }
19003         // Force a gc here.
19004         Runtime.getRuntime().gc();
19005         // Delete the resources here after sending the broadcast to let
19006         // other processes clean up before deleting resources.
19007         if (info.args != null) {
19008             synchronized (mInstallLock) {
19009                 info.args.doPostDeleteLI(true);
19010             }
19011         }
19012
19013         return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19014     }
19015
19016     static class PackageRemovedInfo {
19017         final PackageSender packageSender;
19018         String removedPackage;
19019         String installerPackageName;
19020         int uid = -1;
19021         int removedAppId = -1;
19022         int[] origUsers;
19023         int[] removedUsers = null;
19024         int[] broadcastUsers = null;
19025         SparseArray<Integer> installReasons;
19026         boolean isRemovedPackageSystemUpdate = false;
19027         boolean isUpdate;
19028         boolean dataRemoved;
19029         boolean removedForAllUsers;
19030         boolean isStaticSharedLib;
19031         // Clean up resources deleted packages.
19032         InstallArgs args = null;
19033         ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19034         ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19035
19036         PackageRemovedInfo(PackageSender packageSender) {
19037             this.packageSender = packageSender;
19038         }
19039
19040         void sendPackageRemovedBroadcasts(boolean killApp) {
19041             sendPackageRemovedBroadcastInternal(killApp);
19042             final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19043             for (int i = 0; i < childCount; i++) {
19044                 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19045                 childInfo.sendPackageRemovedBroadcastInternal(killApp);
19046             }
19047         }
19048
19049         void sendSystemPackageUpdatedBroadcasts() {
19050             if (isRemovedPackageSystemUpdate) {
19051                 sendSystemPackageUpdatedBroadcastsInternal();
19052                 final int childCount = (removedChildPackages != null)
19053                         ? removedChildPackages.size() : 0;
19054                 for (int i = 0; i < childCount; i++) {
19055                     PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19056                     if (childInfo.isRemovedPackageSystemUpdate) {
19057                         childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19058                     }
19059                 }
19060             }
19061         }
19062
19063         void sendSystemPackageAppearedBroadcasts() {
19064             final int packageCount = (appearedChildPackages != null)
19065                     ? appearedChildPackages.size() : 0;
19066             for (int i = 0; i < packageCount; i++) {
19067                 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19068                 packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19069                     true, UserHandle.getAppId(installedInfo.uid),
19070                     installedInfo.newUsers);
19071             }
19072         }
19073
19074         private void sendSystemPackageUpdatedBroadcastsInternal() {
19075             Bundle extras = new Bundle(2);
19076             extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19077             extras.putBoolean(Intent.EXTRA_REPLACING, true);
19078             packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19079                 removedPackage, extras, 0, null /*targetPackage*/, null, null);
19080             packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19081                 removedPackage, extras, 0, null /*targetPackage*/, null, null);
19082             packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19083                 null, null, 0, removedPackage, null, null);
19084             if (installerPackageName != null) {
19085                 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19086                         removedPackage, extras, 0 /*flags*/,
19087                         installerPackageName, null, null);
19088                 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19089                         removedPackage, extras, 0 /*flags*/,
19090                         installerPackageName, null, null);
19091             }
19092         }
19093
19094         private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19095             // Don't send static shared library removal broadcasts as these
19096             // libs are visible only the the apps that depend on them an one
19097             // cannot remove the library if it has a dependency.
19098             if (isStaticSharedLib) {
19099                 return;
19100             }
19101             Bundle extras = new Bundle(2);
19102             extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19103             extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19104             extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19105             if (isUpdate || isRemovedPackageSystemUpdate) {
19106                 extras.putBoolean(Intent.EXTRA_REPLACING, true);
19107             }
19108             extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19109             if (removedPackage != null) {
19110                 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19111                     removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19112                 if (installerPackageName != null) {
19113                     packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19114                             removedPackage, extras, 0 /*flags*/,
19115                             installerPackageName, null, broadcastUsers);
19116                 }
19117                 if (dataRemoved && !isRemovedPackageSystemUpdate) {
19118                     packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19119                         removedPackage, extras,
19120                         Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19121                         null, null, broadcastUsers);
19122                 }
19123             }
19124             if (removedAppId >= 0) {
19125                 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras,
19126                         Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers);
19127             }
19128         }
19129
19130         void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19131             removedUsers = userIds;
19132             if (removedUsers == null) {
19133                 broadcastUsers = null;
19134                 return;
19135             }
19136
19137             broadcastUsers = EMPTY_INT_ARRAY;
19138             for (int i = userIds.length - 1; i >= 0; --i) {
19139                 final int userId = userIds[i];
19140                 if (deletedPackageSetting.getInstantApp(userId)) {
19141                     continue;
19142                 }
19143                 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19144             }
19145         }
19146     }
19147
19148     /*
19149      * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19150      * flag is not set, the data directory is removed as well.
19151      * make sure this flag is set for partially installed apps. If not its meaningless to
19152      * delete a partially installed application.
19153      */
19154     private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19155             PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19156         String packageName = ps.name;
19157         if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19158         // Retrieve object to delete permissions for shared user later on
19159         final PackageParser.Package deletedPkg;
19160         final PackageSetting deletedPs;
19161         // reader
19162         synchronized (mPackages) {
19163             deletedPkg = mPackages.get(packageName);
19164             deletedPs = mSettings.mPackages.get(packageName);
19165             if (outInfo != null) {
19166                 outInfo.removedPackage = packageName;
19167                 outInfo.installerPackageName = ps.installerPackageName;
19168                 outInfo.isStaticSharedLib = deletedPkg != null
19169                         && deletedPkg.staticSharedLibName != null;
19170                 outInfo.populateUsers(deletedPs == null ? null
19171                         : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19172             }
19173         }
19174
19175         removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19176
19177         if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19178             final PackageParser.Package resolvedPkg;
19179             if (deletedPkg != null) {
19180                 resolvedPkg = deletedPkg;
19181             } else {
19182                 // We don't have a parsed package when it lives on an ejected
19183                 // adopted storage device, so fake something together
19184                 resolvedPkg = new PackageParser.Package(ps.name);
19185                 resolvedPkg.setVolumeUuid(ps.volumeUuid);
19186             }
19187             destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19188                     StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19189             destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19190             if (outInfo != null) {
19191                 outInfo.dataRemoved = true;
19192             }
19193             schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19194         }
19195
19196         int removedAppId = -1;
19197
19198         // writer
19199         synchronized (mPackages) {
19200             boolean installedStateChanged = false;
19201             if (deletedPs != null) {
19202                 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19203                     clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19204                     clearDefaultBrowserIfNeeded(packageName);
19205                     mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19206                     removedAppId = mSettings.removePackageLPw(packageName);
19207                     if (outInfo != null) {
19208                         outInfo.removedAppId = removedAppId;
19209                     }
19210                     updatePermissionsLPw(deletedPs.name, null, 0);
19211                     if (deletedPs.sharedUser != null) {
19212                         // Remove permissions associated with package. Since runtime
19213                         // permissions are per user we have to kill the removed package
19214                         // or packages running under the shared user of the removed
19215                         // package if revoking the permissions requested only by the removed
19216                         // package is successful and this causes a change in gids.
19217                         for (int userId : UserManagerService.getInstance().getUserIds()) {
19218                             final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19219                                     userId);
19220                             if (userIdToKill == UserHandle.USER_ALL
19221                                     || userIdToKill >= UserHandle.USER_SYSTEM) {
19222                                 // If gids changed for this user, kill all affected packages.
19223                                 mHandler.post(new Runnable() {
19224                                     @Override
19225                                     public void run() {
19226                                         // This has to happen with no lock held.
19227                                         killApplication(deletedPs.name, deletedPs.appId,
19228                                                 KILL_APP_REASON_GIDS_CHANGED);
19229                                     }
19230                                 });
19231                                 break;
19232                             }
19233                         }
19234                     }
19235                     clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19236                 }
19237                 // make sure to preserve per-user disabled state if this removal was just
19238                 // a downgrade of a system app to the factory package
19239                 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19240                     if (DEBUG_REMOVE) {
19241                         Slog.d(TAG, "Propagating install state across downgrade");
19242                     }
19243                     for (int userId : allUserHandles) {
19244                         final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19245                         if (DEBUG_REMOVE) {
19246                             Slog.d(TAG, "    user " + userId + " => " + installed);
19247                         }
19248                         if (installed != ps.getInstalled(userId)) {
19249                             installedStateChanged = true;
19250                         }
19251                         ps.setInstalled(installed, userId);
19252                     }
19253                 }
19254             }
19255             // can downgrade to reader
19256             if (writeSettings) {
19257                 // Save settings now
19258                 mSettings.writeLPr();
19259             }
19260             if (installedStateChanged) {
19261                 mSettings.writeKernelMappingLPr(ps);
19262             }
19263         }
19264         if (removedAppId != -1) {
19265             // A user ID was deleted here. Go through all users and remove it
19266             // from KeyStore.
19267             removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19268         }
19269     }
19270
19271     static boolean locationIsPrivileged(File path) {
19272         try {
19273             final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19274                     .getCanonicalPath();
19275             return path.getCanonicalPath().startsWith(privilegedAppDir);
19276         } catch (IOException e) {
19277             Slog.e(TAG, "Unable to access code path " + path);
19278         }
19279         return false;
19280     }
19281
19282     /*
19283      * Tries to delete system package.
19284      */
19285     private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19286             PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19287             boolean writeSettings) {
19288         if (deletedPs.parentPackageName != null) {
19289             Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19290             return false;
19291         }
19292
19293         final boolean applyUserRestrictions
19294                 = (allUserHandles != null) && (outInfo.origUsers != null);
19295         final PackageSetting disabledPs;
19296         // Confirm if the system package has been updated
19297         // An updated system app can be deleted. This will also have to restore
19298         // the system pkg from system partition
19299         // reader
19300         synchronized (mPackages) {
19301             disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19302         }
19303
19304         if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19305                 + " disabledPs=" + disabledPs);
19306
19307         if (disabledPs == null) {
19308             Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19309             return false;
19310         } else if (DEBUG_REMOVE) {
19311             Slog.d(TAG, "Deleting system pkg from data partition");
19312         }
19313
19314         if (DEBUG_REMOVE) {
19315             if (applyUserRestrictions) {
19316                 Slog.d(TAG, "Remembering install states:");
19317                 for (int userId : allUserHandles) {
19318                     final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19319                     Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19320                 }
19321             }
19322         }
19323
19324         // Delete the updated package
19325         outInfo.isRemovedPackageSystemUpdate = true;
19326         if (outInfo.removedChildPackages != null) {
19327             final int childCount = (deletedPs.childPackageNames != null)
19328                     ? deletedPs.childPackageNames.size() : 0;
19329             for (int i = 0; i < childCount; i++) {
19330                 String childPackageName = deletedPs.childPackageNames.get(i);
19331                 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19332                         .contains(childPackageName)) {
19333                     PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19334                             childPackageName);
19335                     if (childInfo != null) {
19336                         childInfo.isRemovedPackageSystemUpdate = true;
19337                     }
19338                 }
19339             }
19340         }
19341
19342         if (disabledPs.versionCode < deletedPs.versionCode) {
19343             // Delete data for downgrades
19344             flags &= ~PackageManager.DELETE_KEEP_DATA;
19345         } else {
19346             // Preserve data by setting flag
19347             flags |= PackageManager.DELETE_KEEP_DATA;
19348         }
19349
19350         boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19351                 outInfo, writeSettings, disabledPs.pkg);
19352         if (!ret) {
19353             return false;
19354         }
19355
19356         // writer
19357         synchronized (mPackages) {
19358             // Reinstate the old system package
19359             enableSystemPackageLPw(disabledPs.pkg);
19360             // Remove any native libraries from the upgraded package.
19361             removeNativeBinariesLI(deletedPs);
19362         }
19363
19364         // Install the system package
19365         if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19366         int parseFlags = mDefParseFlags
19367                 | PackageParser.PARSE_MUST_BE_APK
19368                 | PackageParser.PARSE_IS_SYSTEM
19369                 | PackageParser.PARSE_IS_SYSTEM_DIR;
19370         if (locationIsPrivileged(disabledPs.codePath)) {
19371             parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19372         }
19373
19374         final PackageParser.Package newPkg;
19375         try {
19376             newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19377                 0 /* currentTime */, null);
19378         } catch (PackageManagerException e) {
19379             Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19380                     + e.getMessage());
19381             return false;
19382         }
19383
19384         try {
19385             // update shared libraries for the newly re-installed system package
19386             updateSharedLibrariesLPr(newPkg, null);
19387         } catch (PackageManagerException e) {
19388             Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19389         }
19390
19391         prepareAppDataAfterInstallLIF(newPkg);
19392
19393         // writer
19394         synchronized (mPackages) {
19395             PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19396
19397             // Propagate the permissions state as we do not want to drop on the floor
19398             // runtime permissions. The update permissions method below will take
19399             // care of removing obsolete permissions and grant install permissions.
19400             ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19401             updatePermissionsLPw(newPkg.packageName, newPkg,
19402                     UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19403
19404             if (applyUserRestrictions) {
19405                 boolean installedStateChanged = false;
19406                 if (DEBUG_REMOVE) {
19407                     Slog.d(TAG, "Propagating install state across reinstall");
19408                 }
19409                 for (int userId : allUserHandles) {
19410                     final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19411                     if (DEBUG_REMOVE) {
19412                         Slog.d(TAG, "    user " + userId + " => " + installed);
19413                     }
19414                     if (installed != ps.getInstalled(userId)) {
19415                         installedStateChanged = true;
19416                     }
19417                     ps.setInstalled(installed, userId);
19418
19419                     mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19420                 }
19421                 // Regardless of writeSettings we need to ensure that this restriction
19422                 // state propagation is persisted
19423                 mSettings.writeAllUsersPackageRestrictionsLPr();
19424                 if (installedStateChanged) {
19425                     mSettings.writeKernelMappingLPr(ps);
19426                 }
19427             }
19428             // can downgrade to reader here
19429             if (writeSettings) {
19430                 mSettings.writeLPr();
19431             }
19432         }
19433         return true;
19434     }
19435
19436     private boolean deleteInstalledPackageLIF(PackageSetting ps,
19437             boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19438             PackageRemovedInfo outInfo, boolean writeSettings,
19439             PackageParser.Package replacingPackage) {
19440         synchronized (mPackages) {
19441             if (outInfo != null) {
19442                 outInfo.uid = ps.appId;
19443             }
19444
19445             if (outInfo != null && outInfo.removedChildPackages != null) {
19446                 final int childCount = (ps.childPackageNames != null)
19447                         ? ps.childPackageNames.size() : 0;
19448                 for (int i = 0; i < childCount; i++) {
19449                     String childPackageName = ps.childPackageNames.get(i);
19450                     PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19451                     if (childPs == null) {
19452                         return false;
19453                     }
19454                     PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19455                             childPackageName);
19456                     if (childInfo != null) {
19457                         childInfo.uid = childPs.appId;
19458                     }
19459                 }
19460             }
19461         }
19462
19463         // Delete package data from internal structures and also remove data if flag is set
19464         removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19465
19466         // Delete the child packages data
19467         final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19468         for (int i = 0; i < childCount; i++) {
19469             PackageSetting childPs;
19470             synchronized (mPackages) {
19471                 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19472             }
19473             if (childPs != null) {
19474                 PackageRemovedInfo childOutInfo = (outInfo != null
19475                         && outInfo.removedChildPackages != null)
19476                         ? outInfo.removedChildPackages.get(childPs.name) : null;
19477                 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19478                         && (replacingPackage != null
19479                         && !replacingPackage.hasChildPackage(childPs.name))
19480                         ? flags & ~DELETE_KEEP_DATA : flags;
19481                 removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19482                         deleteFlags, writeSettings);
19483             }
19484         }
19485
19486         // Delete application code and resources only for parent packages
19487         if (ps.parentPackageName == null) {
19488             if (deleteCodeAndResources && (outInfo != null)) {
19489                 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19490                         ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19491                 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19492             }
19493         }
19494
19495         return true;
19496     }
19497
19498     @Override
19499     public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19500             int userId) {
19501         mContext.enforceCallingOrSelfPermission(
19502                 android.Manifest.permission.DELETE_PACKAGES, null);
19503         synchronized (mPackages) {
19504             // Cannot block uninstall of static shared libs as they are
19505             // considered a part of the using app (emulating static linking).
19506             // Also static libs are installed always on internal storage.
19507             PackageParser.Package pkg = mPackages.get(packageName);
19508             if (pkg != null && pkg.staticSharedLibName != null) {
19509                 Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19510                         + " providing static shared library: " + pkg.staticSharedLibName);
19511                 return false;
19512             }
19513             mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19514             mSettings.writePackageRestrictionsLPr(userId);
19515         }
19516         return true;
19517     }
19518
19519     @Override
19520     public boolean getBlockUninstallForUser(String packageName, int userId) {
19521         synchronized (mPackages) {
19522             final PackageSetting ps = mSettings.mPackages.get(packageName);
19523             if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19524                 return false;
19525             }
19526             return mSettings.getBlockUninstallLPr(userId, packageName);
19527         }
19528     }
19529
19530     @Override
19531     public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19532         enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19533         synchronized (mPackages) {
19534             PackageSetting ps = mSettings.mPackages.get(packageName);
19535             if (ps == null) {
19536                 Log.w(TAG, "Package doesn't exist: " + packageName);
19537                 return false;
19538             }
19539             if (systemUserApp) {
19540                 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19541             } else {
19542                 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19543             }
19544             mSettings.writeLPr();
19545         }
19546         return true;
19547     }
19548
19549     /*
19550      * This method handles package deletion in general
19551      */
19552     private boolean deletePackageLIF(String packageName, UserHandle user,
19553             boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19554             PackageRemovedInfo outInfo, boolean writeSettings,
19555             PackageParser.Package replacingPackage) {
19556         if (packageName == null) {
19557             Slog.w(TAG, "Attempt to delete null packageName.");
19558             return false;
19559         }
19560
19561         if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19562
19563         PackageSetting ps;
19564         synchronized (mPackages) {
19565             ps = mSettings.mPackages.get(packageName);
19566             if (ps == null) {
19567                 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19568                 return false;
19569             }
19570
19571             if (ps.parentPackageName != null && (!isSystemApp(ps)
19572                     || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19573                 if (DEBUG_REMOVE) {
19574                     Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19575                             + ((user == null) ? UserHandle.USER_ALL : user));
19576                 }
19577                 final int removedUserId = (user != null) ? user.getIdentifier()
19578                         : UserHandle.USER_ALL;
19579                 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19580                     return false;
19581                 }
19582                 markPackageUninstalledForUserLPw(ps, user);
19583                 scheduleWritePackageRestrictionsLocked(user);
19584                 return true;
19585             }
19586         }
19587
19588         if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19589                 && user.getIdentifier() != UserHandle.USER_ALL)) {
19590             // The caller is asking that the package only be deleted for a single
19591             // user.  To do this, we just mark its uninstalled state and delete
19592             // its data. If this is a system app, we only allow this to happen if
19593             // they have set the special DELETE_SYSTEM_APP which requests different
19594             // semantics than normal for uninstalling system apps.
19595             markPackageUninstalledForUserLPw(ps, user);
19596
19597             if (!isSystemApp(ps)) {
19598                 // Do not uninstall the APK if an app should be cached
19599                 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19600                 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19601                     // Other user still have this package installed, so all
19602                     // we need to do is clear this user's data and save that
19603                     // it is uninstalled.
19604                     if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19605                     if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19606                         return false;
19607                     }
19608                     scheduleWritePackageRestrictionsLocked(user);
19609                     return true;
19610                 } else {
19611                     // We need to set it back to 'installed' so the uninstall
19612                     // broadcasts will be sent correctly.
19613                     if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19614                     ps.setInstalled(true, user.getIdentifier());
19615                     mSettings.writeKernelMappingLPr(ps);
19616                 }
19617             } else {
19618                 // This is a system app, so we assume that the
19619                 // other users still have this package installed, so all
19620                 // we need to do is clear this user's data and save that
19621                 // it is uninstalled.
19622                 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19623                 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19624                     return false;
19625                 }
19626                 scheduleWritePackageRestrictionsLocked(user);
19627                 return true;
19628             }
19629         }
19630
19631         // If we are deleting a composite package for all users, keep track
19632         // of result for each child.
19633         if (ps.childPackageNames != null && outInfo != null) {
19634             synchronized (mPackages) {
19635                 final int childCount = ps.childPackageNames.size();
19636                 outInfo.removedChildPackages = new ArrayMap<>(childCount);
19637                 for (int i = 0; i < childCount; i++) {
19638                     String childPackageName = ps.childPackageNames.get(i);
19639                     PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19640                     childInfo.removedPackage = childPackageName;
19641                     childInfo.installerPackageName = ps.installerPackageName;
19642                     outInfo.removedChildPackages.put(childPackageName, childInfo);
19643                     PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19644                     if (childPs != null) {
19645                         childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19646                     }
19647                 }
19648             }
19649         }
19650
19651         boolean ret = false;
19652         if (isSystemApp(ps)) {
19653             if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19654             // When an updated system application is deleted we delete the existing resources
19655             // as well and fall back to existing code in system partition
19656             ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19657         } else {
19658             if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19659             ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19660                     outInfo, writeSettings, replacingPackage);
19661         }
19662
19663         // Take a note whether we deleted the package for all users
19664         if (outInfo != null) {
19665             outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19666             if (outInfo.removedChildPackages != null) {
19667                 synchronized (mPackages) {
19668                     final int childCount = outInfo.removedChildPackages.size();
19669                     for (int i = 0; i < childCount; i++) {
19670                         PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19671                         if (childInfo != null) {
19672                             childInfo.removedForAllUsers = mPackages.get(
19673                                     childInfo.removedPackage) == null;
19674                         }
19675                     }
19676                 }
19677             }
19678             // If we uninstalled an update to a system app there may be some
19679             // child packages that appeared as they are declared in the system
19680             // app but were not declared in the update.
19681             if (isSystemApp(ps)) {
19682                 synchronized (mPackages) {
19683                     PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19684                     final int childCount = (updatedPs.childPackageNames != null)
19685                             ? updatedPs.childPackageNames.size() : 0;
19686                     for (int i = 0; i < childCount; i++) {
19687                         String childPackageName = updatedPs.childPackageNames.get(i);
19688                         if (outInfo.removedChildPackages == null
19689                                 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19690                             PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19691                             if (childPs == null) {
19692                                 continue;
19693                             }
19694                             PackageInstalledInfo installRes = new PackageInstalledInfo();
19695                             installRes.name = childPackageName;
19696                             installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19697                             installRes.pkg = mPackages.get(childPackageName);
19698                             installRes.uid = childPs.pkg.applicationInfo.uid;
19699                             if (outInfo.appearedChildPackages == null) {
19700                                 outInfo.appearedChildPackages = new ArrayMap<>();
19701                             }
19702                             outInfo.appearedChildPackages.put(childPackageName, installRes);
19703                         }
19704                     }
19705                 }
19706             }
19707         }
19708
19709         return ret;
19710     }
19711
19712     private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19713         final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19714                 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19715         for (int nextUserId : userIds) {
19716             if (DEBUG_REMOVE) {
19717                 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19718             }
19719             ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19720                     false /*installed*/,
19721                     true /*stopped*/,
19722                     true /*notLaunched*/,
19723                     false /*hidden*/,
19724                     false /*suspended*/,
19725                     false /*instantApp*/,
19726                     null /*lastDisableAppCaller*/,
19727                     null /*enabledComponents*/,
19728                     null /*disabledComponents*/,
19729                     ps.readUserState(nextUserId).domainVerificationStatus,
19730                     0, PackageManager.INSTALL_REASON_UNKNOWN);
19731         }
19732         mSettings.writeKernelMappingLPr(ps);
19733     }
19734
19735     private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19736             PackageRemovedInfo outInfo) {
19737         final PackageParser.Package pkg;
19738         synchronized (mPackages) {
19739             pkg = mPackages.get(ps.name);
19740         }
19741
19742         final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19743                 : new int[] {userId};
19744         for (int nextUserId : userIds) {
19745             if (DEBUG_REMOVE) {
19746                 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19747                         + nextUserId);
19748             }
19749
19750             destroyAppDataLIF(pkg, userId,
19751                     StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19752             destroyAppProfilesLIF(pkg, userId);
19753             clearDefaultBrowserIfNeededForUser(ps.name, userId);
19754             removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19755             schedulePackageCleaning(ps.name, nextUserId, false);
19756             synchronized (mPackages) {
19757                 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19758                     scheduleWritePackageRestrictionsLocked(nextUserId);
19759                 }
19760                 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19761             }
19762         }
19763
19764         if (outInfo != null) {
19765             outInfo.removedPackage = ps.name;
19766             outInfo.installerPackageName = ps.installerPackageName;
19767             outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19768             outInfo.removedAppId = ps.appId;
19769             outInfo.removedUsers = userIds;
19770             outInfo.broadcastUsers = userIds;
19771         }
19772
19773         return true;
19774     }
19775
19776     private final class ClearStorageConnection implements ServiceConnection {
19777         IMediaContainerService mContainerService;
19778
19779         @Override
19780         public void onServiceConnected(ComponentName name, IBinder service) {
19781             synchronized (this) {
19782                 mContainerService = IMediaContainerService.Stub
19783                         .asInterface(Binder.allowBlocking(service));
19784                 notifyAll();
19785             }
19786         }
19787
19788         @Override
19789         public void onServiceDisconnected(ComponentName name) {
19790         }
19791     }
19792
19793     private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19794         if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19795
19796         final boolean mounted;
19797         if (Environment.isExternalStorageEmulated()) {
19798             mounted = true;
19799         } else {
19800             final String status = Environment.getExternalStorageState();
19801
19802             mounted = status.equals(Environment.MEDIA_MOUNTED)
19803                     || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19804         }
19805
19806         if (!mounted) {
19807             return;
19808         }
19809
19810         final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19811         int[] users;
19812         if (userId == UserHandle.USER_ALL) {
19813             users = sUserManager.getUserIds();
19814         } else {
19815             users = new int[] { userId };
19816         }
19817         final ClearStorageConnection conn = new ClearStorageConnection();
19818         if (mContext.bindServiceAsUser(
19819                 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19820             try {
19821                 for (int curUser : users) {
19822                     long timeout = SystemClock.uptimeMillis() + 5000;
19823                     synchronized (conn) {
19824                         long now;
19825                         while (conn.mContainerService == null &&
19826                                 (now = SystemClock.uptimeMillis()) < timeout) {
19827                             try {
19828                                 conn.wait(timeout - now);
19829                             } catch (InterruptedException e) {
19830                             }
19831                         }
19832                     }
19833                     if (conn.mContainerService == null) {
19834                         return;
19835                     }
19836
19837                     final UserEnvironment userEnv = new UserEnvironment(curUser);
19838                     clearDirectory(conn.mContainerService,
19839                             userEnv.buildExternalStorageAppCacheDirs(packageName));
19840                     if (allData) {
19841                         clearDirectory(conn.mContainerService,
19842                                 userEnv.buildExternalStorageAppDataDirs(packageName));
19843                         clearDirectory(conn.mContainerService,
19844                                 userEnv.buildExternalStorageAppMediaDirs(packageName));
19845                     }
19846                 }
19847             } finally {
19848                 mContext.unbindService(conn);
19849             }
19850         }
19851     }
19852
19853     @Override
19854     public void clearApplicationProfileData(String packageName) {
19855         enforceSystemOrRoot("Only the system can clear all profile data");
19856
19857         final PackageParser.Package pkg;
19858         synchronized (mPackages) {
19859             pkg = mPackages.get(packageName);
19860         }
19861
19862         try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19863             synchronized (mInstallLock) {
19864                 clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19865             }
19866         }
19867     }
19868
19869     @Override
19870     public void clearApplicationUserData(final String packageName,
19871             final IPackageDataObserver observer, final int userId) {
19872         mContext.enforceCallingOrSelfPermission(
19873                 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19874
19875         final int callingUid = Binder.getCallingUid();
19876         enforceCrossUserPermission(callingUid, userId,
19877                 true /* requireFullPermission */, false /* checkShell */, "clear application data");
19878
19879         final PackageSetting ps = mSettings.getPackageLPr(packageName);
19880         if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19881             return;
19882         }
19883         if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19884             throw new SecurityException("Cannot clear data for a protected package: "
19885                     + packageName);
19886         }
19887         // Queue up an async operation since the package deletion may take a little while.
19888         mHandler.post(new Runnable() {
19889             public void run() {
19890                 mHandler.removeCallbacks(this);
19891                 final boolean succeeded;
19892                 try (PackageFreezer freezer = freezePackage(packageName,
19893                         "clearApplicationUserData")) {
19894                     synchronized (mInstallLock) {
19895                         succeeded = clearApplicationUserDataLIF(packageName, userId);
19896                     }
19897                     clearExternalStorageDataSync(packageName, userId, true);
19898                     synchronized (mPackages) {
19899                         mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19900                                 packageName, userId);
19901                     }
19902                 }
19903                 if (succeeded) {
19904                     // invoke DeviceStorageMonitor's update method to clear any notifications
19905                     DeviceStorageMonitorInternal dsm = LocalServices
19906                             .getService(DeviceStorageMonitorInternal.class);
19907                     if (dsm != null) {
19908                         dsm.checkMemory();
19909                     }
19910                 }
19911                 if(observer != null) {
19912                     try {
19913                         observer.onRemoveCompleted(packageName, succeeded);
19914                     } catch (RemoteException e) {
19915                         Log.i(TAG, "Observer no longer exists.");
19916                     }
19917                 } //end if observer
19918             } //end run
19919         });
19920     }
19921
19922     private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19923         if (packageName == null) {
19924             Slog.w(TAG, "Attempt to delete null packageName.");
19925             return false;
19926         }
19927
19928         // Try finding details about the requested package
19929         PackageParser.Package pkg;
19930         synchronized (mPackages) {
19931             pkg = mPackages.get(packageName);
19932             if (pkg == null) {
19933                 final PackageSetting ps = mSettings.mPackages.get(packageName);
19934                 if (ps != null) {
19935                     pkg = ps.pkg;
19936                 }
19937             }
19938
19939             if (pkg == null) {
19940                 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19941                 return false;
19942             }
19943
19944             PackageSetting ps = (PackageSetting) pkg.mExtras;
19945             resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19946         }
19947
19948         clearAppDataLIF(pkg, userId,
19949                 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19950
19951         final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19952         removeKeystoreDataIfNeeded(userId, appId);
19953
19954         UserManagerInternal umInternal = getUserManagerInternal();
19955         final int flags;
19956         if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19957             flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19958         } else if (umInternal.isUserRunning(userId)) {
19959             flags = StorageManager.FLAG_STORAGE_DE;
19960         } else {
19961             flags = 0;
19962         }
19963         prepareAppDataContentsLIF(pkg, userId, flags);
19964
19965         return true;
19966     }
19967
19968     /**
19969      * Reverts user permission state changes (permissions and flags) in
19970      * all packages for a given user.
19971      *
19972      * @param userId The device user for which to do a reset.
19973      */
19974     private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19975         final int packageCount = mPackages.size();
19976         for (int i = 0; i < packageCount; i++) {
19977             PackageParser.Package pkg = mPackages.valueAt(i);
19978             PackageSetting ps = (PackageSetting) pkg.mExtras;
19979             resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19980         }
19981     }
19982
19983     private void resetNetworkPolicies(int userId) {
19984         LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19985     }
19986
19987     /**
19988      * Reverts user permission state changes (permissions and flags).
19989      *
19990      * @param ps The package for which to reset.
19991      * @param userId The device user for which to do a reset.
19992      */
19993     private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19994             final PackageSetting ps, final int userId) {
19995         if (ps.pkg == null) {
19996             return;
19997         }
19998
19999         // These are flags that can change base on user actions.
20000         final int userSettableMask = FLAG_PERMISSION_USER_SET
20001                 | FLAG_PERMISSION_USER_FIXED
20002                 | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20003                 | FLAG_PERMISSION_REVIEW_REQUIRED;
20004
20005         final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20006                 | FLAG_PERMISSION_POLICY_FIXED;
20007
20008         boolean writeInstallPermissions = false;
20009         boolean writeRuntimePermissions = false;
20010
20011         final int permissionCount = ps.pkg.requestedPermissions.size();
20012         for (int i = 0; i < permissionCount; i++) {
20013             String permission = ps.pkg.requestedPermissions.get(i);
20014
20015             BasePermission bp = mSettings.mPermissions.get(permission);
20016             if (bp == null) {
20017                 continue;
20018             }
20019
20020             // If shared user we just reset the state to which only this app contributed.
20021             if (ps.sharedUser != null) {
20022                 boolean used = false;
20023                 final int packageCount = ps.sharedUser.packages.size();
20024                 for (int j = 0; j < packageCount; j++) {
20025                     PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20026                     if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20027                             && pkg.pkg.requestedPermissions.contains(permission)) {
20028                         used = true;
20029                         break;
20030                     }
20031                 }
20032                 if (used) {
20033                     continue;
20034                 }
20035             }
20036
20037             PermissionsState permissionsState = ps.getPermissionsState();
20038
20039             final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20040
20041             // Always clear the user settable flags.
20042             final boolean hasInstallState = permissionsState.getInstallPermissionState(
20043                     bp.name) != null;
20044             // If permission review is enabled and this is a legacy app, mark the
20045             // permission as requiring a review as this is the initial state.
20046             int flags = 0;
20047             if (mPermissionReviewRequired
20048                     && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20049                 flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20050             }
20051             if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20052                 if (hasInstallState) {
20053                     writeInstallPermissions = true;
20054                 } else {
20055                     writeRuntimePermissions = true;
20056                 }
20057             }
20058
20059             // Below is only runtime permission handling.
20060             if (!bp.isRuntime()) {
20061                 continue;
20062             }
20063
20064             // Never clobber system or policy.
20065             if ((oldFlags & policyOrSystemFlags) != 0) {
20066                 continue;
20067             }
20068
20069             // If this permission was granted by default, make sure it is.
20070             if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20071                 if (permissionsState.grantRuntimePermission(bp, userId)
20072                         != PERMISSION_OPERATION_FAILURE) {
20073                     writeRuntimePermissions = true;
20074                 }
20075             // If permission review is enabled the permissions for a legacy apps
20076             // are represented as constantly granted runtime ones, so don't revoke.
20077             } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20078                 // Otherwise, reset the permission.
20079                 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20080                 switch (revokeResult) {
20081                     case PERMISSION_OPERATION_SUCCESS:
20082                     case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20083                         writeRuntimePermissions = true;
20084                         final int appId = ps.appId;
20085                         mHandler.post(new Runnable() {
20086                             @Override
20087                             public void run() {
20088                                 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20089                             }
20090                         });
20091                     } break;
20092                 }
20093             }
20094         }
20095
20096         // Synchronously write as we are taking permissions away.
20097         if (writeRuntimePermissions) {
20098             mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20099         }
20100
20101         // Synchronously write as we are taking permissions away.
20102         if (writeInstallPermissions) {
20103             mSettings.writeLPr();
20104         }
20105     }
20106
20107     /**
20108      * Remove entries from the keystore daemon. Will only remove it if the
20109      * {@code appId} is valid.
20110      */
20111     private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20112         if (appId < 0) {
20113             return;
20114         }
20115
20116         final KeyStore keyStore = KeyStore.getInstance();
20117         if (keyStore != null) {
20118             if (userId == UserHandle.USER_ALL) {
20119                 for (final int individual : sUserManager.getUserIds()) {
20120                     keyStore.clearUid(UserHandle.getUid(individual, appId));
20121                 }
20122             } else {
20123                 keyStore.clearUid(UserHandle.getUid(userId, appId));
20124             }
20125         } else {
20126             Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20127         }
20128     }
20129
20130     @Override
20131     public void deleteApplicationCacheFiles(final String packageName,
20132             final IPackageDataObserver observer) {
20133         final int userId = UserHandle.getCallingUserId();
20134         deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20135     }
20136
20137     @Override
20138     public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20139             final IPackageDataObserver observer) {
20140         final int callingUid = Binder.getCallingUid();
20141         mContext.enforceCallingOrSelfPermission(
20142                 android.Manifest.permission.DELETE_CACHE_FILES, null);
20143         enforceCrossUserPermission(callingUid, userId,
20144                 /* requireFullPermission= */ true, /* checkShell= */ false,
20145                 "delete application cache files");
20146         final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20147                 android.Manifest.permission.ACCESS_INSTANT_APPS);
20148
20149         final PackageParser.Package pkg;
20150         synchronized (mPackages) {
20151             pkg = mPackages.get(packageName);
20152         }
20153
20154         // Queue up an async operation since the package deletion may take a little while.
20155         mHandler.post(new Runnable() {
20156             public void run() {
20157                 final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20158                 boolean doClearData = true;
20159                 if (ps != null) {
20160                     final boolean targetIsInstantApp =
20161                             ps.getInstantApp(UserHandle.getUserId(callingUid));
20162                     doClearData = !targetIsInstantApp
20163                             || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20164                 }
20165                 if (doClearData) {
20166                     synchronized (mInstallLock) {
20167                         final int flags = StorageManager.FLAG_STORAGE_DE
20168                                 | StorageManager.FLAG_STORAGE_CE;
20169                         // We're only clearing cache files, so we don't care if the
20170                         // app is unfrozen and still able to run
20171                         clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20172                         clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20173                     }
20174                     clearExternalStorageDataSync(packageName, userId, false);
20175                 }
20176                 if (observer != null) {
20177                     try {
20178                         observer.onRemoveCompleted(packageName, true);
20179                     } catch (RemoteException e) {
20180                         Log.i(TAG, "Observer no longer exists.");
20181                     }
20182                 }
20183             }
20184         });
20185     }
20186
20187     @Override
20188     public void getPackageSizeInfo(final String packageName, int userHandle,
20189             final IPackageStatsObserver observer) {
20190         throw new UnsupportedOperationException(
20191                 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20192     }
20193
20194     private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20195         final PackageSetting ps;
20196         synchronized (mPackages) {
20197             ps = mSettings.mPackages.get(packageName);
20198             if (ps == null) {
20199                 Slog.w(TAG, "Failed to find settings for " + packageName);
20200                 return false;
20201             }
20202         }
20203
20204         final String[] packageNames = { packageName };
20205         final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20206         final String[] codePaths = { ps.codePathString };
20207
20208         try {
20209             mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20210                     ps.appId, ceDataInodes, codePaths, stats);
20211
20212             // For now, ignore code size of packages on system partition
20213             if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20214                 stats.codeSize = 0;
20215             }
20216
20217             // External clients expect these to be tracked separately
20218             stats.dataSize -= stats.cacheSize;
20219
20220         } catch (InstallerException e) {
20221             Slog.w(TAG, String.valueOf(e));
20222             return false;
20223         }
20224
20225         return true;
20226     }
20227
20228     private int getUidTargetSdkVersionLockedLPr(int uid) {
20229         Object obj = mSettings.getUserIdLPr(uid);
20230         if (obj instanceof SharedUserSetting) {
20231             final SharedUserSetting sus = (SharedUserSetting) obj;
20232             int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20233             final Iterator<PackageSetting> it = sus.packages.iterator();
20234             while (it.hasNext()) {
20235                 final PackageSetting ps = it.next();
20236                 if (ps.pkg != null) {
20237                     int v = ps.pkg.applicationInfo.targetSdkVersion;
20238                     if (v < vers) vers = v;
20239                 }
20240             }
20241             return vers;
20242         } else if (obj instanceof PackageSetting) {
20243             final PackageSetting ps = (PackageSetting) obj;
20244             if (ps.pkg != null) {
20245                 return ps.pkg.applicationInfo.targetSdkVersion;
20246             }
20247         }
20248         return Build.VERSION_CODES.CUR_DEVELOPMENT;
20249     }
20250
20251     @Override
20252     public void addPreferredActivity(IntentFilter filter, int match,
20253             ComponentName[] set, ComponentName activity, int userId) {
20254         addPreferredActivityInternal(filter, match, set, activity, true, userId,
20255                 "Adding preferred");
20256     }
20257
20258     private void addPreferredActivityInternal(IntentFilter filter, int match,
20259             ComponentName[] set, ComponentName activity, boolean always, int userId,
20260             String opname) {
20261         // writer
20262         int callingUid = Binder.getCallingUid();
20263         enforceCrossUserPermission(callingUid, userId,
20264                 true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20265         if (filter.countActions() == 0) {
20266             Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20267             return;
20268         }
20269         synchronized (mPackages) {
20270             if (mContext.checkCallingOrSelfPermission(
20271                     android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20272                     != PackageManager.PERMISSION_GRANTED) {
20273                 if (getUidTargetSdkVersionLockedLPr(callingUid)
20274                         < Build.VERSION_CODES.FROYO) {
20275                     Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20276                             + callingUid);
20277                     return;
20278                 }
20279                 mContext.enforceCallingOrSelfPermission(
20280                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20281             }
20282
20283             PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20284             Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20285                     + userId + ":");
20286             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20287             pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20288             scheduleWritePackageRestrictionsLocked(userId);
20289             postPreferredActivityChangedBroadcast(userId);
20290         }
20291     }
20292
20293     private void postPreferredActivityChangedBroadcast(int userId) {
20294         mHandler.post(() -> {
20295             final IActivityManager am = ActivityManager.getService();
20296             if (am == null) {
20297                 return;
20298             }
20299
20300             final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20301             intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20302             try {
20303                 am.broadcastIntent(null, intent, null, null,
20304                         0, null, null, null, android.app.AppOpsManager.OP_NONE,
20305                         null, false, false, userId);
20306             } catch (RemoteException e) {
20307             }
20308         });
20309     }
20310
20311     @Override
20312     public void replacePreferredActivity(IntentFilter filter, int match,
20313             ComponentName[] set, ComponentName activity, int userId) {
20314         if (filter.countActions() != 1) {
20315             throw new IllegalArgumentException(
20316                     "replacePreferredActivity expects filter to have only 1 action.");
20317         }
20318         if (filter.countDataAuthorities() != 0
20319                 || filter.countDataPaths() != 0
20320                 || filter.countDataSchemes() > 1
20321                 || filter.countDataTypes() != 0) {
20322             throw new IllegalArgumentException(
20323                     "replacePreferredActivity expects filter to have no data authorities, " +
20324                     "paths, or types; and at most one scheme.");
20325         }
20326
20327         final int callingUid = Binder.getCallingUid();
20328         enforceCrossUserPermission(callingUid, userId,
20329                 true /* requireFullPermission */, false /* checkShell */,
20330                 "replace preferred activity");
20331         synchronized (mPackages) {
20332             if (mContext.checkCallingOrSelfPermission(
20333                     android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20334                     != PackageManager.PERMISSION_GRANTED) {
20335                 if (getUidTargetSdkVersionLockedLPr(callingUid)
20336                         < Build.VERSION_CODES.FROYO) {
20337                     Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20338                             + Binder.getCallingUid());
20339                     return;
20340                 }
20341                 mContext.enforceCallingOrSelfPermission(
20342                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20343             }
20344
20345             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20346             if (pir != null) {
20347                 // Get all of the existing entries that exactly match this filter.
20348                 ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20349                 if (existing != null && existing.size() == 1) {
20350                     PreferredActivity cur = existing.get(0);
20351                     if (DEBUG_PREFERRED) {
20352                         Slog.i(TAG, "Checking replace of preferred:");
20353                         filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20354                         if (!cur.mPref.mAlways) {
20355                             Slog.i(TAG, "  -- CUR; not mAlways!");
20356                         } else {
20357                             Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20358                             Slog.i(TAG, "  -- CUR: mSet="
20359                                     + Arrays.toString(cur.mPref.mSetComponents));
20360                             Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20361                             Slog.i(TAG, "  -- NEW: mMatch="
20362                                     + (match&IntentFilter.MATCH_CATEGORY_MASK));
20363                             Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20364                             Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20365                         }
20366                     }
20367                     if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20368                             && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20369                             && cur.mPref.sameSet(set)) {
20370                         // Setting the preferred activity to what it happens to be already
20371                         if (DEBUG_PREFERRED) {
20372                             Slog.i(TAG, "Replacing with same preferred activity "
20373                                     + cur.mPref.mShortComponent + " for user "
20374                                     + userId + ":");
20375                             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20376                         }
20377                         return;
20378                     }
20379                 }
20380
20381                 if (existing != null) {
20382                     if (DEBUG_PREFERRED) {
20383                         Slog.i(TAG, existing.size() + " existing preferred matches for:");
20384                         filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20385                     }
20386                     for (int i = 0; i < existing.size(); i++) {
20387                         PreferredActivity pa = existing.get(i);
20388                         if (DEBUG_PREFERRED) {
20389                             Slog.i(TAG, "Removing existing preferred activity "
20390                                     + pa.mPref.mComponent + ":");
20391                             pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20392                         }
20393                         pir.removeFilter(pa);
20394                     }
20395                 }
20396             }
20397             addPreferredActivityInternal(filter, match, set, activity, true, userId,
20398                     "Replacing preferred");
20399         }
20400     }
20401
20402     @Override
20403     public void clearPackagePreferredActivities(String packageName) {
20404         final int callingUid = Binder.getCallingUid();
20405         if (getInstantAppPackageName(callingUid) != null) {
20406             return;
20407         }
20408         // writer
20409         synchronized (mPackages) {
20410             PackageParser.Package pkg = mPackages.get(packageName);
20411             if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20412                 if (mContext.checkCallingOrSelfPermission(
20413                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20414                         != PackageManager.PERMISSION_GRANTED) {
20415                     if (getUidTargetSdkVersionLockedLPr(callingUid)
20416                             < Build.VERSION_CODES.FROYO) {
20417                         Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20418                                 + callingUid);
20419                         return;
20420                     }
20421                     mContext.enforceCallingOrSelfPermission(
20422                             android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20423                 }
20424             }
20425             final PackageSetting ps = mSettings.getPackageLPr(packageName);
20426             if (ps != null
20427                     && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20428                 return;
20429             }
20430             int user = UserHandle.getCallingUserId();
20431             if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20432                 scheduleWritePackageRestrictionsLocked(user);
20433             }
20434         }
20435     }
20436
20437     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20438     boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20439         ArrayList<PreferredActivity> removed = null;
20440         boolean changed = false;
20441         for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20442             final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20443             PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20444             if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20445                 continue;
20446             }
20447             Iterator<PreferredActivity> it = pir.filterIterator();
20448             while (it.hasNext()) {
20449                 PreferredActivity pa = it.next();
20450                 // Mark entry for removal only if it matches the package name
20451                 // and the entry is of type "always".
20452                 if (packageName == null ||
20453                         (pa.mPref.mComponent.getPackageName().equals(packageName)
20454                                 && pa.mPref.mAlways)) {
20455                     if (removed == null) {
20456                         removed = new ArrayList<PreferredActivity>();
20457                     }
20458                     removed.add(pa);
20459                 }
20460             }
20461             if (removed != null) {
20462                 for (int j=0; j<removed.size(); j++) {
20463                     PreferredActivity pa = removed.get(j);
20464                     pir.removeFilter(pa);
20465                 }
20466                 changed = true;
20467             }
20468         }
20469         if (changed) {
20470             postPreferredActivityChangedBroadcast(userId);
20471         }
20472         return changed;
20473     }
20474
20475     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20476     private void clearIntentFilterVerificationsLPw(int userId) {
20477         final int packageCount = mPackages.size();
20478         for (int i = 0; i < packageCount; i++) {
20479             PackageParser.Package pkg = mPackages.valueAt(i);
20480             clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20481         }
20482     }
20483
20484     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20485     void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20486         if (userId == UserHandle.USER_ALL) {
20487             if (mSettings.removeIntentFilterVerificationLPw(packageName,
20488                     sUserManager.getUserIds())) {
20489                 for (int oneUserId : sUserManager.getUserIds()) {
20490                     scheduleWritePackageRestrictionsLocked(oneUserId);
20491                 }
20492             }
20493         } else {
20494             if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20495                 scheduleWritePackageRestrictionsLocked(userId);
20496             }
20497         }
20498     }
20499
20500     /** Clears state for all users, and touches intent filter verification policy */
20501     void clearDefaultBrowserIfNeeded(String packageName) {
20502         for (int oneUserId : sUserManager.getUserIds()) {
20503             clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20504         }
20505     }
20506
20507     private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20508         final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20509         if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20510             if (packageName.equals(defaultBrowserPackageName)) {
20511                 setDefaultBrowserPackageName(null, userId);
20512             }
20513         }
20514     }
20515
20516     @Override
20517     public void resetApplicationPreferences(int userId) {
20518         mContext.enforceCallingOrSelfPermission(
20519                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20520         final long identity = Binder.clearCallingIdentity();
20521         // writer
20522         try {
20523             synchronized (mPackages) {
20524                 clearPackagePreferredActivitiesLPw(null, userId);
20525                 mSettings.applyDefaultPreferredAppsLPw(this, userId);
20526                 // TODO: We have to reset the default SMS and Phone. This requires
20527                 // significant refactoring to keep all default apps in the package
20528                 // manager (cleaner but more work) or have the services provide
20529                 // callbacks to the package manager to request a default app reset.
20530                 applyFactoryDefaultBrowserLPw(userId);
20531                 clearIntentFilterVerificationsLPw(userId);
20532                 primeDomainVerificationsLPw(userId);
20533                 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20534                 scheduleWritePackageRestrictionsLocked(userId);
20535             }
20536             resetNetworkPolicies(userId);
20537         } finally {
20538             Binder.restoreCallingIdentity(identity);
20539         }
20540     }
20541
20542     @Override
20543     public int getPreferredActivities(List<IntentFilter> outFilters,
20544             List<ComponentName> outActivities, String packageName) {
20545         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20546             return 0;
20547         }
20548         int num = 0;
20549         final int userId = UserHandle.getCallingUserId();
20550         // reader
20551         synchronized (mPackages) {
20552             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20553             if (pir != null) {
20554                 final Iterator<PreferredActivity> it = pir.filterIterator();
20555                 while (it.hasNext()) {
20556                     final PreferredActivity pa = it.next();
20557                     if (packageName == null
20558                             || (pa.mPref.mComponent.getPackageName().equals(packageName)
20559                                     && pa.mPref.mAlways)) {
20560                         if (outFilters != null) {
20561                             outFilters.add(new IntentFilter(pa));
20562                         }
20563                         if (outActivities != null) {
20564                             outActivities.add(pa.mPref.mComponent);
20565                         }
20566                     }
20567                 }
20568             }
20569         }
20570
20571         return num;
20572     }
20573
20574     @Override
20575     public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20576             int userId) {
20577         int callingUid = Binder.getCallingUid();
20578         if (callingUid != Process.SYSTEM_UID) {
20579             throw new SecurityException(
20580                     "addPersistentPreferredActivity can only be run by the system");
20581         }
20582         if (filter.countActions() == 0) {
20583             Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20584             return;
20585         }
20586         synchronized (mPackages) {
20587             Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20588                     ":");
20589             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20590             mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20591                     new PersistentPreferredActivity(filter, activity));
20592             scheduleWritePackageRestrictionsLocked(userId);
20593             postPreferredActivityChangedBroadcast(userId);
20594         }
20595     }
20596
20597     @Override
20598     public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20599         int callingUid = Binder.getCallingUid();
20600         if (callingUid != Process.SYSTEM_UID) {
20601             throw new SecurityException(
20602                     "clearPackagePersistentPreferredActivities can only be run by the system");
20603         }
20604         ArrayList<PersistentPreferredActivity> removed = null;
20605         boolean changed = false;
20606         synchronized (mPackages) {
20607             for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20608                 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20609                 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20610                         .valueAt(i);
20611                 if (userId != thisUserId) {
20612                     continue;
20613                 }
20614                 Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20615                 while (it.hasNext()) {
20616                     PersistentPreferredActivity ppa = it.next();
20617                     // Mark entry for removal only if it matches the package name.
20618                     if (ppa.mComponent.getPackageName().equals(packageName)) {
20619                         if (removed == null) {
20620                             removed = new ArrayList<PersistentPreferredActivity>();
20621                         }
20622                         removed.add(ppa);
20623                     }
20624                 }
20625                 if (removed != null) {
20626                     for (int j=0; j<removed.size(); j++) {
20627                         PersistentPreferredActivity ppa = removed.get(j);
20628                         ppir.removeFilter(ppa);
20629                     }
20630                     changed = true;
20631                 }
20632             }
20633
20634             if (changed) {
20635                 scheduleWritePackageRestrictionsLocked(userId);
20636                 postPreferredActivityChangedBroadcast(userId);
20637             }
20638         }
20639     }
20640
20641     /**
20642      * Common machinery for picking apart a restored XML blob and passing
20643      * it to a caller-supplied functor to be applied to the running system.
20644      */
20645     private void restoreFromXml(XmlPullParser parser, int userId,
20646             String expectedStartTag, BlobXmlRestorer functor)
20647             throws IOException, XmlPullParserException {
20648         int type;
20649         while ((type = parser.next()) != XmlPullParser.START_TAG
20650                 && type != XmlPullParser.END_DOCUMENT) {
20651         }
20652         if (type != XmlPullParser.START_TAG) {
20653             // oops didn't find a start tag?!
20654             if (DEBUG_BACKUP) {
20655                 Slog.e(TAG, "Didn't find start tag during restore");
20656             }
20657             return;
20658         }
20659 Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20660         // this is supposed to be TAG_PREFERRED_BACKUP
20661         if (!expectedStartTag.equals(parser.getName())) {
20662             if (DEBUG_BACKUP) {
20663                 Slog.e(TAG, "Found unexpected tag " + parser.getName());
20664             }
20665             return;
20666         }
20667
20668         // skip interfering stuff, then we're aligned with the backing implementation
20669         while ((type = parser.next()) == XmlPullParser.TEXT) { }
20670 Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20671         functor.apply(parser, userId);
20672     }
20673
20674     private interface BlobXmlRestorer {
20675         public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20676     }
20677
20678     /**
20679      * Non-Binder method, support for the backup/restore mechanism: write the
20680      * full set of preferred activities in its canonical XML format.  Returns the
20681      * XML output as a byte array, or null if there is none.
20682      */
20683     @Override
20684     public byte[] getPreferredActivityBackup(int userId) {
20685         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20686             throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20687         }
20688
20689         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20690         try {
20691             final XmlSerializer serializer = new FastXmlSerializer();
20692             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20693             serializer.startDocument(null, true);
20694             serializer.startTag(null, TAG_PREFERRED_BACKUP);
20695
20696             synchronized (mPackages) {
20697                 mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20698             }
20699
20700             serializer.endTag(null, TAG_PREFERRED_BACKUP);
20701             serializer.endDocument();
20702             serializer.flush();
20703         } catch (Exception e) {
20704             if (DEBUG_BACKUP) {
20705                 Slog.e(TAG, "Unable to write preferred activities for backup", e);
20706             }
20707             return null;
20708         }
20709
20710         return dataStream.toByteArray();
20711     }
20712
20713     @Override
20714     public void restorePreferredActivities(byte[] backup, int userId) {
20715         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20716             throw new SecurityException("Only the system may call restorePreferredActivities()");
20717         }
20718
20719         try {
20720             final XmlPullParser parser = Xml.newPullParser();
20721             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20722             restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20723                     new BlobXmlRestorer() {
20724                         @Override
20725                         public void apply(XmlPullParser parser, int userId)
20726                                 throws XmlPullParserException, IOException {
20727                             synchronized (mPackages) {
20728                                 mSettings.readPreferredActivitiesLPw(parser, userId);
20729                             }
20730                         }
20731                     } );
20732         } catch (Exception e) {
20733             if (DEBUG_BACKUP) {
20734                 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20735             }
20736         }
20737     }
20738
20739     /**
20740      * Non-Binder method, support for the backup/restore mechanism: write the
20741      * default browser (etc) settings in its canonical XML format.  Returns the default
20742      * browser XML representation as a byte array, or null if there is none.
20743      */
20744     @Override
20745     public byte[] getDefaultAppsBackup(int userId) {
20746         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20747             throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20748         }
20749
20750         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20751         try {
20752             final XmlSerializer serializer = new FastXmlSerializer();
20753             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20754             serializer.startDocument(null, true);
20755             serializer.startTag(null, TAG_DEFAULT_APPS);
20756
20757             synchronized (mPackages) {
20758                 mSettings.writeDefaultAppsLPr(serializer, userId);
20759             }
20760
20761             serializer.endTag(null, TAG_DEFAULT_APPS);
20762             serializer.endDocument();
20763             serializer.flush();
20764         } catch (Exception e) {
20765             if (DEBUG_BACKUP) {
20766                 Slog.e(TAG, "Unable to write default apps for backup", e);
20767             }
20768             return null;
20769         }
20770
20771         return dataStream.toByteArray();
20772     }
20773
20774     @Override
20775     public void restoreDefaultApps(byte[] backup, int userId) {
20776         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20777             throw new SecurityException("Only the system may call restoreDefaultApps()");
20778         }
20779
20780         try {
20781             final XmlPullParser parser = Xml.newPullParser();
20782             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20783             restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20784                     new BlobXmlRestorer() {
20785                         @Override
20786                         public void apply(XmlPullParser parser, int userId)
20787                                 throws XmlPullParserException, IOException {
20788                             synchronized (mPackages) {
20789                                 mSettings.readDefaultAppsLPw(parser, userId);
20790                             }
20791                         }
20792                     } );
20793         } catch (Exception e) {
20794             if (DEBUG_BACKUP) {
20795                 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20796             }
20797         }
20798     }
20799
20800     @Override
20801     public byte[] getIntentFilterVerificationBackup(int userId) {
20802         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20803             throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20804         }
20805
20806         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20807         try {
20808             final XmlSerializer serializer = new FastXmlSerializer();
20809             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20810             serializer.startDocument(null, true);
20811             serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20812
20813             synchronized (mPackages) {
20814                 mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20815             }
20816
20817             serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20818             serializer.endDocument();
20819             serializer.flush();
20820         } catch (Exception e) {
20821             if (DEBUG_BACKUP) {
20822                 Slog.e(TAG, "Unable to write default apps for backup", e);
20823             }
20824             return null;
20825         }
20826
20827         return dataStream.toByteArray();
20828     }
20829
20830     @Override
20831     public void restoreIntentFilterVerification(byte[] backup, int userId) {
20832         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20833             throw new SecurityException("Only the system may call restorePreferredActivities()");
20834         }
20835
20836         try {
20837             final XmlPullParser parser = Xml.newPullParser();
20838             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20839             restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20840                     new BlobXmlRestorer() {
20841                         @Override
20842                         public void apply(XmlPullParser parser, int userId)
20843                                 throws XmlPullParserException, IOException {
20844                             synchronized (mPackages) {
20845                                 mSettings.readAllDomainVerificationsLPr(parser, userId);
20846                                 mSettings.writeLPr();
20847                             }
20848                         }
20849                     } );
20850         } catch (Exception e) {
20851             if (DEBUG_BACKUP) {
20852                 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20853             }
20854         }
20855     }
20856
20857     @Override
20858     public byte[] getPermissionGrantBackup(int userId) {
20859         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20860             throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20861         }
20862
20863         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20864         try {
20865             final XmlSerializer serializer = new FastXmlSerializer();
20866             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20867             serializer.startDocument(null, true);
20868             serializer.startTag(null, TAG_PERMISSION_BACKUP);
20869
20870             synchronized (mPackages) {
20871                 serializeRuntimePermissionGrantsLPr(serializer, userId);
20872             }
20873
20874             serializer.endTag(null, TAG_PERMISSION_BACKUP);
20875             serializer.endDocument();
20876             serializer.flush();
20877         } catch (Exception e) {
20878             if (DEBUG_BACKUP) {
20879                 Slog.e(TAG, "Unable to write default apps for backup", e);
20880             }
20881             return null;
20882         }
20883
20884         return dataStream.toByteArray();
20885     }
20886
20887     @Override
20888     public void restorePermissionGrants(byte[] backup, int userId) {
20889         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20890             throw new SecurityException("Only the system may call restorePermissionGrants()");
20891         }
20892
20893         try {
20894             final XmlPullParser parser = Xml.newPullParser();
20895             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20896             restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20897                     new BlobXmlRestorer() {
20898                         @Override
20899                         public void apply(XmlPullParser parser, int userId)
20900                                 throws XmlPullParserException, IOException {
20901                             synchronized (mPackages) {
20902                                 processRestoredPermissionGrantsLPr(parser, userId);
20903                             }
20904                         }
20905                     } );
20906         } catch (Exception e) {
20907             if (DEBUG_BACKUP) {
20908                 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20909             }
20910         }
20911     }
20912
20913     private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20914             throws IOException {
20915         serializer.startTag(null, TAG_ALL_GRANTS);
20916
20917         final int N = mSettings.mPackages.size();
20918         for (int i = 0; i < N; i++) {
20919             final PackageSetting ps = mSettings.mPackages.valueAt(i);
20920             boolean pkgGrantsKnown = false;
20921
20922             PermissionsState packagePerms = ps.getPermissionsState();
20923
20924             for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20925                 final int grantFlags = state.getFlags();
20926                 // only look at grants that are not system/policy fixed
20927                 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20928                     final boolean isGranted = state.isGranted();
20929                     // And only back up the user-twiddled state bits
20930                     if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20931                         final String packageName = mSettings.mPackages.keyAt(i);
20932                         if (!pkgGrantsKnown) {
20933                             serializer.startTag(null, TAG_GRANT);
20934                             serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20935                             pkgGrantsKnown = true;
20936                         }
20937
20938                         final boolean userSet =
20939                                 (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20940                         final boolean userFixed =
20941                                 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20942                         final boolean revoke =
20943                                 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20944
20945                         serializer.startTag(null, TAG_PERMISSION);
20946                         serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20947                         if (isGranted) {
20948                             serializer.attribute(null, ATTR_IS_GRANTED, "true");
20949                         }
20950                         if (userSet) {
20951                             serializer.attribute(null, ATTR_USER_SET, "true");
20952                         }
20953                         if (userFixed) {
20954                             serializer.attribute(null, ATTR_USER_FIXED, "true");
20955                         }
20956                         if (revoke) {
20957                             serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20958                         }
20959                         serializer.endTag(null, TAG_PERMISSION);
20960                     }
20961                 }
20962             }
20963
20964             if (pkgGrantsKnown) {
20965                 serializer.endTag(null, TAG_GRANT);
20966             }
20967         }
20968
20969         serializer.endTag(null, TAG_ALL_GRANTS);
20970     }
20971
20972     private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20973             throws XmlPullParserException, IOException {
20974         String pkgName = null;
20975         int outerDepth = parser.getDepth();
20976         int type;
20977         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20978                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20979             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20980                 continue;
20981             }
20982
20983             final String tagName = parser.getName();
20984             if (tagName.equals(TAG_GRANT)) {
20985                 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20986                 if (DEBUG_BACKUP) {
20987                     Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20988                 }
20989             } else if (tagName.equals(TAG_PERMISSION)) {
20990
20991                 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20992                 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20993
20994                 int newFlagSet = 0;
20995                 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20996                     newFlagSet |= FLAG_PERMISSION_USER_SET;
20997                 }
20998                 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20999                     newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21000                 }
21001                 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21002                     newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21003                 }
21004                 if (DEBUG_BACKUP) {
21005                     Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21006                             + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21007                 }
21008                 final PackageSetting ps = mSettings.mPackages.get(pkgName);
21009                 if (ps != null) {
21010                     // Already installed so we apply the grant immediately
21011                     if (DEBUG_BACKUP) {
21012                         Slog.v(TAG, "        + already installed; applying");
21013                     }
21014                     PermissionsState perms = ps.getPermissionsState();
21015                     BasePermission bp = mSettings.mPermissions.get(permName);
21016                     if (bp != null) {
21017                         if (isGranted) {
21018                             perms.grantRuntimePermission(bp, userId);
21019                         }
21020                         if (newFlagSet != 0) {
21021                             perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21022                         }
21023                     }
21024                 } else {
21025                     // Need to wait for post-restore install to apply the grant
21026                     if (DEBUG_BACKUP) {
21027                         Slog.v(TAG, "        - not yet installed; saving for later");
21028                     }
21029                     mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21030                             isGranted, newFlagSet, userId);
21031                 }
21032             } else {
21033                 PackageManagerService.reportSettingsProblem(Log.WARN,
21034                         "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21035                 XmlUtils.skipCurrentTag(parser);
21036             }
21037         }
21038
21039         scheduleWriteSettingsLocked();
21040         mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21041     }
21042
21043     @Override
21044     public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21045             int sourceUserId, int targetUserId, int flags) {
21046         mContext.enforceCallingOrSelfPermission(
21047                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21048         int callingUid = Binder.getCallingUid();
21049         enforceOwnerRights(ownerPackage, callingUid);
21050         enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21051         if (intentFilter.countActions() == 0) {
21052             Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21053             return;
21054         }
21055         synchronized (mPackages) {
21056             CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21057                     ownerPackage, targetUserId, flags);
21058             CrossProfileIntentResolver resolver =
21059                     mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21060             ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21061             // We have all those whose filter is equal. Now checking if the rest is equal as well.
21062             if (existing != null) {
21063                 int size = existing.size();
21064                 for (int i = 0; i < size; i++) {
21065                     if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21066                         return;
21067                     }
21068                 }
21069             }
21070             resolver.addFilter(newFilter);
21071             scheduleWritePackageRestrictionsLocked(sourceUserId);
21072         }
21073     }
21074
21075     @Override
21076     public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21077         mContext.enforceCallingOrSelfPermission(
21078                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21079         final int callingUid = Binder.getCallingUid();
21080         enforceOwnerRights(ownerPackage, callingUid);
21081         enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21082         synchronized (mPackages) {
21083             CrossProfileIntentResolver resolver =
21084                     mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21085             ArraySet<CrossProfileIntentFilter> set =
21086                     new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21087             for (CrossProfileIntentFilter filter : set) {
21088                 if (filter.getOwnerPackage().equals(ownerPackage)) {
21089                     resolver.removeFilter(filter);
21090                 }
21091             }
21092             scheduleWritePackageRestrictionsLocked(sourceUserId);
21093         }
21094     }
21095
21096     // Enforcing that callingUid is owning pkg on userId
21097     private void enforceOwnerRights(String pkg, int callingUid) {
21098         // The system owns everything.
21099         if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21100             return;
21101         }
21102         final int callingUserId = UserHandle.getUserId(callingUid);
21103         PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21104         if (pi == null) {
21105             throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21106                     + callingUserId);
21107         }
21108         if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21109             throw new SecurityException("Calling uid " + callingUid
21110                     + " does not own package " + pkg);
21111         }
21112     }
21113
21114     @Override
21115     public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21116         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21117             return null;
21118         }
21119         return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21120     }
21121
21122     public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21123         UserManagerService ums = UserManagerService.getInstance();
21124         if (ums != null) {
21125             final UserInfo parent = ums.getProfileParent(userId);
21126             final int launcherUid = (parent != null) ? parent.id : userId;
21127             final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21128             if (launcherComponent != null) {
21129                 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21130                         .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21131                         .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21132                         .setPackage(launcherComponent.getPackageName());
21133                 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21134             }
21135         }
21136     }
21137
21138     /**
21139      * Report the 'Home' activity which is currently set as "always use this one". If non is set
21140      * then reports the most likely home activity or null if there are more than one.
21141      */
21142     private ComponentName getDefaultHomeActivity(int userId) {
21143         List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21144         ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21145         if (cn != null) {
21146             return cn;
21147         }
21148
21149         // Find the launcher with the highest priority and return that component if there are no
21150         // other home activity with the same priority.
21151         int lastPriority = Integer.MIN_VALUE;
21152         ComponentName lastComponent = null;
21153         final int size = allHomeCandidates.size();
21154         for (int i = 0; i < size; i++) {
21155             final ResolveInfo ri = allHomeCandidates.get(i);
21156             if (ri.priority > lastPriority) {
21157                 lastComponent = ri.activityInfo.getComponentName();
21158                 lastPriority = ri.priority;
21159             } else if (ri.priority == lastPriority) {
21160                 // Two components found with same priority.
21161                 lastComponent = null;
21162             }
21163         }
21164         return lastComponent;
21165     }
21166
21167     private Intent getHomeIntent() {
21168         Intent intent = new Intent(Intent.ACTION_MAIN);
21169         intent.addCategory(Intent.CATEGORY_HOME);
21170         intent.addCategory(Intent.CATEGORY_DEFAULT);
21171         return intent;
21172     }
21173
21174     private IntentFilter getHomeFilter() {
21175         IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21176         filter.addCategory(Intent.CATEGORY_HOME);
21177         filter.addCategory(Intent.CATEGORY_DEFAULT);
21178         return filter;
21179     }
21180
21181     ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21182             int userId) {
21183         Intent intent  = getHomeIntent();
21184         List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21185                 PackageManager.GET_META_DATA, userId);
21186         ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21187                 true, false, false, userId);
21188
21189         allHomeCandidates.clear();
21190         if (list != null) {
21191             for (ResolveInfo ri : list) {
21192                 allHomeCandidates.add(ri);
21193             }
21194         }
21195         return (preferred == null || preferred.activityInfo == null)
21196                 ? null
21197                 : new ComponentName(preferred.activityInfo.packageName,
21198                         preferred.activityInfo.name);
21199     }
21200
21201     @Override
21202     public void setHomeActivity(ComponentName comp, int userId) {
21203         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21204             return;
21205         }
21206         ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21207         getHomeActivitiesAsUser(homeActivities, userId);
21208
21209         boolean found = false;
21210
21211         final int size = homeActivities.size();
21212         final ComponentName[] set = new ComponentName[size];
21213         for (int i = 0; i < size; i++) {
21214             final ResolveInfo candidate = homeActivities.get(i);
21215             final ActivityInfo info = candidate.activityInfo;
21216             final ComponentName activityName = new ComponentName(info.packageName, info.name);
21217             set[i] = activityName;
21218             if (!found && activityName.equals(comp)) {
21219                 found = true;
21220             }
21221         }
21222         if (!found) {
21223             throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21224                     + userId);
21225         }
21226         replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21227                 set, comp, userId);
21228     }
21229
21230     private @Nullable String getSetupWizardPackageName() {
21231         final Intent intent = new Intent(Intent.ACTION_MAIN);
21232         intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21233
21234         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21235                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21236                         | MATCH_DISABLED_COMPONENTS,
21237                 UserHandle.myUserId());
21238         if (matches.size() == 1) {
21239             return matches.get(0).getComponentInfo().packageName;
21240         } else {
21241             Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21242                     + ": matches=" + matches);
21243             return null;
21244         }
21245     }
21246
21247     private @Nullable String getStorageManagerPackageName() {
21248         final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21249
21250         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21251                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21252                         | MATCH_DISABLED_COMPONENTS,
21253                 UserHandle.myUserId());
21254         if (matches.size() == 1) {
21255             return matches.get(0).getComponentInfo().packageName;
21256         } else {
21257             Slog.e(TAG, "There should probably be exactly one storage manager; found "
21258                     + matches.size() + ": matches=" + matches);
21259             return null;
21260         }
21261     }
21262
21263     @Override
21264     public void setApplicationEnabledSetting(String appPackageName,
21265             int newState, int flags, int userId, String callingPackage) {
21266         if (!sUserManager.exists(userId)) return;
21267         if (callingPackage == null) {
21268             callingPackage = Integer.toString(Binder.getCallingUid());
21269         }
21270         setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21271     }
21272
21273     @Override
21274     public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21275         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21276         synchronized (mPackages) {
21277             final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21278             if (pkgSetting != null) {
21279                 pkgSetting.setUpdateAvailable(updateAvailable);
21280             }
21281         }
21282     }
21283
21284     @Override
21285     public void setComponentEnabledSetting(ComponentName componentName,
21286             int newState, int flags, int userId) {
21287         if (!sUserManager.exists(userId)) return;
21288         setEnabledSetting(componentName.getPackageName(),
21289                 componentName.getClassName(), newState, flags, userId, null);
21290     }
21291
21292     private void setEnabledSetting(final String packageName, String className, int newState,
21293             final int flags, int userId, String callingPackage) {
21294         if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21295               || newState == COMPONENT_ENABLED_STATE_ENABLED
21296               || newState == COMPONENT_ENABLED_STATE_DISABLED
21297               || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21298               || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21299             throw new IllegalArgumentException("Invalid new component state: "
21300                     + newState);
21301         }
21302         PackageSetting pkgSetting;
21303         final int callingUid = Binder.getCallingUid();
21304         final int permission;
21305         if (callingUid == Process.SYSTEM_UID) {
21306             permission = PackageManager.PERMISSION_GRANTED;
21307         } else {
21308             permission = mContext.checkCallingOrSelfPermission(
21309                     android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21310         }
21311         enforceCrossUserPermission(callingUid, userId,
21312                 false /* requireFullPermission */, true /* checkShell */, "set enabled");
21313         final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21314         boolean sendNow = false;
21315         boolean isApp = (className == null);
21316         final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21317         String componentName = isApp ? packageName : className;
21318         int packageUid = -1;
21319         ArrayList<String> components;
21320
21321         // reader
21322         synchronized (mPackages) {
21323             pkgSetting = mSettings.mPackages.get(packageName);
21324             if (pkgSetting == null) {
21325                 if (!isCallerInstantApp) {
21326                     if (className == null) {
21327                         throw new IllegalArgumentException("Unknown package: " + packageName);
21328                     }
21329                     throw new IllegalArgumentException(
21330                             "Unknown component: " + packageName + "/" + className);
21331                 } else {
21332                     // throw SecurityException to prevent leaking package information
21333                     throw new SecurityException(
21334                             "Attempt to change component state; "
21335                             + "pid=" + Binder.getCallingPid()
21336                             + ", uid=" + callingUid
21337                             + (className == null
21338                                     ? ", package=" + packageName
21339                                     : ", component=" + packageName + "/" + className));
21340                 }
21341             }
21342         }
21343
21344         // Limit who can change which apps
21345         if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21346             // Don't allow apps that don't have permission to modify other apps
21347             if (!allowedByPermission
21348                     || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21349                 throw new SecurityException(
21350                         "Attempt to change component state; "
21351                         + "pid=" + Binder.getCallingPid()
21352                         + ", uid=" + callingUid
21353                         + (className == null
21354                                 ? ", package=" + packageName
21355                                 : ", component=" + packageName + "/" + className));
21356             }
21357             // Don't allow changing protected packages.
21358             if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21359                 throw new SecurityException("Cannot disable a protected package: " + packageName);
21360             }
21361         }
21362
21363         synchronized (mPackages) {
21364             if (callingUid == Process.SHELL_UID
21365                     && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21366                 // Shell can only change whole packages between ENABLED and DISABLED_USER states
21367                 // unless it is a test package.
21368                 int oldState = pkgSetting.getEnabled(userId);
21369                 if (className == null
21370                     &&
21371                     (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21372                      || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21373                      || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21374                     &&
21375                     (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21376                      || newState == COMPONENT_ENABLED_STATE_DEFAULT
21377                      || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21378                     // ok
21379                 } else {
21380                     throw new SecurityException(
21381                             "Shell cannot change component state for " + packageName + "/"
21382                             + className + " to " + newState);
21383                 }
21384             }
21385             if (className == null) {
21386                 // We're dealing with an application/package level state change
21387                 if (pkgSetting.getEnabled(userId) == newState) {
21388                     // Nothing to do
21389                     return;
21390                 }
21391                 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21392                     || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21393                     // Don't care about who enables an app.
21394                     callingPackage = null;
21395                 }
21396                 pkgSetting.setEnabled(newState, userId, callingPackage);
21397                 // pkgSetting.pkg.mSetEnabled = newState;
21398             } else {
21399                 // We're dealing with a component level state change
21400                 // First, verify that this is a valid class name.
21401                 PackageParser.Package pkg = pkgSetting.pkg;
21402                 if (pkg == null || !pkg.hasComponentClassName(className)) {
21403                     if (pkg != null &&
21404                             pkg.applicationInfo.targetSdkVersion >=
21405                                     Build.VERSION_CODES.JELLY_BEAN) {
21406                         throw new IllegalArgumentException("Component class " + className
21407                                 + " does not exist in " + packageName);
21408                     } else {
21409                         Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21410                                 + className + " does not exist in " + packageName);
21411                     }
21412                 }
21413                 switch (newState) {
21414                 case COMPONENT_ENABLED_STATE_ENABLED:
21415                     if (!pkgSetting.enableComponentLPw(className, userId)) {
21416                         return;
21417                     }
21418                     break;
21419                 case COMPONENT_ENABLED_STATE_DISABLED:
21420                     if (!pkgSetting.disableComponentLPw(className, userId)) {
21421                         return;
21422                     }
21423                     break;
21424                 case COMPONENT_ENABLED_STATE_DEFAULT:
21425                     if (!pkgSetting.restoreComponentLPw(className, userId)) {
21426                         return;
21427                     }
21428                     break;
21429                 default:
21430                     Slog.e(TAG, "Invalid new component state: " + newState);
21431                     return;
21432                 }
21433             }
21434             scheduleWritePackageRestrictionsLocked(userId);
21435             updateSequenceNumberLP(pkgSetting, new int[] { userId });
21436             final long callingId = Binder.clearCallingIdentity();
21437             try {
21438                 updateInstantAppInstallerLocked(packageName);
21439             } finally {
21440                 Binder.restoreCallingIdentity(callingId);
21441             }
21442             components = mPendingBroadcasts.get(userId, packageName);
21443             final boolean newPackage = components == null;
21444             if (newPackage) {
21445                 components = new ArrayList<String>();
21446             }
21447             if (!components.contains(componentName)) {
21448                 components.add(componentName);
21449             }
21450             if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21451                 sendNow = true;
21452                 // Purge entry from pending broadcast list if another one exists already
21453                 // since we are sending one right away.
21454                 mPendingBroadcasts.remove(userId, packageName);
21455             } else {
21456                 if (newPackage) {
21457                     mPendingBroadcasts.put(userId, packageName, components);
21458                 }
21459                 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21460                     // Schedule a message
21461                     mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21462                 }
21463             }
21464         }
21465
21466         long callingId = Binder.clearCallingIdentity();
21467         try {
21468             if (sendNow) {
21469                 packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21470                 sendPackageChangedBroadcast(packageName,
21471                         (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21472             }
21473         } finally {
21474             Binder.restoreCallingIdentity(callingId);
21475         }
21476     }
21477
21478     @Override
21479     public void flushPackageRestrictionsAsUser(int userId) {
21480         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21481             return;
21482         }
21483         if (!sUserManager.exists(userId)) {
21484             return;
21485         }
21486         enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21487                 false /* checkShell */, "flushPackageRestrictions");
21488         synchronized (mPackages) {
21489             mSettings.writePackageRestrictionsLPr(userId);
21490             mDirtyUsers.remove(userId);
21491             if (mDirtyUsers.isEmpty()) {
21492                 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21493             }
21494         }
21495     }
21496
21497     private void sendPackageChangedBroadcast(String packageName,
21498             boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21499         if (DEBUG_INSTALL)
21500             Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21501                     + componentNames);
21502         Bundle extras = new Bundle(4);
21503         extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21504         String nameList[] = new String[componentNames.size()];
21505         componentNames.toArray(nameList);
21506         extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21507         extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21508         extras.putInt(Intent.EXTRA_UID, packageUid);
21509         // If this is not reporting a change of the overall package, then only send it
21510         // to registered receivers.  We don't want to launch a swath of apps for every
21511         // little component state change.
21512         final int flags = !componentNames.contains(packageName)
21513                 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21514         sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21515                 new int[] {UserHandle.getUserId(packageUid)});
21516     }
21517
21518     @Override
21519     public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21520         if (!sUserManager.exists(userId)) return;
21521         final int callingUid = Binder.getCallingUid();
21522         if (getInstantAppPackageName(callingUid) != null) {
21523             return;
21524         }
21525         final int permission = mContext.checkCallingOrSelfPermission(
21526                 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21527         final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21528         enforceCrossUserPermission(callingUid, userId,
21529                 true /* requireFullPermission */, true /* checkShell */, "stop package");
21530         // writer
21531         synchronized (mPackages) {
21532             final PackageSetting ps = mSettings.mPackages.get(packageName);
21533             if (!filterAppAccessLPr(ps, callingUid, userId)
21534                     && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21535                             allowedByPermission, callingUid, userId)) {
21536                 scheduleWritePackageRestrictionsLocked(userId);
21537             }
21538         }
21539     }
21540
21541     @Override
21542     public String getInstallerPackageName(String packageName) {
21543         final int callingUid = Binder.getCallingUid();
21544         if (getInstantAppPackageName(callingUid) != null) {
21545             return null;
21546         }
21547         // reader
21548         synchronized (mPackages) {
21549             final PackageSetting ps = mSettings.mPackages.get(packageName);
21550             if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21551                 return null;
21552             }
21553             return mSettings.getInstallerPackageNameLPr(packageName);
21554         }
21555     }
21556
21557     public boolean isOrphaned(String packageName) {
21558         // reader
21559         synchronized (mPackages) {
21560             return mSettings.isOrphaned(packageName);
21561         }
21562     }
21563
21564     @Override
21565     public int getApplicationEnabledSetting(String packageName, int userId) {
21566         if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21567         int callingUid = Binder.getCallingUid();
21568         enforceCrossUserPermission(callingUid, userId,
21569                 false /* requireFullPermission */, false /* checkShell */, "get enabled");
21570         // reader
21571         synchronized (mPackages) {
21572             if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21573                 return COMPONENT_ENABLED_STATE_DISABLED;
21574             }
21575             return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21576         }
21577     }
21578
21579     @Override
21580     public int getComponentEnabledSetting(ComponentName component, int userId) {
21581         if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21582         int callingUid = Binder.getCallingUid();
21583         enforceCrossUserPermission(callingUid, userId,
21584                 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21585         synchronized (mPackages) {
21586             if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21587                     component, TYPE_UNKNOWN, userId)) {
21588                 return COMPONENT_ENABLED_STATE_DISABLED;
21589             }
21590             return mSettings.getComponentEnabledSettingLPr(component, userId);
21591         }
21592     }
21593
21594     @Override
21595     public void enterSafeMode() {
21596         enforceSystemOrRoot("Only the system can request entering safe mode");
21597
21598         if (!mSystemReady) {
21599             mSafeMode = true;
21600         }
21601     }
21602
21603     @Override
21604     public void systemReady() {
21605         enforceSystemOrRoot("Only the system can claim the system is ready");
21606
21607         mSystemReady = true;
21608         final ContentResolver resolver = mContext.getContentResolver();
21609         ContentObserver co = new ContentObserver(mHandler) {
21610             @Override
21611             public void onChange(boolean selfChange) {
21612                 mEphemeralAppsDisabled =
21613                         (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21614                                 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21615             }
21616         };
21617         mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21618                         .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21619                 false, co, UserHandle.USER_SYSTEM);
21620         mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21621                         .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21622         co.onChange(true);
21623
21624         // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21625         // disabled after already being started.
21626         CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21627                 mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21628
21629         // Read the compatibilty setting when the system is ready.
21630         boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21631                 mContext.getContentResolver(),
21632                 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21633         PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21634         if (DEBUG_SETTINGS) {
21635             Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21636         }
21637
21638         int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21639
21640         synchronized (mPackages) {
21641             // Verify that all of the preferred activity components actually
21642             // exist.  It is possible for applications to be updated and at
21643             // that point remove a previously declared activity component that
21644             // had been set as a preferred activity.  We try to clean this up
21645             // the next time we encounter that preferred activity, but it is
21646             // possible for the user flow to never be able to return to that
21647             // situation so here we do a sanity check to make sure we haven't
21648             // left any junk around.
21649             ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21650             for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21651                 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21652                 removed.clear();
21653                 for (PreferredActivity pa : pir.filterSet()) {
21654                     if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21655                         removed.add(pa);
21656                     }
21657                 }
21658                 if (removed.size() > 0) {
21659                     for (int r=0; r<removed.size(); r++) {
21660                         PreferredActivity pa = removed.get(r);
21661                         Slog.w(TAG, "Removing dangling preferred activity: "
21662                                 + pa.mPref.mComponent);
21663                         pir.removeFilter(pa);
21664                     }
21665                     mSettings.writePackageRestrictionsLPr(
21666                             mSettings.mPreferredActivities.keyAt(i));
21667                 }
21668             }
21669
21670             for (int userId : UserManagerService.getInstance().getUserIds()) {
21671                 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21672                     grantPermissionsUserIds = ArrayUtils.appendInt(
21673                             grantPermissionsUserIds, userId);
21674                 }
21675             }
21676         }
21677         sUserManager.systemReady();
21678
21679         // If we upgraded grant all default permissions before kicking off.
21680         for (int userId : grantPermissionsUserIds) {
21681             mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21682         }
21683
21684         // If we did not grant default permissions, we preload from this the
21685         // default permission exceptions lazily to ensure we don't hit the
21686         // disk on a new user creation.
21687         if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21688             mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21689         }
21690
21691         // Kick off any messages waiting for system ready
21692         if (mPostSystemReadyMessages != null) {
21693             for (Message msg : mPostSystemReadyMessages) {
21694                 msg.sendToTarget();
21695             }
21696             mPostSystemReadyMessages = null;
21697         }
21698
21699         // Watch for external volumes that come and go over time
21700         final StorageManager storage = mContext.getSystemService(StorageManager.class);
21701         storage.registerListener(mStorageListener);
21702
21703         mInstallerService.systemReady();
21704         mPackageDexOptimizer.systemReady();
21705
21706         StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21707                 StorageManagerInternal.class);
21708         StorageManagerInternal.addExternalStoragePolicy(
21709                 new StorageManagerInternal.ExternalStorageMountPolicy() {
21710             @Override
21711             public int getMountMode(int uid, String packageName) {
21712                 if (Process.isIsolated(uid)) {
21713                     return Zygote.MOUNT_EXTERNAL_NONE;
21714                 }
21715                 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21716                     return Zygote.MOUNT_EXTERNAL_DEFAULT;
21717                 }
21718                 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21719                     return Zygote.MOUNT_EXTERNAL_DEFAULT;
21720                 }
21721                 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21722                     return Zygote.MOUNT_EXTERNAL_READ;
21723                 }
21724                 return Zygote.MOUNT_EXTERNAL_WRITE;
21725             }
21726
21727             @Override
21728             public boolean hasExternalStorage(int uid, String packageName) {
21729                 return true;
21730             }
21731         });
21732
21733         // Now that we're mostly running, clean up stale users and apps
21734         sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21735         reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21736
21737         if (mPrivappPermissionsViolations != null) {
21738             Slog.wtf(TAG,"Signature|privileged permissions not in "
21739                     + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21740             mPrivappPermissionsViolations = null;
21741         }
21742     }
21743
21744     public void waitForAppDataPrepared() {
21745         if (mPrepareAppDataFuture == null) {
21746             return;
21747         }
21748         ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21749         mPrepareAppDataFuture = null;
21750     }
21751
21752     @Override
21753     public boolean isSafeMode() {
21754         // allow instant applications
21755         return mSafeMode;
21756     }
21757
21758     @Override
21759     public boolean hasSystemUidErrors() {
21760         // allow instant applications
21761         return mHasSystemUidErrors;
21762     }
21763
21764     static String arrayToString(int[] array) {
21765         StringBuffer buf = new StringBuffer(128);
21766         buf.append('[');
21767         if (array != null) {
21768             for (int i=0; i<array.length; i++) {
21769                 if (i > 0) buf.append(", ");
21770                 buf.append(array[i]);
21771             }
21772         }
21773         buf.append(']');
21774         return buf.toString();
21775     }
21776
21777     static class DumpState {
21778         public static final int DUMP_LIBS = 1 << 0;
21779         public static final int DUMP_FEATURES = 1 << 1;
21780         public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21781         public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21782         public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21783         public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21784         public static final int DUMP_PERMISSIONS = 1 << 6;
21785         public static final int DUMP_PACKAGES = 1 << 7;
21786         public static final int DUMP_SHARED_USERS = 1 << 8;
21787         public static final int DUMP_MESSAGES = 1 << 9;
21788         public static final int DUMP_PROVIDERS = 1 << 10;
21789         public static final int DUMP_VERIFIERS = 1 << 11;
21790         public static final int DUMP_PREFERRED = 1 << 12;
21791         public static final int DUMP_PREFERRED_XML = 1 << 13;
21792         public static final int DUMP_KEYSETS = 1 << 14;
21793         public static final int DUMP_VERSION = 1 << 15;
21794         public static final int DUMP_INSTALLS = 1 << 16;
21795         public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21796         public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21797         public static final int DUMP_FROZEN = 1 << 19;
21798         public static final int DUMP_DEXOPT = 1 << 20;
21799         public static final int DUMP_COMPILER_STATS = 1 << 21;
21800         public static final int DUMP_CHANGES = 1 << 22;
21801
21802         public static final int OPTION_SHOW_FILTERS = 1 << 0;
21803
21804         private int mTypes;
21805
21806         private int mOptions;
21807
21808         private boolean mTitlePrinted;
21809
21810         private SharedUserSetting mSharedUser;
21811
21812         public boolean isDumping(int type) {
21813             if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21814                 return true;
21815             }
21816
21817             return (mTypes & type) != 0;
21818         }
21819
21820         public void setDump(int type) {
21821             mTypes |= type;
21822         }
21823
21824         public boolean isOptionEnabled(int option) {
21825             return (mOptions & option) != 0;
21826         }
21827
21828         public void setOptionEnabled(int option) {
21829             mOptions |= option;
21830         }
21831
21832         public boolean onTitlePrinted() {
21833             final boolean printed = mTitlePrinted;
21834             mTitlePrinted = true;
21835             return printed;
21836         }
21837
21838         public boolean getTitlePrinted() {
21839             return mTitlePrinted;
21840         }
21841
21842         public void setTitlePrinted(boolean enabled) {
21843             mTitlePrinted = enabled;
21844         }
21845
21846         public SharedUserSetting getSharedUser() {
21847             return mSharedUser;
21848         }
21849
21850         public void setSharedUser(SharedUserSetting user) {
21851             mSharedUser = user;
21852         }
21853     }
21854
21855     @Override
21856     public void onShellCommand(FileDescriptor in, FileDescriptor out,
21857             FileDescriptor err, String[] args, ShellCallback callback,
21858             ResultReceiver resultReceiver) {
21859         (new PackageManagerShellCommand(this)).exec(
21860                 this, in, out, err, args, callback, resultReceiver);
21861     }
21862
21863     @Override
21864     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21865         if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21866
21867         DumpState dumpState = new DumpState();
21868         boolean fullPreferred = false;
21869         boolean checkin = false;
21870
21871         String packageName = null;
21872         ArraySet<String> permissionNames = null;
21873
21874         int opti = 0;
21875         while (opti < args.length) {
21876             String opt = args[opti];
21877             if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21878                 break;
21879             }
21880             opti++;
21881
21882             if ("-a".equals(opt)) {
21883                 // Right now we only know how to print all.
21884             } else if ("-h".equals(opt)) {
21885                 pw.println("Package manager dump options:");
21886                 pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21887                 pw.println("    --checkin: dump for a checkin");
21888                 pw.println("    -f: print details of intent filters");
21889                 pw.println("    -h: print this help");
21890                 pw.println("  cmd may be one of:");
21891                 pw.println("    l[ibraries]: list known shared libraries");
21892                 pw.println("    f[eatures]: list device features");
21893                 pw.println("    k[eysets]: print known keysets");
21894                 pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21895                 pw.println("    perm[issions]: dump permissions");
21896                 pw.println("    permission [name ...]: dump declaration and use of given permission");
21897                 pw.println("    pref[erred]: print preferred package settings");
21898                 pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21899                 pw.println("    prov[iders]: dump content providers");
21900                 pw.println("    p[ackages]: dump installed packages");
21901                 pw.println("    s[hared-users]: dump shared user IDs");
21902                 pw.println("    m[essages]: print collected runtime messages");
21903                 pw.println("    v[erifiers]: print package verifier info");
21904                 pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21905                 pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21906                 pw.println("    version: print database version info");
21907                 pw.println("    write: write current settings now");
21908                 pw.println("    installs: details about install sessions");
21909                 pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21910                 pw.println("    dexopt: dump dexopt state");
21911                 pw.println("    compiler-stats: dump compiler statistics");
21912                 pw.println("    enabled-overlays: dump list of enabled overlay packages");
21913                 pw.println("    <package.name>: info about given package");
21914                 return;
21915             } else if ("--checkin".equals(opt)) {
21916                 checkin = true;
21917             } else if ("-f".equals(opt)) {
21918                 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21919             } else if ("--proto".equals(opt)) {
21920                 dumpProto(fd);
21921                 return;
21922             } else {
21923                 pw.println("Unknown argument: " + opt + "; use -h for help");
21924             }
21925         }
21926
21927         // Is the caller requesting to dump a particular piece of data?
21928         if (opti < args.length) {
21929             String cmd = args[opti];
21930             opti++;
21931             // Is this a package name?
21932             if ("android".equals(cmd) || cmd.contains(".")) {
21933                 packageName = cmd;
21934                 // When dumping a single package, we always dump all of its
21935                 // filter information since the amount of data will be reasonable.
21936                 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21937             } else if ("check-permission".equals(cmd)) {
21938                 if (opti >= args.length) {
21939                     pw.println("Error: check-permission missing permission argument");
21940                     return;
21941                 }
21942                 String perm = args[opti];
21943                 opti++;
21944                 if (opti >= args.length) {
21945                     pw.println("Error: check-permission missing package argument");
21946                     return;
21947                 }
21948
21949                 String pkg = args[opti];
21950                 opti++;
21951                 int user = UserHandle.getUserId(Binder.getCallingUid());
21952                 if (opti < args.length) {
21953                     try {
21954                         user = Integer.parseInt(args[opti]);
21955                     } catch (NumberFormatException e) {
21956                         pw.println("Error: check-permission user argument is not a number: "
21957                                 + args[opti]);
21958                         return;
21959                     }
21960                 }
21961
21962                 // Normalize package name to handle renamed packages and static libs
21963                 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21964
21965                 pw.println(checkPermission(perm, pkg, user));
21966                 return;
21967             } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21968                 dumpState.setDump(DumpState.DUMP_LIBS);
21969             } else if ("f".equals(cmd) || "features".equals(cmd)) {
21970                 dumpState.setDump(DumpState.DUMP_FEATURES);
21971             } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21972                 if (opti >= args.length) {
21973                     dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21974                             | DumpState.DUMP_SERVICE_RESOLVERS
21975                             | DumpState.DUMP_RECEIVER_RESOLVERS
21976                             | DumpState.DUMP_CONTENT_RESOLVERS);
21977                 } else {
21978                     while (opti < args.length) {
21979                         String name = args[opti];
21980                         if ("a".equals(name) || "activity".equals(name)) {
21981                             dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21982                         } else if ("s".equals(name) || "service".equals(name)) {
21983                             dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21984                         } else if ("r".equals(name) || "receiver".equals(name)) {
21985                             dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21986                         } else if ("c".equals(name) || "content".equals(name)) {
21987                             dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21988                         } else {
21989                             pw.println("Error: unknown resolver table type: " + name);
21990                             return;
21991                         }
21992                         opti++;
21993                     }
21994                 }
21995             } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21996                 dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21997             } else if ("permission".equals(cmd)) {
21998                 if (opti >= args.length) {
21999                     pw.println("Error: permission requires permission name");
22000                     return;
22001                 }
22002                 permissionNames = new ArraySet<>();
22003                 while (opti < args.length) {
22004                     permissionNames.add(args[opti]);
22005                     opti++;
22006                 }
22007                 dumpState.setDump(DumpState.DUMP_PERMISSIONS
22008                         | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22009             } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22010                 dumpState.setDump(DumpState.DUMP_PREFERRED);
22011             } else if ("preferred-xml".equals(cmd)) {
22012                 dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22013                 if (opti < args.length && "--full".equals(args[opti])) {
22014                     fullPreferred = true;
22015                     opti++;
22016                 }
22017             } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22018                 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22019             } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22020                 dumpState.setDump(DumpState.DUMP_PACKAGES);
22021             } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22022                 dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22023             } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22024                 dumpState.setDump(DumpState.DUMP_PROVIDERS);
22025             } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22026                 dumpState.setDump(DumpState.DUMP_MESSAGES);
22027             } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22028                 dumpState.setDump(DumpState.DUMP_VERIFIERS);
22029             } else if ("i".equals(cmd) || "ifv".equals(cmd)
22030                     || "intent-filter-verifiers".equals(cmd)) {
22031                 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22032             } else if ("version".equals(cmd)) {
22033                 dumpState.setDump(DumpState.DUMP_VERSION);
22034             } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22035                 dumpState.setDump(DumpState.DUMP_KEYSETS);
22036             } else if ("installs".equals(cmd)) {
22037                 dumpState.setDump(DumpState.DUMP_INSTALLS);
22038             } else if ("frozen".equals(cmd)) {
22039                 dumpState.setDump(DumpState.DUMP_FROZEN);
22040             } else if ("dexopt".equals(cmd)) {
22041                 dumpState.setDump(DumpState.DUMP_DEXOPT);
22042             } else if ("compiler-stats".equals(cmd)) {
22043                 dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22044             } else if ("changes".equals(cmd)) {
22045                 dumpState.setDump(DumpState.DUMP_CHANGES);
22046             } else if ("write".equals(cmd)) {
22047                 synchronized (mPackages) {
22048                     mSettings.writeLPr();
22049                     pw.println("Settings written.");
22050                     return;
22051                 }
22052             }
22053         }
22054
22055         if (checkin) {
22056             pw.println("vers,1");
22057         }
22058
22059         // reader
22060         synchronized (mPackages) {
22061             if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22062                 if (!checkin) {
22063                     if (dumpState.onTitlePrinted())
22064                         pw.println();
22065                     pw.println("Database versions:");
22066                     mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22067                 }
22068             }
22069
22070             if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22071                 if (!checkin) {
22072                     if (dumpState.onTitlePrinted())
22073                         pw.println();
22074                     pw.println("Verifiers:");
22075                     pw.print("  Required: ");
22076                     pw.print(mRequiredVerifierPackage);
22077                     pw.print(" (uid=");
22078                     pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22079                             UserHandle.USER_SYSTEM));
22080                     pw.println(")");
22081                 } else if (mRequiredVerifierPackage != null) {
22082                     pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22083                     pw.print(",");
22084                     pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22085                             UserHandle.USER_SYSTEM));
22086                 }
22087             }
22088
22089             if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22090                     packageName == null) {
22091                 if (mIntentFilterVerifierComponent != null) {
22092                     String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22093                     if (!checkin) {
22094                         if (dumpState.onTitlePrinted())
22095                             pw.println();
22096                         pw.println("Intent Filter Verifier:");
22097                         pw.print("  Using: ");
22098                         pw.print(verifierPackageName);
22099                         pw.print(" (uid=");
22100                         pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22101                                 UserHandle.USER_SYSTEM));
22102                         pw.println(")");
22103                     } else if (verifierPackageName != null) {
22104                         pw.print("ifv,"); pw.print(verifierPackageName);
22105                         pw.print(",");
22106                         pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22107                                 UserHandle.USER_SYSTEM));
22108                     }
22109                 } else {
22110                     pw.println();
22111                     pw.println("No Intent Filter Verifier available!");
22112                 }
22113             }
22114
22115             if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22116                 boolean printedHeader = false;
22117                 final Iterator<String> it = mSharedLibraries.keySet().iterator();
22118                 while (it.hasNext()) {
22119                     String libName = it.next();
22120                     SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22121                     if (versionedLib == null) {
22122                         continue;
22123                     }
22124                     final int versionCount = versionedLib.size();
22125                     for (int i = 0; i < versionCount; i++) {
22126                         SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22127                         if (!checkin) {
22128                             if (!printedHeader) {
22129                                 if (dumpState.onTitlePrinted())
22130                                     pw.println();
22131                                 pw.println("Libraries:");
22132                                 printedHeader = true;
22133                             }
22134                             pw.print("  ");
22135                         } else {
22136                             pw.print("lib,");
22137                         }
22138                         pw.print(libEntry.info.getName());
22139                         if (libEntry.info.isStatic()) {
22140                             pw.print(" version=" + libEntry.info.getVersion());
22141                         }
22142                         if (!checkin) {
22143                             pw.print(" -> ");
22144                         }
22145                         if (libEntry.path != null) {
22146                             pw.print(" (jar) ");
22147                             pw.print(libEntry.path);
22148                         } else {
22149                             pw.print(" (apk) ");
22150                             pw.print(libEntry.apk);
22151                         }
22152                         pw.println();
22153                     }
22154                 }
22155             }
22156
22157             if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22158                 if (dumpState.onTitlePrinted())
22159                     pw.println();
22160                 if (!checkin) {
22161                     pw.println("Features:");
22162                 }
22163
22164                 synchronized (mAvailableFeatures) {
22165                     for (FeatureInfo feat : mAvailableFeatures.values()) {
22166                         if (checkin) {
22167                             pw.print("feat,");
22168                             pw.print(feat.name);
22169                             pw.print(",");
22170                             pw.println(feat.version);
22171                         } else {
22172                             pw.print("  ");
22173                             pw.print(feat.name);
22174                             if (feat.version > 0) {
22175                                 pw.print(" version=");
22176                                 pw.print(feat.version);
22177                             }
22178                             pw.println();
22179                         }
22180                     }
22181                 }
22182             }
22183
22184             if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22185                 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22186                         : "Activity Resolver Table:", "  ", packageName,
22187                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22188                     dumpState.setTitlePrinted(true);
22189                 }
22190             }
22191             if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22192                 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22193                         : "Receiver Resolver Table:", "  ", packageName,
22194                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22195                     dumpState.setTitlePrinted(true);
22196                 }
22197             }
22198             if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22199                 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22200                         : "Service Resolver Table:", "  ", packageName,
22201                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22202                     dumpState.setTitlePrinted(true);
22203                 }
22204             }
22205             if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22206                 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22207                         : "Provider Resolver Table:", "  ", packageName,
22208                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22209                     dumpState.setTitlePrinted(true);
22210                 }
22211             }
22212
22213             if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22214                 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22215                     PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22216                     int user = mSettings.mPreferredActivities.keyAt(i);
22217                     if (pir.dump(pw,
22218                             dumpState.getTitlePrinted()
22219                                 ? "\nPreferred Activities User " + user + ":"
22220                                 : "Preferred Activities User " + user + ":", "  ",
22221                             packageName, true, false)) {
22222                         dumpState.setTitlePrinted(true);
22223                     }
22224                 }
22225             }
22226
22227             if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22228                 pw.flush();
22229                 FileOutputStream fout = new FileOutputStream(fd);
22230                 BufferedOutputStream str = new BufferedOutputStream(fout);
22231                 XmlSerializer serializer = new FastXmlSerializer();
22232                 try {
22233                     serializer.setOutput(str, StandardCharsets.UTF_8.name());
22234                     serializer.startDocument(null, true);
22235                     serializer.setFeature(
22236                             "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22237                     mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22238                     serializer.endDocument();
22239                     serializer.flush();
22240                 } catch (IllegalArgumentException e) {
22241                     pw.println("Failed writing: " + e);
22242                 } catch (IllegalStateException e) {
22243                     pw.println("Failed writing: " + e);
22244                 } catch (IOException e) {
22245                     pw.println("Failed writing: " + e);
22246                 }
22247             }
22248
22249             if (!checkin
22250                     && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22251                     && packageName == null) {
22252                 pw.println();
22253                 int count = mSettings.mPackages.size();
22254                 if (count == 0) {
22255                     pw.println("No applications!");
22256                     pw.println();
22257                 } else {
22258                     final String prefix = "  ";
22259                     Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22260                     if (allPackageSettings.size() == 0) {
22261                         pw.println("No domain preferred apps!");
22262                         pw.println();
22263                     } else {
22264                         pw.println("App verification status:");
22265                         pw.println();
22266                         count = 0;
22267                         for (PackageSetting ps : allPackageSettings) {
22268                             IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22269                             if (ivi == null || ivi.getPackageName() == null) continue;
22270                             pw.println(prefix + "Package: " + ivi.getPackageName());
22271                             pw.println(prefix + "Domains: " + ivi.getDomainsString());
22272                             pw.println(prefix + "Status:  " + ivi.getStatusString());
22273                             pw.println();
22274                             count++;
22275                         }
22276                         if (count == 0) {
22277                             pw.println(prefix + "No app verification established.");
22278                             pw.println();
22279                         }
22280                         for (int userId : sUserManager.getUserIds()) {
22281                             pw.println("App linkages for user " + userId + ":");
22282                             pw.println();
22283                             count = 0;
22284                             for (PackageSetting ps : allPackageSettings) {
22285                                 final long status = ps.getDomainVerificationStatusForUser(userId);
22286                                 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22287                                         && !DEBUG_DOMAIN_VERIFICATION) {
22288                                     continue;
22289                                 }
22290                                 pw.println(prefix + "Package: " + ps.name);
22291                                 pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22292                                 String statusStr = IntentFilterVerificationInfo.
22293                                         getStatusStringFromValue(status);
22294                                 pw.println(prefix + "Status:  " + statusStr);
22295                                 pw.println();
22296                                 count++;
22297                             }
22298                             if (count == 0) {
22299                                 pw.println(prefix + "No configured app linkages.");
22300                                 pw.println();
22301                             }
22302                         }
22303                     }
22304                 }
22305             }
22306
22307             if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22308                 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22309                 if (packageName == null && permissionNames == null) {
22310                     for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22311                         if (iperm == 0) {
22312                             if (dumpState.onTitlePrinted())
22313                                 pw.println();
22314                             pw.println("AppOp Permissions:");
22315                         }
22316                         pw.print("  AppOp Permission ");
22317                         pw.print(mAppOpPermissionPackages.keyAt(iperm));
22318                         pw.println(":");
22319                         ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22320                         for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22321                             pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22322                         }
22323                     }
22324                 }
22325             }
22326
22327             if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22328                 boolean printedSomething = false;
22329                 for (PackageParser.Provider p : mProviders.mProviders.values()) {
22330                     if (packageName != null && !packageName.equals(p.info.packageName)) {
22331                         continue;
22332                     }
22333                     if (!printedSomething) {
22334                         if (dumpState.onTitlePrinted())
22335                             pw.println();
22336                         pw.println("Registered ContentProviders:");
22337                         printedSomething = true;
22338                     }
22339                     pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22340                     pw.print("    "); pw.println(p.toString());
22341                 }
22342                 printedSomething = false;
22343                 for (Map.Entry<String, PackageParser.Provider> entry :
22344                         mProvidersByAuthority.entrySet()) {
22345                     PackageParser.Provider p = entry.getValue();
22346                     if (packageName != null && !packageName.equals(p.info.packageName)) {
22347                         continue;
22348                     }
22349                     if (!printedSomething) {
22350                         if (dumpState.onTitlePrinted())
22351                             pw.println();
22352                         pw.println("ContentProvider Authorities:");
22353                         printedSomething = true;
22354                     }
22355                     pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22356                     pw.print("    "); pw.println(p.toString());
22357                     if (p.info != null && p.info.applicationInfo != null) {
22358                         final String appInfo = p.info.applicationInfo.toString();
22359                         pw.print("      applicationInfo="); pw.println(appInfo);
22360                     }
22361                 }
22362             }
22363
22364             if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22365                 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22366             }
22367
22368             if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22369                 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22370             }
22371
22372             if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22373                 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22374             }
22375
22376             if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22377                 if (dumpState.onTitlePrinted()) pw.println();
22378                 pw.println("Package Changes:");
22379                 pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22380                 final int K = mChangedPackages.size();
22381                 for (int i = 0; i < K; i++) {
22382                     final SparseArray<String> changes = mChangedPackages.valueAt(i);
22383                     pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22384                     final int N = changes.size();
22385                     if (N == 0) {
22386                         pw.print("    "); pw.println("No packages changed");
22387                     } else {
22388                         for (int j = 0; j < N; j++) {
22389                             final String pkgName = changes.valueAt(j);
22390                             final int sequenceNumber = changes.keyAt(j);
22391                             pw.print("    ");
22392                             pw.print("seq=");
22393                             pw.print(sequenceNumber);
22394                             pw.print(", package=");
22395                             pw.println(pkgName);
22396                         }
22397                     }
22398                 }
22399             }
22400
22401             if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22402                 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22403             }
22404
22405             if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22406                 // XXX should handle packageName != null by dumping only install data that
22407                 // the given package is involved with.
22408                 if (dumpState.onTitlePrinted()) pw.println();
22409
22410                 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22411                 ipw.println();
22412                 ipw.println("Frozen packages:");
22413                 ipw.increaseIndent();
22414                 if (mFrozenPackages.size() == 0) {
22415                     ipw.println("(none)");
22416                 } else {
22417                     for (int i = 0; i < mFrozenPackages.size(); i++) {
22418                         ipw.println(mFrozenPackages.valueAt(i));
22419                     }
22420                 }
22421                 ipw.decreaseIndent();
22422             }
22423
22424             if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22425                 if (dumpState.onTitlePrinted()) pw.println();
22426                 dumpDexoptStateLPr(pw, packageName);
22427             }
22428
22429             if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22430                 if (dumpState.onTitlePrinted()) pw.println();
22431                 dumpCompilerStatsLPr(pw, packageName);
22432             }
22433
22434             if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22435                 if (dumpState.onTitlePrinted()) pw.println();
22436                 mSettings.dumpReadMessagesLPr(pw, dumpState);
22437
22438                 pw.println();
22439                 pw.println("Package warning messages:");
22440                 BufferedReader in = null;
22441                 String line = null;
22442                 try {
22443                     in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22444                     while ((line = in.readLine()) != null) {
22445                         if (line.contains("ignored: updated version")) continue;
22446                         pw.println(line);
22447                     }
22448                 } catch (IOException ignored) {
22449                 } finally {
22450                     IoUtils.closeQuietly(in);
22451                 }
22452             }
22453
22454             if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22455                 BufferedReader in = null;
22456                 String line = null;
22457                 try {
22458                     in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22459                     while ((line = in.readLine()) != null) {
22460                         if (line.contains("ignored: updated version")) continue;
22461                         pw.print("msg,");
22462                         pw.println(line);
22463                     }
22464                 } catch (IOException ignored) {
22465                 } finally {
22466                     IoUtils.closeQuietly(in);
22467                 }
22468             }
22469         }
22470
22471         // PackageInstaller should be called outside of mPackages lock
22472         if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22473             // XXX should handle packageName != null by dumping only install data that
22474             // the given package is involved with.
22475             if (dumpState.onTitlePrinted()) pw.println();
22476             mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22477         }
22478     }
22479
22480     private void dumpProto(FileDescriptor fd) {
22481         final ProtoOutputStream proto = new ProtoOutputStream(fd);
22482
22483         synchronized (mPackages) {
22484             final long requiredVerifierPackageToken =
22485                     proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22486             proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22487             proto.write(
22488                     PackageServiceDumpProto.PackageShortProto.UID,
22489                     getPackageUid(
22490                             mRequiredVerifierPackage,
22491                             MATCH_DEBUG_TRIAGED_MISSING,
22492                             UserHandle.USER_SYSTEM));
22493             proto.end(requiredVerifierPackageToken);
22494
22495             if (mIntentFilterVerifierComponent != null) {
22496                 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22497                 final long verifierPackageToken =
22498                         proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22499                 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22500                 proto.write(
22501                         PackageServiceDumpProto.PackageShortProto.UID,
22502                         getPackageUid(
22503                                 verifierPackageName,
22504                                 MATCH_DEBUG_TRIAGED_MISSING,
22505                                 UserHandle.USER_SYSTEM));
22506                 proto.end(verifierPackageToken);
22507             }
22508
22509             dumpSharedLibrariesProto(proto);
22510             dumpFeaturesProto(proto);
22511             mSettings.dumpPackagesProto(proto);
22512             mSettings.dumpSharedUsersProto(proto);
22513             dumpMessagesProto(proto);
22514         }
22515         proto.flush();
22516     }
22517
22518     private void dumpMessagesProto(ProtoOutputStream proto) {
22519         BufferedReader in = null;
22520         String line = null;
22521         try {
22522             in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22523             while ((line = in.readLine()) != null) {
22524                 if (line.contains("ignored: updated version")) continue;
22525                 proto.write(PackageServiceDumpProto.MESSAGES, line);
22526             }
22527         } catch (IOException ignored) {
22528         } finally {
22529             IoUtils.closeQuietly(in);
22530         }
22531     }
22532
22533     private void dumpFeaturesProto(ProtoOutputStream proto) {
22534         synchronized (mAvailableFeatures) {
22535             final int count = mAvailableFeatures.size();
22536             for (int i = 0; i < count; i++) {
22537                 final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22538                 final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22539                 proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22540                 proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22541                 proto.end(featureToken);
22542             }
22543         }
22544     }
22545
22546     private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22547         final int count = mSharedLibraries.size();
22548         for (int i = 0; i < count; i++) {
22549             final String libName = mSharedLibraries.keyAt(i);
22550             SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22551             if (versionedLib == null) {
22552                 continue;
22553             }
22554             final int versionCount = versionedLib.size();
22555             for (int j = 0; j < versionCount; j++) {
22556                 final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22557                 final long sharedLibraryToken =
22558                         proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22559                 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22560                 final boolean isJar = (libEntry.path != null);
22561                 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22562                 if (isJar) {
22563                     proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22564                 } else {
22565                     proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22566                 }
22567                 proto.end(sharedLibraryToken);
22568             }
22569         }
22570     }
22571
22572     private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22573         final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22574         ipw.println();
22575         ipw.println("Dexopt state:");
22576         ipw.increaseIndent();
22577         Collection<PackageParser.Package> packages = null;
22578         if (packageName != null) {
22579             PackageParser.Package targetPackage = mPackages.get(packageName);
22580             if (targetPackage != null) {
22581                 packages = Collections.singletonList(targetPackage);
22582             } else {
22583                 ipw.println("Unable to find package: " + packageName);
22584                 return;
22585             }
22586         } else {
22587             packages = mPackages.values();
22588         }
22589
22590         for (PackageParser.Package pkg : packages) {
22591             ipw.println("[" + pkg.packageName + "]");
22592             ipw.increaseIndent();
22593             mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22594             ipw.decreaseIndent();
22595         }
22596     }
22597
22598     private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22599         final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22600         ipw.println();
22601         ipw.println("Compiler stats:");
22602         ipw.increaseIndent();
22603         Collection<PackageParser.Package> packages = null;
22604         if (packageName != null) {
22605             PackageParser.Package targetPackage = mPackages.get(packageName);
22606             if (targetPackage != null) {
22607                 packages = Collections.singletonList(targetPackage);
22608             } else {
22609                 ipw.println("Unable to find package: " + packageName);
22610                 return;
22611             }
22612         } else {
22613             packages = mPackages.values();
22614         }
22615
22616         for (PackageParser.Package pkg : packages) {
22617             ipw.println("[" + pkg.packageName + "]");
22618             ipw.increaseIndent();
22619
22620             CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22621             if (stats == null) {
22622                 ipw.println("(No recorded stats)");
22623             } else {
22624                 stats.dump(ipw);
22625             }
22626             ipw.decreaseIndent();
22627         }
22628     }
22629
22630     private String dumpDomainString(String packageName) {
22631         List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22632                 .getList();
22633         List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22634
22635         ArraySet<String> result = new ArraySet<>();
22636         if (iviList.size() > 0) {
22637             for (IntentFilterVerificationInfo ivi : iviList) {
22638                 for (String host : ivi.getDomains()) {
22639                     result.add(host);
22640                 }
22641             }
22642         }
22643         if (filters != null && filters.size() > 0) {
22644             for (IntentFilter filter : filters) {
22645                 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22646                         && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22647                                 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22648                     result.addAll(filter.getHostsList());
22649                 }
22650             }
22651         }
22652
22653         StringBuilder sb = new StringBuilder(result.size() * 16);
22654         for (String domain : result) {
22655             if (sb.length() > 0) sb.append(" ");
22656             sb.append(domain);
22657         }
22658         return sb.toString();
22659     }
22660
22661     // ------- apps on sdcard specific code -------
22662     static final boolean DEBUG_SD_INSTALL = false;
22663
22664     private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22665
22666     private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22667
22668     private boolean mMediaMounted = false;
22669
22670     static String getEncryptKey() {
22671         try {
22672             String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22673                     SD_ENCRYPTION_KEYSTORE_NAME);
22674             if (sdEncKey == null) {
22675                 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22676                         SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22677                 if (sdEncKey == null) {
22678                     Slog.e(TAG, "Failed to create encryption keys");
22679                     return null;
22680                 }
22681             }
22682             return sdEncKey;
22683         } catch (NoSuchAlgorithmException nsae) {
22684             Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22685             return null;
22686         } catch (IOException ioe) {
22687             Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22688             return null;
22689         }
22690     }
22691
22692     /*
22693      * Update media status on PackageManager.
22694      */
22695     @Override
22696     public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22697         enforceSystemOrRoot("Media status can only be updated by the system");
22698         // reader; this apparently protects mMediaMounted, but should probably
22699         // be a different lock in that case.
22700         synchronized (mPackages) {
22701             Log.i(TAG, "Updating external media status from "
22702                     + (mMediaMounted ? "mounted" : "unmounted") + " to "
22703                     + (mediaStatus ? "mounted" : "unmounted"));
22704             if (DEBUG_SD_INSTALL)
22705                 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22706                         + ", mMediaMounted=" + mMediaMounted);
22707             if (mediaStatus == mMediaMounted) {
22708                 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22709                         : 0, -1);
22710                 mHandler.sendMessage(msg);
22711                 return;
22712             }
22713             mMediaMounted = mediaStatus;
22714         }
22715         // Queue up an async operation since the package installation may take a
22716         // little while.
22717         mHandler.post(new Runnable() {
22718             public void run() {
22719                 updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22720             }
22721         });
22722     }
22723
22724     /**
22725      * Called by StorageManagerService when the initial ASECs to scan are available.
22726      * Should block until all the ASEC containers are finished being scanned.
22727      */
22728     public void scanAvailableAsecs() {
22729         updateExternalMediaStatusInner(true, false, false);
22730     }
22731
22732     /*
22733      * Collect information of applications on external media, map them against
22734      * existing containers and update information based on current mount status.
22735      * Please note that we always have to report status if reportStatus has been
22736      * set to true especially when unloading packages.
22737      */
22738     private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22739             boolean externalStorage) {
22740         ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22741         int[] uidArr = EmptyArray.INT;
22742
22743         final String[] list = PackageHelper.getSecureContainerList();
22744         if (ArrayUtils.isEmpty(list)) {
22745             Log.i(TAG, "No secure containers found");
22746         } else {
22747             // Process list of secure containers and categorize them
22748             // as active or stale based on their package internal state.
22749
22750             // reader
22751             synchronized (mPackages) {
22752                 for (String cid : list) {
22753                     // Leave stages untouched for now; installer service owns them
22754                     if (PackageInstallerService.isStageName(cid)) continue;
22755
22756                     if (DEBUG_SD_INSTALL)
22757                         Log.i(TAG, "Processing container " + cid);
22758                     String pkgName = getAsecPackageName(cid);
22759                     if (pkgName == null) {
22760                         Slog.i(TAG, "Found stale container " + cid + " with no package name");
22761                         continue;
22762                     }
22763                     if (DEBUG_SD_INSTALL)
22764                         Log.i(TAG, "Looking for pkg : " + pkgName);
22765
22766                     final PackageSetting ps = mSettings.mPackages.get(pkgName);
22767                     if (ps == null) {
22768                         Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22769                         continue;
22770                     }
22771
22772                     /*
22773                      * Skip packages that are not external if we're unmounting
22774                      * external storage.
22775                      */
22776                     if (externalStorage && !isMounted && !isExternal(ps)) {
22777                         continue;
22778                     }
22779
22780                     final AsecInstallArgs args = new AsecInstallArgs(cid,
22781                             getAppDexInstructionSets(ps), ps.isForwardLocked());
22782                     // The package status is changed only if the code path
22783                     // matches between settings and the container id.
22784                     if (ps.codePathString != null
22785                             && ps.codePathString.startsWith(args.getCodePath())) {
22786                         if (DEBUG_SD_INSTALL) {
22787                             Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22788                                     + " at code path: " + ps.codePathString);
22789                         }
22790
22791                         // We do have a valid package installed on sdcard
22792                         processCids.put(args, ps.codePathString);
22793                         final int uid = ps.appId;
22794                         if (uid != -1) {
22795                             uidArr = ArrayUtils.appendInt(uidArr, uid);
22796                         }
22797                     } else {
22798                         Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22799                                 + ps.codePathString);
22800                     }
22801                 }
22802             }
22803
22804             Arrays.sort(uidArr);
22805         }
22806
22807         // Process packages with valid entries.
22808         if (isMounted) {
22809             if (DEBUG_SD_INSTALL)
22810                 Log.i(TAG, "Loading packages");
22811             loadMediaPackages(processCids, uidArr, externalStorage);
22812             startCleaningPackages();
22813             mInstallerService.onSecureContainersAvailable();
22814         } else {
22815             if (DEBUG_SD_INSTALL)
22816                 Log.i(TAG, "Unloading packages");
22817             unloadMediaPackages(processCids, uidArr, reportStatus);
22818         }
22819     }
22820
22821     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22822             ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22823         final int size = infos.size();
22824         final String[] packageNames = new String[size];
22825         final int[] packageUids = new int[size];
22826         for (int i = 0; i < size; i++) {
22827             final ApplicationInfo info = infos.get(i);
22828             packageNames[i] = info.packageName;
22829             packageUids[i] = info.uid;
22830         }
22831         sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22832                 finishedReceiver);
22833     }
22834
22835     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22836             ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22837         sendResourcesChangedBroadcast(mediaStatus, replacing,
22838                 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22839     }
22840
22841     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22842             String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22843         int size = pkgList.length;
22844         if (size > 0) {
22845             // Send broadcasts here
22846             Bundle extras = new Bundle();
22847             extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22848             if (uidArr != null) {
22849                 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22850             }
22851             if (replacing) {
22852                 extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22853             }
22854             String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22855                     : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22856             sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22857         }
22858     }
22859
22860    /*
22861      * Look at potentially valid container ids from processCids If package
22862      * information doesn't match the one on record or package scanning fails,
22863      * the cid is added to list of removeCids. We currently don't delete stale
22864      * containers.
22865      */
22866     private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22867             boolean externalStorage) {
22868         ArrayList<String> pkgList = new ArrayList<String>();
22869         Set<AsecInstallArgs> keys = processCids.keySet();
22870
22871         for (AsecInstallArgs args : keys) {
22872             String codePath = processCids.get(args);
22873             if (DEBUG_SD_INSTALL)
22874                 Log.i(TAG, "Loading container : " + args.cid);
22875             int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22876             try {
22877                 // Make sure there are no container errors first.
22878                 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22879                     Slog.e(TAG, "Failed to mount cid : " + args.cid
22880                             + " when installing from sdcard");
22881                     continue;
22882                 }
22883                 // Check code path here.
22884                 if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22885                     Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22886                             + " does not match one in settings " + codePath);
22887                     continue;
22888                 }
22889                 // Parse package
22890                 int parseFlags = mDefParseFlags;
22891                 if (args.isExternalAsec()) {
22892                     parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22893                 }
22894                 if (args.isFwdLocked()) {
22895                     parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22896                 }
22897
22898                 synchronized (mInstallLock) {
22899                     PackageParser.Package pkg = null;
22900                     try {
22901                         // Sadly we don't know the package name yet to freeze it
22902                         pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22903                                 SCAN_IGNORE_FROZEN, 0, null);
22904                     } catch (PackageManagerException e) {
22905                         Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22906                     }
22907                     // Scan the package
22908                     if (pkg != null) {
22909                         /*
22910                          * TODO why is the lock being held? doPostInstall is
22911                          * called in other places without the lock. This needs
22912                          * to be straightened out.
22913                          */
22914                         // writer
22915                         synchronized (mPackages) {
22916                             retCode = PackageManager.INSTALL_SUCCEEDED;
22917                             pkgList.add(pkg.packageName);
22918                             // Post process args
22919                             args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22920                                     pkg.applicationInfo.uid);
22921                         }
22922                     } else {
22923                         Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22924                     }
22925                 }
22926
22927             } finally {
22928                 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22929                     Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22930                 }
22931             }
22932         }
22933         // writer
22934         synchronized (mPackages) {
22935             // If the platform SDK has changed since the last time we booted,
22936             // we need to re-grant app permission to catch any new ones that
22937             // appear. This is really a hack, and means that apps can in some
22938             // cases get permissions that the user didn't initially explicitly
22939             // allow... it would be nice to have some better way to handle
22940             // this situation.
22941             final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22942                     : mSettings.getInternalVersion();
22943             final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22944                     : StorageManager.UUID_PRIVATE_INTERNAL;
22945
22946             int updateFlags = UPDATE_PERMISSIONS_ALL;
22947             if (ver.sdkVersion != mSdkVersion) {
22948                 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22949                         + mSdkVersion + "; regranting permissions for external");
22950                 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22951             }
22952             updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22953
22954             // Yay, everything is now upgraded
22955             ver.forceCurrent();
22956
22957             // can downgrade to reader
22958             // Persist settings
22959             mSettings.writeLPr();
22960         }
22961         // Send a broadcast to let everyone know we are done processing
22962         if (pkgList.size() > 0) {
22963             sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22964         }
22965     }
22966
22967    /*
22968      * Utility method to unload a list of specified containers
22969      */
22970     private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22971         // Just unmount all valid containers.
22972         for (AsecInstallArgs arg : cidArgs) {
22973             synchronized (mInstallLock) {
22974                 arg.doPostDeleteLI(false);
22975            }
22976        }
22977    }
22978
22979     /*
22980      * Unload packages mounted on external media. This involves deleting package
22981      * data from internal structures, sending broadcasts about disabled packages,
22982      * gc'ing to free up references, unmounting all secure containers
22983      * corresponding to packages on external media, and posting a
22984      * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22985      * that we always have to post this message if status has been requested no
22986      * matter what.
22987      */
22988     private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22989             final boolean reportStatus) {
22990         if (DEBUG_SD_INSTALL)
22991             Log.i(TAG, "unloading media packages");
22992         ArrayList<String> pkgList = new ArrayList<String>();
22993         ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22994         final Set<AsecInstallArgs> keys = processCids.keySet();
22995         for (AsecInstallArgs args : keys) {
22996             String pkgName = args.getPackageName();
22997             if (DEBUG_SD_INSTALL)
22998                 Log.i(TAG, "Trying to unload pkg : " + pkgName);
22999             // Delete package internally
23000             PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23001             synchronized (mInstallLock) {
23002                 final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23003                 final boolean res;
23004                 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23005                         "unloadMediaPackages")) {
23006                     res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23007                             null);
23008                 }
23009                 if (res) {
23010                     pkgList.add(pkgName);
23011                 } else {
23012                     Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23013                     failedList.add(args);
23014                 }
23015             }
23016         }
23017
23018         // reader
23019         synchronized (mPackages) {
23020             // We didn't update the settings after removing each package;
23021             // write them now for all packages.
23022             mSettings.writeLPr();
23023         }
23024
23025         // We have to absolutely send UPDATED_MEDIA_STATUS only
23026         // after confirming that all the receivers processed the ordered
23027         // broadcast when packages get disabled, force a gc to clean things up.
23028         // and unload all the containers.
23029         if (pkgList.size() > 0) {
23030             sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23031                     new IIntentReceiver.Stub() {
23032                 public void performReceive(Intent intent, int resultCode, String data,
23033                         Bundle extras, boolean ordered, boolean sticky,
23034                         int sendingUser) throws RemoteException {
23035                     Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23036                             reportStatus ? 1 : 0, 1, keys);
23037                     mHandler.sendMessage(msg);
23038                 }
23039             });
23040         } else {
23041             Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23042                     keys);
23043             mHandler.sendMessage(msg);
23044         }
23045     }
23046
23047     private void loadPrivatePackages(final VolumeInfo vol) {
23048         mHandler.post(new Runnable() {
23049             @Override
23050             public void run() {
23051                 loadPrivatePackagesInner(vol);
23052             }
23053         });
23054     }
23055
23056     private void loadPrivatePackagesInner(VolumeInfo vol) {
23057         final String volumeUuid = vol.fsUuid;
23058         if (TextUtils.isEmpty(volumeUuid)) {
23059             Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23060             return;
23061         }
23062
23063         final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23064         final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23065         final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23066
23067         final VersionInfo ver;
23068         final List<PackageSetting> packages;
23069         synchronized (mPackages) {
23070             ver = mSettings.findOrCreateVersion(volumeUuid);
23071             packages = mSettings.getVolumePackagesLPr(volumeUuid);
23072         }
23073
23074         for (PackageSetting ps : packages) {
23075             freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23076             synchronized (mInstallLock) {
23077                 final PackageParser.Package pkg;
23078                 try {
23079                     pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23080                     loaded.add(pkg.applicationInfo);
23081
23082                 } catch (PackageManagerException e) {
23083                     Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23084                 }
23085
23086                 if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23087                     clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23088                             StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23089                                     | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23090                 }
23091             }
23092         }
23093
23094         // Reconcile app data for all started/unlocked users
23095         final StorageManager sm = mContext.getSystemService(StorageManager.class);
23096         final UserManager um = mContext.getSystemService(UserManager.class);
23097         UserManagerInternal umInternal = getUserManagerInternal();
23098         for (UserInfo user : um.getUsers()) {
23099             final int flags;
23100             if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23101                 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23102             } else if (umInternal.isUserRunning(user.id)) {
23103                 flags = StorageManager.FLAG_STORAGE_DE;
23104             } else {
23105                 continue;
23106             }
23107
23108             try {
23109                 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23110                 synchronized (mInstallLock) {
23111                     reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23112                 }
23113             } catch (IllegalStateException e) {
23114                 // Device was probably ejected, and we'll process that event momentarily
23115                 Slog.w(TAG, "Failed to prepare storage: " + e);
23116             }
23117         }
23118
23119         synchronized (mPackages) {
23120             int updateFlags = UPDATE_PERMISSIONS_ALL;
23121             if (ver.sdkVersion != mSdkVersion) {
23122                 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23123                         + mSdkVersion + "; regranting permissions for " + volumeUuid);
23124                 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23125             }
23126             updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23127
23128             // Yay, everything is now upgraded
23129             ver.forceCurrent();
23130
23131             mSettings.writeLPr();
23132         }
23133
23134         for (PackageFreezer freezer : freezers) {
23135             freezer.close();
23136         }
23137
23138         if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23139         sendResourcesChangedBroadcast(true, false, loaded, null);
23140     }
23141
23142     private void unloadPrivatePackages(final VolumeInfo vol) {
23143         mHandler.post(new Runnable() {
23144             @Override
23145             public void run() {
23146                 unloadPrivatePackagesInner(vol);
23147             }
23148         });
23149     }
23150
23151     private void unloadPrivatePackagesInner(VolumeInfo vol) {
23152         final String volumeUuid = vol.fsUuid;
23153         if (TextUtils.isEmpty(volumeUuid)) {
23154             Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23155             return;
23156         }
23157
23158         final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23159         synchronized (mInstallLock) {
23160         synchronized (mPackages) {
23161             final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23162             for (PackageSetting ps : packages) {
23163                 if (ps.pkg == null) continue;
23164
23165                 final ApplicationInfo info = ps.pkg.applicationInfo;
23166                 final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23167                 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23168
23169                 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23170                         "unloadPrivatePackagesInner")) {
23171                     if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23172                             false, null)) {
23173                         unloaded.add(info);
23174                     } else {
23175                         Slog.w(TAG, "Failed to unload " + ps.codePath);
23176                     }
23177                 }
23178
23179                 // Try very hard to release any references to this package
23180                 // so we don't risk the system server being killed due to
23181                 // open FDs
23182                 AttributeCache.instance().removePackage(ps.name);
23183             }
23184
23185             mSettings.writeLPr();
23186         }
23187         }
23188
23189         if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23190         sendResourcesChangedBroadcast(false, false, unloaded, null);
23191
23192         // Try very hard to release any references to this path so we don't risk
23193         // the system server being killed due to open FDs
23194         ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23195
23196         for (int i = 0; i < 3; i++) {
23197             System.gc();
23198             System.runFinalization();
23199         }
23200     }
23201
23202     private void assertPackageKnown(String volumeUuid, String packageName)
23203             throws PackageManagerException {
23204         synchronized (mPackages) {
23205             // Normalize package name to handle renamed packages
23206             packageName = normalizePackageNameLPr(packageName);
23207
23208             final PackageSetting ps = mSettings.mPackages.get(packageName);
23209             if (ps == null) {
23210                 throw new PackageManagerException("Package " + packageName + " is unknown");
23211             } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23212                 throw new PackageManagerException(
23213                         "Package " + packageName + " found on unknown volume " + volumeUuid
23214                                 + "; expected volume " + ps.volumeUuid);
23215             }
23216         }
23217     }
23218
23219     private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23220             throws PackageManagerException {
23221         synchronized (mPackages) {
23222             // Normalize package name to handle renamed packages
23223             packageName = normalizePackageNameLPr(packageName);
23224
23225             final PackageSetting ps = mSettings.mPackages.get(packageName);
23226             if (ps == null) {
23227                 throw new PackageManagerException("Package " + packageName + " is unknown");
23228             } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23229                 throw new PackageManagerException(
23230                         "Package " + packageName + " found on unknown volume " + volumeUuid
23231                                 + "; expected volume " + ps.volumeUuid);
23232             } else if (!ps.getInstalled(userId)) {
23233                 throw new PackageManagerException(
23234                         "Package " + packageName + " not installed for user " + userId);
23235             }
23236         }
23237     }
23238
23239     private List<String> collectAbsoluteCodePaths() {
23240         synchronized (mPackages) {
23241             List<String> codePaths = new ArrayList<>();
23242             final int packageCount = mSettings.mPackages.size();
23243             for (int i = 0; i < packageCount; i++) {
23244                 final PackageSetting ps = mSettings.mPackages.valueAt(i);
23245                 codePaths.add(ps.codePath.getAbsolutePath());
23246             }
23247             return codePaths;
23248         }
23249     }
23250
23251     /**
23252      * Examine all apps present on given mounted volume, and destroy apps that
23253      * aren't expected, either due to uninstallation or reinstallation on
23254      * another volume.
23255      */
23256     private void reconcileApps(String volumeUuid) {
23257         List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23258         List<File> filesToDelete = null;
23259
23260         final File[] files = FileUtils.listFilesOrEmpty(
23261                 Environment.getDataAppDirectory(volumeUuid));
23262         for (File file : files) {
23263             final boolean isPackage = (isApkFile(file) || file.isDirectory())
23264                     && !PackageInstallerService.isStageName(file.getName());
23265             if (!isPackage) {
23266                 // Ignore entries which are not packages
23267                 continue;
23268             }
23269
23270             String absolutePath = file.getAbsolutePath();
23271
23272             boolean pathValid = false;
23273             final int absoluteCodePathCount = absoluteCodePaths.size();
23274             for (int i = 0; i < absoluteCodePathCount; i++) {
23275                 String absoluteCodePath = absoluteCodePaths.get(i);
23276                 if (absolutePath.startsWith(absoluteCodePath)) {
23277                     pathValid = true;
23278                     break;
23279                 }
23280             }
23281
23282             if (!pathValid) {
23283                 if (filesToDelete == null) {
23284                     filesToDelete = new ArrayList<>();
23285                 }
23286                 filesToDelete.add(file);
23287             }
23288         }
23289
23290         if (filesToDelete != null) {
23291             final int fileToDeleteCount = filesToDelete.size();
23292             for (int i = 0; i < fileToDeleteCount; i++) {
23293                 File fileToDelete = filesToDelete.get(i);
23294                 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23295                 synchronized (mInstallLock) {
23296                     removeCodePathLI(fileToDelete);
23297                 }
23298             }
23299         }
23300     }
23301
23302     /**
23303      * Reconcile all app data for the given user.
23304      * <p>
23305      * Verifies that directories exist and that ownership and labeling is
23306      * correct for all installed apps on all mounted volumes.
23307      */
23308     void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23309         final StorageManager storage = mContext.getSystemService(StorageManager.class);
23310         for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23311             final String volumeUuid = vol.getFsUuid();
23312             synchronized (mInstallLock) {
23313                 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23314             }
23315         }
23316     }
23317
23318     private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23319             boolean migrateAppData) {
23320         reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23321     }
23322
23323     /**
23324      * Reconcile all app data on given mounted volume.
23325      * <p>
23326      * Destroys app data that isn't expected, either due to uninstallation or
23327      * reinstallation on another volume.
23328      * <p>
23329      * Verifies that directories exist and that ownership and labeling is
23330      * correct for all installed apps.
23331      * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23332      */
23333     private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23334             boolean migrateAppData, boolean onlyCoreApps) {
23335         Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23336                 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23337         List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23338
23339         final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23340         final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23341
23342         // First look for stale data that doesn't belong, and check if things
23343         // have changed since we did our last restorecon
23344         if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23345             if (StorageManager.isFileEncryptedNativeOrEmulated()
23346                     && !StorageManager.isUserKeyUnlocked(userId)) {
23347                 throw new RuntimeException(
23348                         "Yikes, someone asked us to reconcile CE storage while " + userId
23349                                 + " was still locked; this would have caused massive data loss!");
23350             }
23351
23352             final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23353             for (File file : files) {
23354                 final String packageName = file.getName();
23355                 try {
23356                     assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23357                 } catch (PackageManagerException e) {
23358                     logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23359                     try {
23360                         mInstaller.destroyAppData(volumeUuid, packageName, userId,
23361                                 StorageManager.FLAG_STORAGE_CE, 0);
23362                     } catch (InstallerException e2) {
23363                         logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23364                     }
23365                 }
23366             }
23367         }
23368         if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23369             final File[] files = FileUtils.listFilesOrEmpty(deDir);
23370             for (File file : files) {
23371                 final String packageName = file.getName();
23372                 try {
23373                     assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23374                 } catch (PackageManagerException e) {
23375                     logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23376                     try {
23377                         mInstaller.destroyAppData(volumeUuid, packageName, userId,
23378                                 StorageManager.FLAG_STORAGE_DE, 0);
23379                     } catch (InstallerException e2) {
23380                         logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23381                     }
23382                 }
23383             }
23384         }
23385
23386         // Ensure that data directories are ready to roll for all packages
23387         // installed for this volume and user
23388         final List<PackageSetting> packages;
23389         synchronized (mPackages) {
23390             packages = mSettings.getVolumePackagesLPr(volumeUuid);
23391         }
23392         int preparedCount = 0;
23393         for (PackageSetting ps : packages) {
23394             final String packageName = ps.name;
23395             if (ps.pkg == null) {
23396                 Slog.w(TAG, "Odd, missing scanned package " + packageName);
23397                 // TODO: might be due to legacy ASEC apps; we should circle back
23398                 // and reconcile again once they're scanned
23399                 continue;
23400             }
23401             // Skip non-core apps if requested
23402             if (onlyCoreApps && !ps.pkg.coreApp) {
23403                 result.add(packageName);
23404                 continue;
23405             }
23406
23407             if (ps.getInstalled(userId)) {
23408                 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23409                 preparedCount++;
23410             }
23411         }
23412
23413         Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23414         return result;
23415     }
23416
23417     /**
23418      * Prepare app data for the given app just after it was installed or
23419      * upgraded. This method carefully only touches users that it's installed
23420      * for, and it forces a restorecon to handle any seinfo changes.
23421      * <p>
23422      * Verifies that directories exist and that ownership and labeling is
23423      * correct for all installed apps. If there is an ownership mismatch, it
23424      * will try recovering system apps by wiping data; third-party app data is
23425      * left intact.
23426      * <p>
23427      * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23428      */
23429     private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23430         final PackageSetting ps;
23431         synchronized (mPackages) {
23432             ps = mSettings.mPackages.get(pkg.packageName);
23433             mSettings.writeKernelMappingLPr(ps);
23434         }
23435
23436         final UserManager um = mContext.getSystemService(UserManager.class);
23437         UserManagerInternal umInternal = getUserManagerInternal();
23438         for (UserInfo user : um.getUsers()) {
23439             final int flags;
23440             if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23441                 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23442             } else if (umInternal.isUserRunning(user.id)) {
23443                 flags = StorageManager.FLAG_STORAGE_DE;
23444             } else {
23445                 continue;
23446             }
23447
23448             if (ps.getInstalled(user.id)) {
23449                 // TODO: when user data is locked, mark that we're still dirty
23450                 prepareAppDataLIF(pkg, user.id, flags);
23451             }
23452         }
23453     }
23454
23455     /**
23456      * Prepare app data for the given app.
23457      * <p>
23458      * Verifies that directories exist and that ownership and labeling is
23459      * correct for all installed apps. If there is an ownership mismatch, this
23460      * will try recovering system apps by wiping data; third-party app data is
23461      * left intact.
23462      */
23463     private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23464         if (pkg == null) {
23465             Slog.wtf(TAG, "Package was null!", new Throwable());
23466             return;
23467         }
23468         prepareAppDataLeafLIF(pkg, userId, flags);
23469         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23470         for (int i = 0; i < childCount; i++) {
23471             prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23472         }
23473     }
23474
23475     private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23476             boolean maybeMigrateAppData) {
23477         prepareAppDataLIF(pkg, userId, flags);
23478
23479         if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23480             // We may have just shuffled around app data directories, so
23481             // prepare them one more time
23482             prepareAppDataLIF(pkg, userId, flags);
23483         }
23484     }
23485
23486     private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23487         if (DEBUG_APP_DATA) {
23488             Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23489                     + Integer.toHexString(flags));
23490         }
23491
23492         final String volumeUuid = pkg.volumeUuid;
23493         final String packageName = pkg.packageName;
23494         final ApplicationInfo app = pkg.applicationInfo;
23495         final int appId = UserHandle.getAppId(app.uid);
23496
23497         Preconditions.checkNotNull(app.seInfo);
23498
23499         long ceDataInode = -1;
23500         try {
23501             ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23502                     appId, app.seInfo, app.targetSdkVersion);
23503         } catch (InstallerException e) {
23504             if (app.isSystemApp()) {
23505                 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23506                         + ", but trying to recover: " + e);
23507                 destroyAppDataLeafLIF(pkg, userId, flags);
23508                 try {
23509                     ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23510                             appId, app.seInfo, app.targetSdkVersion);
23511                     logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23512                 } catch (InstallerException e2) {
23513                     logCriticalInfo(Log.DEBUG, "Recovery failed!");
23514                 }
23515             } else {
23516                 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23517             }
23518         }
23519
23520         if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23521             // TODO: mark this structure as dirty so we persist it!
23522             synchronized (mPackages) {
23523                 final PackageSetting ps = mSettings.mPackages.get(packageName);
23524                 if (ps != null) {
23525                     ps.setCeDataInode(ceDataInode, userId);
23526                 }
23527             }
23528         }
23529
23530         prepareAppDataContentsLeafLIF(pkg, userId, flags);
23531     }
23532
23533     private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23534         if (pkg == null) {
23535             Slog.wtf(TAG, "Package was null!", new Throwable());
23536             return;
23537         }
23538         prepareAppDataContentsLeafLIF(pkg, userId, flags);
23539         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23540         for (int i = 0; i < childCount; i++) {
23541             prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23542         }
23543     }
23544
23545     private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23546         final String volumeUuid = pkg.volumeUuid;
23547         final String packageName = pkg.packageName;
23548         final ApplicationInfo app = pkg.applicationInfo;
23549
23550         if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23551             // Create a native library symlink only if we have native libraries
23552             // and if the native libraries are 32 bit libraries. We do not provide
23553             // this symlink for 64 bit libraries.
23554             if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23555                 final String nativeLibPath = app.nativeLibraryDir;
23556                 try {
23557                     mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23558                             nativeLibPath, userId);
23559                 } catch (InstallerException e) {
23560                     Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23561                 }
23562             }
23563         }
23564     }
23565
23566     /**
23567      * For system apps on non-FBE devices, this method migrates any existing
23568      * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23569      * requested by the app.
23570      */
23571     private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23572         if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23573                 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23574             final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23575                     ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23576             try {
23577                 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23578                         storageTarget);
23579             } catch (InstallerException e) {
23580                 logCriticalInfo(Log.WARN,
23581                         "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23582             }
23583             return true;
23584         } else {
23585             return false;
23586         }
23587     }
23588
23589     public PackageFreezer freezePackage(String packageName, String killReason) {
23590         return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23591     }
23592
23593     public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23594         return new PackageFreezer(packageName, userId, killReason);
23595     }
23596
23597     public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23598             String killReason) {
23599         return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23600     }
23601
23602     public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23603             String killReason) {
23604         if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23605             return new PackageFreezer();
23606         } else {
23607             return freezePackage(packageName, userId, killReason);
23608         }
23609     }
23610
23611     public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23612             String killReason) {
23613         return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23614     }
23615
23616     public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23617             String killReason) {
23618         if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23619             return new PackageFreezer();
23620         } else {
23621             return freezePackage(packageName, userId, killReason);
23622         }
23623     }
23624
23625     /**
23626      * Class that freezes and kills the given package upon creation, and
23627      * unfreezes it upon closing. This is typically used when doing surgery on
23628      * app code/data to prevent the app from running while you're working.
23629      */
23630     private class PackageFreezer implements AutoCloseable {
23631         private final String mPackageName;
23632         private final PackageFreezer[] mChildren;
23633
23634         private final boolean mWeFroze;
23635
23636         private final AtomicBoolean mClosed = new AtomicBoolean();
23637         private final CloseGuard mCloseGuard = CloseGuard.get();
23638
23639         /**
23640          * Create and return a stub freezer that doesn't actually do anything,
23641          * typically used when someone requested
23642          * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23643          * {@link PackageManager#DELETE_DONT_KILL_APP}.
23644          */
23645         public PackageFreezer() {
23646             mPackageName = null;
23647             mChildren = null;
23648             mWeFroze = false;
23649             mCloseGuard.open("close");
23650         }
23651
23652         public PackageFreezer(String packageName, int userId, String killReason) {
23653             synchronized (mPackages) {
23654                 mPackageName = packageName;
23655                 mWeFroze = mFrozenPackages.add(mPackageName);
23656
23657                 final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23658                 if (ps != null) {
23659                     killApplication(ps.name, ps.appId, userId, killReason);
23660                 }
23661
23662                 final PackageParser.Package p = mPackages.get(packageName);
23663                 if (p != null && p.childPackages != null) {
23664                     final int N = p.childPackages.size();
23665                     mChildren = new PackageFreezer[N];
23666                     for (int i = 0; i < N; i++) {
23667                         mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23668                                 userId, killReason);
23669                     }
23670                 } else {
23671                     mChildren = null;
23672                 }
23673             }
23674             mCloseGuard.open("close");
23675         }
23676
23677         @Override
23678         protected void finalize() throws Throwable {
23679             try {
23680                 mCloseGuard.warnIfOpen();
23681                 close();
23682             } finally {
23683                 super.finalize();
23684             }
23685         }
23686
23687         @Override
23688         public void close() {
23689             mCloseGuard.close();
23690             if (mClosed.compareAndSet(false, true)) {
23691                 synchronized (mPackages) {
23692                     if (mWeFroze) {
23693                         mFrozenPackages.remove(mPackageName);
23694                     }
23695
23696                     if (mChildren != null) {
23697                         for (PackageFreezer freezer : mChildren) {
23698                             freezer.close();
23699                         }
23700                     }
23701                 }
23702             }
23703         }
23704     }
23705
23706     /**
23707      * Verify that given package is currently frozen.
23708      */
23709     private void checkPackageFrozen(String packageName) {
23710         synchronized (mPackages) {
23711             if (!mFrozenPackages.contains(packageName)) {
23712                 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23713             }
23714         }
23715     }
23716
23717     @Override
23718     public int movePackage(final String packageName, final String volumeUuid) {
23719         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23720
23721         final int callingUid = Binder.getCallingUid();
23722         final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23723         final int moveId = mNextMoveId.getAndIncrement();
23724         mHandler.post(new Runnable() {
23725             @Override
23726             public void run() {
23727                 try {
23728                     movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23729                 } catch (PackageManagerException e) {
23730                     Slog.w(TAG, "Failed to move " + packageName, e);
23731                     mMoveCallbacks.notifyStatusChanged(moveId,
23732                             PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23733                 }
23734             }
23735         });
23736         return moveId;
23737     }
23738
23739     private void movePackageInternal(final String packageName, final String volumeUuid,
23740             final int moveId, final int callingUid, UserHandle user)
23741                     throws PackageManagerException {
23742         final StorageManager storage = mContext.getSystemService(StorageManager.class);
23743         final PackageManager pm = mContext.getPackageManager();
23744
23745         final boolean currentAsec;
23746         final String currentVolumeUuid;
23747         final File codeFile;
23748         final String installerPackageName;
23749         final String packageAbiOverride;
23750         final int appId;
23751         final String seinfo;
23752         final String label;
23753         final int targetSdkVersion;
23754         final PackageFreezer freezer;
23755         final int[] installedUserIds;
23756
23757         // reader
23758         synchronized (mPackages) {
23759             final PackageParser.Package pkg = mPackages.get(packageName);
23760             final PackageSetting ps = mSettings.mPackages.get(packageName);
23761             if (pkg == null
23762                     || ps == null
23763                     || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23764                 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23765             }
23766             if (pkg.applicationInfo.isSystemApp()) {
23767                 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23768                         "Cannot move system application");
23769             }
23770
23771             final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23772             final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23773                     com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23774             if (isInternalStorage && !allow3rdPartyOnInternal) {
23775                 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23776                         "3rd party apps are not allowed on internal storage");
23777             }
23778
23779             if (pkg.applicationInfo.isExternalAsec()) {
23780                 currentAsec = true;
23781                 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23782             } else if (pkg.applicationInfo.isForwardLocked()) {
23783                 currentAsec = true;
23784                 currentVolumeUuid = "forward_locked";
23785             } else {
23786                 currentAsec = false;
23787                 currentVolumeUuid = ps.volumeUuid;
23788
23789                 final File probe = new File(pkg.codePath);
23790                 final File probeOat = new File(probe, "oat");
23791                 if (!probe.isDirectory() || !probeOat.isDirectory()) {
23792                     throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23793                             "Move only supported for modern cluster style installs");
23794                 }
23795             }
23796
23797             if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23798                 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23799                         "Package already moved to " + volumeUuid);
23800             }
23801             if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23802                 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23803                         "Device admin cannot be moved");
23804             }
23805
23806             if (mFrozenPackages.contains(packageName)) {
23807                 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23808                         "Failed to move already frozen package");
23809             }
23810
23811             codeFile = new File(pkg.codePath);
23812             installerPackageName = ps.installerPackageName;
23813             packageAbiOverride = ps.cpuAbiOverrideString;
23814             appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23815             seinfo = pkg.applicationInfo.seInfo;
23816             label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23817             targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23818             freezer = freezePackage(packageName, "movePackageInternal");
23819             installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23820         }
23821
23822         final Bundle extras = new Bundle();
23823         extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23824         extras.putString(Intent.EXTRA_TITLE, label);
23825         mMoveCallbacks.notifyCreated(moveId, extras);
23826
23827         int installFlags;
23828         final boolean moveCompleteApp;
23829         final File measurePath;
23830
23831         if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23832             installFlags = INSTALL_INTERNAL;
23833             moveCompleteApp = !currentAsec;
23834             measurePath = Environment.getDataAppDirectory(volumeUuid);
23835         } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23836             installFlags = INSTALL_EXTERNAL;
23837             moveCompleteApp = false;
23838             measurePath = storage.getPrimaryPhysicalVolume().getPath();
23839         } else {
23840             final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23841             if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23842                     || !volume.isMountedWritable()) {
23843                 freezer.close();
23844                 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23845                         "Move location not mounted private volume");
23846             }
23847
23848             Preconditions.checkState(!currentAsec);
23849
23850             installFlags = INSTALL_INTERNAL;
23851             moveCompleteApp = true;
23852             measurePath = Environment.getDataAppDirectory(volumeUuid);
23853         }
23854
23855         final PackageStats stats = new PackageStats(null, -1);
23856         synchronized (mInstaller) {
23857             for (int userId : installedUserIds) {
23858                 if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23859                     freezer.close();
23860                     throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23861                             "Failed to measure package size");
23862                 }
23863             }
23864         }
23865
23866         if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23867                 + stats.dataSize);
23868
23869         final long startFreeBytes = measurePath.getUsableSpace();
23870         final long sizeBytes;
23871         if (moveCompleteApp) {
23872             sizeBytes = stats.codeSize + stats.dataSize;
23873         } else {
23874             sizeBytes = stats.codeSize;
23875         }
23876
23877         if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23878             freezer.close();
23879             throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23880                     "Not enough free space to move");
23881         }
23882
23883         mMoveCallbacks.notifyStatusChanged(moveId, 10);
23884
23885         final CountDownLatch installedLatch = new CountDownLatch(1);
23886         final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23887             @Override
23888             public void onUserActionRequired(Intent intent) throws RemoteException {
23889                 throw new IllegalStateException();
23890             }
23891
23892             @Override
23893             public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23894                     Bundle extras) throws RemoteException {
23895                 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23896                         + PackageManager.installStatusToString(returnCode, msg));
23897
23898                 installedLatch.countDown();
23899                 freezer.close();
23900
23901                 final int status = PackageManager.installStatusToPublicStatus(returnCode);
23902                 switch (status) {
23903                     case PackageInstaller.STATUS_SUCCESS:
23904                         mMoveCallbacks.notifyStatusChanged(moveId,
23905                                 PackageManager.MOVE_SUCCEEDED);
23906                         break;
23907                     case PackageInstaller.STATUS_FAILURE_STORAGE:
23908                         mMoveCallbacks.notifyStatusChanged(moveId,
23909                                 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23910                         break;
23911                     default:
23912                         mMoveCallbacks.notifyStatusChanged(moveId,
23913                                 PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23914                         break;
23915                 }
23916             }
23917         };
23918
23919         final MoveInfo move;
23920         if (moveCompleteApp) {
23921             // Kick off a thread to report progress estimates
23922             new Thread() {
23923                 @Override
23924                 public void run() {
23925                     while (true) {
23926                         try {
23927                             if (installedLatch.await(1, TimeUnit.SECONDS)) {
23928                                 break;
23929                             }
23930                         } catch (InterruptedException ignored) {
23931                         }
23932
23933                         final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23934                         final int progress = 10 + (int) MathUtils.constrain(
23935                                 ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23936                         mMoveCallbacks.notifyStatusChanged(moveId, progress);
23937                     }
23938                 }
23939             }.start();
23940
23941             final String dataAppName = codeFile.getName();
23942             move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23943                     dataAppName, appId, seinfo, targetSdkVersion);
23944         } else {
23945             move = null;
23946         }
23947
23948         installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23949
23950         final Message msg = mHandler.obtainMessage(INIT_COPY);
23951         final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23952         final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23953                 installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23954                 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23955                 PackageManager.INSTALL_REASON_UNKNOWN);
23956         params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23957         msg.obj = params;
23958
23959         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23960                 System.identityHashCode(msg.obj));
23961         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23962                 System.identityHashCode(msg.obj));
23963
23964         mHandler.sendMessage(msg);
23965     }
23966
23967     @Override
23968     public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23969         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23970
23971         final int realMoveId = mNextMoveId.getAndIncrement();
23972         final Bundle extras = new Bundle();
23973         extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23974         mMoveCallbacks.notifyCreated(realMoveId, extras);
23975
23976         final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23977             @Override
23978             public void onCreated(int moveId, Bundle extras) {
23979                 // Ignored
23980             }
23981
23982             @Override
23983             public void onStatusChanged(int moveId, int status, long estMillis) {
23984                 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23985             }
23986         };
23987
23988         final StorageManager storage = mContext.getSystemService(StorageManager.class);
23989         storage.setPrimaryStorageUuid(volumeUuid, callback);
23990         return realMoveId;
23991     }
23992
23993     @Override
23994     public int getMoveStatus(int moveId) {
23995         mContext.enforceCallingOrSelfPermission(
23996                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23997         return mMoveCallbacks.mLastStatus.get(moveId);
23998     }
23999
24000     @Override
24001     public void registerMoveCallback(IPackageMoveObserver callback) {
24002         mContext.enforceCallingOrSelfPermission(
24003                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24004         mMoveCallbacks.register(callback);
24005     }
24006
24007     @Override
24008     public void unregisterMoveCallback(IPackageMoveObserver callback) {
24009         mContext.enforceCallingOrSelfPermission(
24010                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24011         mMoveCallbacks.unregister(callback);
24012     }
24013
24014     @Override
24015     public boolean setInstallLocation(int loc) {
24016         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24017                 null);
24018         if (getInstallLocation() == loc) {
24019             return true;
24020         }
24021         if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24022                 || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24023             android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24024                     android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24025             return true;
24026         }
24027         return false;
24028    }
24029
24030     @Override
24031     public int getInstallLocation() {
24032         // allow instant app access
24033         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24034                 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24035                 PackageHelper.APP_INSTALL_AUTO);
24036     }
24037
24038     /** Called by UserManagerService */
24039     void cleanUpUser(UserManagerService userManager, int userHandle) {
24040         synchronized (mPackages) {
24041             mDirtyUsers.remove(userHandle);
24042             mUserNeedsBadging.delete(userHandle);
24043             mSettings.removeUserLPw(userHandle);
24044             mPendingBroadcasts.remove(userHandle);
24045             mInstantAppRegistry.onUserRemovedLPw(userHandle);
24046             removeUnusedPackagesLPw(userManager, userHandle);
24047         }
24048     }
24049
24050     /**
24051      * We're removing userHandle and would like to remove any downloaded packages
24052      * that are no longer in use by any other user.
24053      * @param userHandle the user being removed
24054      */
24055     private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24056         final boolean DEBUG_CLEAN_APKS = false;
24057         int [] users = userManager.getUserIds();
24058         Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24059         while (psit.hasNext()) {
24060             PackageSetting ps = psit.next();
24061             if (ps.pkg == null) {
24062                 continue;
24063             }
24064             final String packageName = ps.pkg.packageName;
24065             // Skip over if system app
24066             if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24067                 continue;
24068             }
24069             if (DEBUG_CLEAN_APKS) {
24070                 Slog.i(TAG, "Checking package " + packageName);
24071             }
24072             boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24073             if (keep) {
24074                 if (DEBUG_CLEAN_APKS) {
24075                     Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24076                 }
24077             } else {
24078                 for (int i = 0; i < users.length; i++) {
24079                     if (users[i] != userHandle && ps.getInstalled(users[i])) {
24080                         keep = true;
24081                         if (DEBUG_CLEAN_APKS) {
24082                             Slog.i(TAG, "  Keeping package " + packageName + " for user "
24083                                     + users[i]);
24084                         }
24085                         break;
24086                     }
24087                 }
24088             }
24089             if (!keep) {
24090                 if (DEBUG_CLEAN_APKS) {
24091                     Slog.i(TAG, "  Removing package " + packageName);
24092                 }
24093                 mHandler.post(new Runnable() {
24094                     public void run() {
24095                         deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24096                                 userHandle, 0);
24097                     } //end run
24098                 });
24099             }
24100         }
24101     }
24102
24103     /** Called by UserManagerService */
24104     void createNewUser(int userId, String[] disallowedPackages) {
24105         synchronized (mInstallLock) {
24106             mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24107         }
24108         synchronized (mPackages) {
24109             scheduleWritePackageRestrictionsLocked(userId);
24110             scheduleWritePackageListLocked(userId);
24111             applyFactoryDefaultBrowserLPw(userId);
24112             primeDomainVerificationsLPw(userId);
24113         }
24114     }
24115
24116     void onNewUserCreated(final int userId) {
24117         mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24118         // If permission review for legacy apps is required, we represent
24119         // dagerous permissions for such apps as always granted runtime
24120         // permissions to keep per user flag state whether review is needed.
24121         // Hence, if a new user is added we have to propagate dangerous
24122         // permission grants for these legacy apps.
24123         if (mPermissionReviewRequired) {
24124             updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24125                     | UPDATE_PERMISSIONS_REPLACE_ALL);
24126         }
24127     }
24128
24129     @Override
24130     public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24131         mContext.enforceCallingOrSelfPermission(
24132                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24133                 "Only package verification agents can read the verifier device identity");
24134
24135         synchronized (mPackages) {
24136             return mSettings.getVerifierDeviceIdentityLPw();
24137         }
24138     }
24139
24140     @Override
24141     public void setPermissionEnforced(String permission, boolean enforced) {
24142         // TODO: Now that we no longer change GID for storage, this should to away.
24143         mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24144                 "setPermissionEnforced");
24145         if (READ_EXTERNAL_STORAGE.equals(permission)) {
24146             synchronized (mPackages) {
24147                 if (mSettings.mReadExternalStorageEnforced == null
24148                         || mSettings.mReadExternalStorageEnforced != enforced) {
24149                     mSettings.mReadExternalStorageEnforced = enforced;
24150                     mSettings.writeLPr();
24151                 }
24152             }
24153             // kill any non-foreground processes so we restart them and
24154             // grant/revoke the GID.
24155             final IActivityManager am = ActivityManager.getService();
24156             if (am != null) {
24157                 final long token = Binder.clearCallingIdentity();
24158                 try {
24159                     am.killProcessesBelowForeground("setPermissionEnforcement");
24160                 } catch (RemoteException e) {
24161                 } finally {
24162                     Binder.restoreCallingIdentity(token);
24163                 }
24164             }
24165         } else {
24166             throw new IllegalArgumentException("No selective enforcement for " + permission);
24167         }
24168     }
24169
24170     @Override
24171     @Deprecated
24172     public boolean isPermissionEnforced(String permission) {
24173         // allow instant applications
24174         return true;
24175     }
24176
24177     @Override
24178     public boolean isStorageLow() {
24179         // allow instant applications
24180         final long token = Binder.clearCallingIdentity();
24181         try {
24182             final DeviceStorageMonitorInternal
24183                     dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24184             if (dsm != null) {
24185                 return dsm.isMemoryLow();
24186             } else {
24187                 return false;
24188             }
24189         } finally {
24190             Binder.restoreCallingIdentity(token);
24191         }
24192     }
24193
24194     @Override
24195     public IPackageInstaller getPackageInstaller() {
24196         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24197             return null;
24198         }
24199         return mInstallerService;
24200     }
24201
24202     private boolean userNeedsBadging(int userId) {
24203         int index = mUserNeedsBadging.indexOfKey(userId);
24204         if (index < 0) {
24205             final UserInfo userInfo;
24206             final long token = Binder.clearCallingIdentity();
24207             try {
24208                 userInfo = sUserManager.getUserInfo(userId);
24209             } finally {
24210                 Binder.restoreCallingIdentity(token);
24211             }
24212             final boolean b;
24213             if (userInfo != null && userInfo.isManagedProfile()) {
24214                 b = true;
24215             } else {
24216                 b = false;
24217             }
24218             mUserNeedsBadging.put(userId, b);
24219             return b;
24220         }
24221         return mUserNeedsBadging.valueAt(index);
24222     }
24223
24224     @Override
24225     public KeySet getKeySetByAlias(String packageName, String alias) {
24226         if (packageName == null || alias == null) {
24227             return null;
24228         }
24229         synchronized(mPackages) {
24230             final PackageParser.Package pkg = mPackages.get(packageName);
24231             if (pkg == null) {
24232                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24233                 throw new IllegalArgumentException("Unknown package: " + packageName);
24234             }
24235             final PackageSetting ps = (PackageSetting) pkg.mExtras;
24236             if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24237                 Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24238                 throw new IllegalArgumentException("Unknown package: " + packageName);
24239             }
24240             KeySetManagerService ksms = mSettings.mKeySetManagerService;
24241             return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24242         }
24243     }
24244
24245     @Override
24246     public KeySet getSigningKeySet(String packageName) {
24247         if (packageName == null) {
24248             return null;
24249         }
24250         synchronized(mPackages) {
24251             final int callingUid = Binder.getCallingUid();
24252             final int callingUserId = UserHandle.getUserId(callingUid);
24253             final PackageParser.Package pkg = mPackages.get(packageName);
24254             if (pkg == null) {
24255                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24256                 throw new IllegalArgumentException("Unknown package: " + packageName);
24257             }
24258             final PackageSetting ps = (PackageSetting) pkg.mExtras;
24259             if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24260                 // filter and pretend the package doesn't exist
24261                 Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24262                         + ", uid:" + callingUid);
24263                 throw new IllegalArgumentException("Unknown package: " + packageName);
24264             }
24265             if (pkg.applicationInfo.uid != callingUid
24266                     && Process.SYSTEM_UID != callingUid) {
24267                 throw new SecurityException("May not access signing KeySet of other apps.");
24268             }
24269             KeySetManagerService ksms = mSettings.mKeySetManagerService;
24270             return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24271         }
24272     }
24273
24274     @Override
24275     public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24276         final int callingUid = Binder.getCallingUid();
24277         if (getInstantAppPackageName(callingUid) != null) {
24278             return false;
24279         }
24280         if (packageName == null || ks == null) {
24281             return false;
24282         }
24283         synchronized(mPackages) {
24284             final PackageParser.Package pkg = mPackages.get(packageName);
24285             if (pkg == null
24286                     || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24287                             UserHandle.getUserId(callingUid))) {
24288                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24289                 throw new IllegalArgumentException("Unknown package: " + packageName);
24290             }
24291             IBinder ksh = ks.getToken();
24292             if (ksh instanceof KeySetHandle) {
24293                 KeySetManagerService ksms = mSettings.mKeySetManagerService;
24294                 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24295             }
24296             return false;
24297         }
24298     }
24299
24300     @Override
24301     public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24302         final int callingUid = Binder.getCallingUid();
24303         if (getInstantAppPackageName(callingUid) != null) {
24304             return false;
24305         }
24306         if (packageName == null || ks == null) {
24307             return false;
24308         }
24309         synchronized(mPackages) {
24310             final PackageParser.Package pkg = mPackages.get(packageName);
24311             if (pkg == null
24312                     || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24313                             UserHandle.getUserId(callingUid))) {
24314                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24315                 throw new IllegalArgumentException("Unknown package: " + packageName);
24316             }
24317             IBinder ksh = ks.getToken();
24318             if (ksh instanceof KeySetHandle) {
24319                 KeySetManagerService ksms = mSettings.mKeySetManagerService;
24320                 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24321             }
24322             return false;
24323         }
24324     }
24325
24326     private void deletePackageIfUnusedLPr(final String packageName) {
24327         PackageSetting ps = mSettings.mPackages.get(packageName);
24328         if (ps == null) {
24329             return;
24330         }
24331         if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24332             // TODO Implement atomic delete if package is unused
24333             // It is currently possible that the package will be deleted even if it is installed
24334             // after this method returns.
24335             mHandler.post(new Runnable() {
24336                 public void run() {
24337                     deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24338                             0, PackageManager.DELETE_ALL_USERS);
24339                 }
24340             });
24341         }
24342     }
24343
24344     /**
24345      * Check and throw if the given before/after packages would be considered a
24346      * downgrade.
24347      */
24348     private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24349             throws PackageManagerException {
24350         if (after.versionCode < before.mVersionCode) {
24351             throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24352                     "Update version code " + after.versionCode + " is older than current "
24353                     + before.mVersionCode);
24354         } else if (after.versionCode == before.mVersionCode) {
24355             if (after.baseRevisionCode < before.baseRevisionCode) {
24356                 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24357                         "Update base revision code " + after.baseRevisionCode
24358                         + " is older than current " + before.baseRevisionCode);
24359             }
24360
24361             if (!ArrayUtils.isEmpty(after.splitNames)) {
24362                 for (int i = 0; i < after.splitNames.length; i++) {
24363                     final String splitName = after.splitNames[i];
24364                     final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24365                     if (j != -1) {
24366                         if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24367                             throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24368                                     "Update split " + splitName + " revision code "
24369                                     + after.splitRevisionCodes[i] + " is older than current "
24370                                     + before.splitRevisionCodes[j]);
24371                         }
24372                     }
24373                 }
24374             }
24375         }
24376     }
24377
24378     private static class MoveCallbacks extends Handler {
24379         private static final int MSG_CREATED = 1;
24380         private static final int MSG_STATUS_CHANGED = 2;
24381
24382         private final RemoteCallbackList<IPackageMoveObserver>
24383                 mCallbacks = new RemoteCallbackList<>();
24384
24385         private final SparseIntArray mLastStatus = new SparseIntArray();
24386
24387         public MoveCallbacks(Looper looper) {
24388             super(looper);
24389         }
24390
24391         public void register(IPackageMoveObserver callback) {
24392             mCallbacks.register(callback);
24393         }
24394
24395         public void unregister(IPackageMoveObserver callback) {
24396             mCallbacks.unregister(callback);
24397         }
24398
24399         @Override
24400         public void handleMessage(Message msg) {
24401             final SomeArgs args = (SomeArgs) msg.obj;
24402             final int n = mCallbacks.beginBroadcast();
24403             for (int i = 0; i < n; i++) {
24404                 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24405                 try {
24406                     invokeCallback(callback, msg.what, args);
24407                 } catch (RemoteException ignored) {
24408                 }
24409             }
24410             mCallbacks.finishBroadcast();
24411             args.recycle();
24412         }
24413
24414         private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24415                 throws RemoteException {
24416             switch (what) {
24417                 case MSG_CREATED: {
24418                     callback.onCreated(args.argi1, (Bundle) args.arg2);
24419                     break;
24420                 }
24421                 case MSG_STATUS_CHANGED: {
24422                     callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24423                     break;
24424                 }
24425             }
24426         }
24427
24428         private void notifyCreated(int moveId, Bundle extras) {
24429             Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24430
24431             final SomeArgs args = SomeArgs.obtain();
24432             args.argi1 = moveId;
24433             args.arg2 = extras;
24434             obtainMessage(MSG_CREATED, args).sendToTarget();
24435         }
24436
24437         private void notifyStatusChanged(int moveId, int status) {
24438             notifyStatusChanged(moveId, status, -1);
24439         }
24440
24441         private void notifyStatusChanged(int moveId, int status, long estMillis) {
24442             Slog.v(TAG, "Move " + moveId + " status " + status);
24443
24444             final SomeArgs args = SomeArgs.obtain();
24445             args.argi1 = moveId;
24446             args.argi2 = status;
24447             args.arg3 = estMillis;
24448             obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24449
24450             synchronized (mLastStatus) {
24451                 mLastStatus.put(moveId, status);
24452             }
24453         }
24454     }
24455
24456     private final static class OnPermissionChangeListeners extends Handler {
24457         private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24458
24459         private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24460                 new RemoteCallbackList<>();
24461
24462         public OnPermissionChangeListeners(Looper looper) {
24463             super(looper);
24464         }
24465
24466         @Override
24467         public void handleMessage(Message msg) {
24468             switch (msg.what) {
24469                 case MSG_ON_PERMISSIONS_CHANGED: {
24470                     final int uid = msg.arg1;
24471                     handleOnPermissionsChanged(uid);
24472                 } break;
24473             }
24474         }
24475
24476         public void addListenerLocked(IOnPermissionsChangeListener listener) {
24477             mPermissionListeners.register(listener);
24478
24479         }
24480
24481         public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24482             mPermissionListeners.unregister(listener);
24483         }
24484
24485         public void onPermissionsChanged(int uid) {
24486             if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24487                 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24488             }
24489         }
24490
24491         private void handleOnPermissionsChanged(int uid) {
24492             final int count = mPermissionListeners.beginBroadcast();
24493             try {
24494                 for (int i = 0; i < count; i++) {
24495                     IOnPermissionsChangeListener callback = mPermissionListeners
24496                             .getBroadcastItem(i);
24497                     try {
24498                         callback.onPermissionsChanged(uid);
24499                     } catch (RemoteException e) {
24500                         Log.e(TAG, "Permission listener is dead", e);
24501                     }
24502                 }
24503             } finally {
24504                 mPermissionListeners.finishBroadcast();
24505             }
24506         }
24507     }
24508
24509     private class PackageManagerInternalImpl extends PackageManagerInternal {
24510         @Override
24511         public void setLocationPackagesProvider(PackagesProvider provider) {
24512             synchronized (mPackages) {
24513                 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24514             }
24515         }
24516
24517         @Override
24518         public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24519             synchronized (mPackages) {
24520                 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24521             }
24522         }
24523
24524         @Override
24525         public void setSmsAppPackagesProvider(PackagesProvider provider) {
24526             synchronized (mPackages) {
24527                 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24528             }
24529         }
24530
24531         @Override
24532         public void setDialerAppPackagesProvider(PackagesProvider provider) {
24533             synchronized (mPackages) {
24534                 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24535             }
24536         }
24537
24538         @Override
24539         public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24540             synchronized (mPackages) {
24541                 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24542             }
24543         }
24544
24545         @Override
24546         public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24547             synchronized (mPackages) {
24548                 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24549             }
24550         }
24551
24552         @Override
24553         public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24554             synchronized (mPackages) {
24555                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24556                         packageName, userId);
24557             }
24558         }
24559
24560         @Override
24561         public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24562             synchronized (mPackages) {
24563                 mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24564                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24565                         packageName, userId);
24566             }
24567         }
24568
24569         @Override
24570         public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24571             synchronized (mPackages) {
24572                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24573                         packageName, userId);
24574             }
24575         }
24576
24577         @Override
24578         public void setKeepUninstalledPackages(final List<String> packageList) {
24579             Preconditions.checkNotNull(packageList);
24580             List<String> removedFromList = null;
24581             synchronized (mPackages) {
24582                 if (mKeepUninstalledPackages != null) {
24583                     final int packagesCount = mKeepUninstalledPackages.size();
24584                     for (int i = 0; i < packagesCount; i++) {
24585                         String oldPackage = mKeepUninstalledPackages.get(i);
24586                         if (packageList != null && packageList.contains(oldPackage)) {
24587                             continue;
24588                         }
24589                         if (removedFromList == null) {
24590                             removedFromList = new ArrayList<>();
24591                         }
24592                         removedFromList.add(oldPackage);
24593                     }
24594                 }
24595                 mKeepUninstalledPackages = new ArrayList<>(packageList);
24596                 if (removedFromList != null) {
24597                     final int removedCount = removedFromList.size();
24598                     for (int i = 0; i < removedCount; i++) {
24599                         deletePackageIfUnusedLPr(removedFromList.get(i));
24600                     }
24601                 }
24602             }
24603         }
24604
24605         @Override
24606         public boolean isPermissionsReviewRequired(String packageName, int userId) {
24607             synchronized (mPackages) {
24608                 // If we do not support permission review, done.
24609                 if (!mPermissionReviewRequired) {
24610                     return false;
24611                 }
24612
24613                 PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24614                 if (packageSetting == null) {
24615                     return false;
24616                 }
24617
24618                 // Permission review applies only to apps not supporting the new permission model.
24619                 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24620                     return false;
24621                 }
24622
24623                 // Legacy apps have the permission and get user consent on launch.
24624                 PermissionsState permissionsState = packageSetting.getPermissionsState();
24625                 return permissionsState.isPermissionReviewRequired(userId);
24626             }
24627         }
24628
24629         @Override
24630         public PackageInfo getPackageInfo(
24631                 String packageName, int flags, int filterCallingUid, int userId) {
24632             return PackageManagerService.this
24633                     .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24634                             flags, filterCallingUid, userId);
24635         }
24636
24637         @Override
24638         public ApplicationInfo getApplicationInfo(
24639                 String packageName, int flags, int filterCallingUid, int userId) {
24640             return PackageManagerService.this
24641                     .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24642         }
24643
24644         @Override
24645         public ActivityInfo getActivityInfo(
24646                 ComponentName component, int flags, int filterCallingUid, int userId) {
24647             return PackageManagerService.this
24648                     .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24649         }
24650
24651         @Override
24652         public List<ResolveInfo> queryIntentActivities(
24653                 Intent intent, int flags, int filterCallingUid, int userId) {
24654             final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24655             return PackageManagerService.this
24656                     .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24657                             userId, false /*resolveForStart*/);
24658         }
24659
24660         @Override
24661         public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24662                 int userId) {
24663             return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24664         }
24665
24666         @Override
24667         public void setDeviceAndProfileOwnerPackages(
24668                 int deviceOwnerUserId, String deviceOwnerPackage,
24669                 SparseArray<String> profileOwnerPackages) {
24670             mProtectedPackages.setDeviceAndProfileOwnerPackages(
24671                     deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24672         }
24673
24674         @Override
24675         public boolean isPackageDataProtected(int userId, String packageName) {
24676             return mProtectedPackages.isPackageDataProtected(userId, packageName);
24677         }
24678
24679         @Override
24680         public boolean isPackageEphemeral(int userId, String packageName) {
24681             synchronized (mPackages) {
24682                 final PackageSetting ps = mSettings.mPackages.get(packageName);
24683                 return ps != null ? ps.getInstantApp(userId) : false;
24684             }
24685         }
24686
24687         @Override
24688         public boolean wasPackageEverLaunched(String packageName, int userId) {
24689             synchronized (mPackages) {
24690                 return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24691             }
24692         }
24693
24694         @Override
24695         public void grantRuntimePermission(String packageName, String name, int userId,
24696                 boolean overridePolicy) {
24697             PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24698                     overridePolicy);
24699         }
24700
24701         @Override
24702         public void revokeRuntimePermission(String packageName, String name, int userId,
24703                 boolean overridePolicy) {
24704             PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24705                     overridePolicy);
24706         }
24707
24708         @Override
24709         public String getNameForUid(int uid) {
24710             return PackageManagerService.this.getNameForUid(uid);
24711         }
24712
24713         @Override
24714         public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24715                 Intent origIntent, String resolvedType, String callingPackage,
24716                 Bundle verificationBundle, int userId) {
24717             PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24718                     responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24719                     userId);
24720         }
24721
24722         @Override
24723         public void grantEphemeralAccess(int userId, Intent intent,
24724                 int targetAppId, int ephemeralAppId) {
24725             synchronized (mPackages) {
24726                 mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24727                         targetAppId, ephemeralAppId);
24728             }
24729         }
24730
24731         @Override
24732         public boolean isInstantAppInstallerComponent(ComponentName component) {
24733             synchronized (mPackages) {
24734                 return mInstantAppInstallerActivity != null
24735                         && mInstantAppInstallerActivity.getComponentName().equals(component);
24736             }
24737         }
24738
24739         @Override
24740         public void pruneInstantApps() {
24741             mInstantAppRegistry.pruneInstantApps();
24742         }
24743
24744         @Override
24745         public String getSetupWizardPackageName() {
24746             return mSetupWizardPackage;
24747         }
24748
24749         public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24750             if (policy != null) {
24751                 mExternalSourcesPolicy = policy;
24752             }
24753         }
24754
24755         @Override
24756         public boolean isPackagePersistent(String packageName) {
24757             synchronized (mPackages) {
24758                 PackageParser.Package pkg = mPackages.get(packageName);
24759                 return pkg != null
24760                         ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24761                                         | ApplicationInfo.FLAG_PERSISTENT)) ==
24762                                 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24763                         : false;
24764             }
24765         }
24766
24767         @Override
24768         public List<PackageInfo> getOverlayPackages(int userId) {
24769             final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24770             synchronized (mPackages) {
24771                 for (PackageParser.Package p : mPackages.values()) {
24772                     if (p.mOverlayTarget != null) {
24773                         PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24774                         if (pkg != null) {
24775                             overlayPackages.add(pkg);
24776                         }
24777                     }
24778                 }
24779             }
24780             return overlayPackages;
24781         }
24782
24783         @Override
24784         public List<String> getTargetPackageNames(int userId) {
24785             List<String> targetPackages = new ArrayList<>();
24786             synchronized (mPackages) {
24787                 for (PackageParser.Package p : mPackages.values()) {
24788                     if (p.mOverlayTarget == null) {
24789                         targetPackages.add(p.packageName);
24790                     }
24791                 }
24792             }
24793             return targetPackages;
24794         }
24795
24796         @Override
24797         public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24798                 @Nullable List<String> overlayPackageNames) {
24799             synchronized (mPackages) {
24800                 if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24801                     Slog.e(TAG, "failed to find package " + targetPackageName);
24802                     return false;
24803                 }
24804                 ArrayList<String> overlayPaths = null;
24805                 if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24806                     final int N = overlayPackageNames.size();
24807                     overlayPaths = new ArrayList<>(N);
24808                     for (int i = 0; i < N; i++) {
24809                         final String packageName = overlayPackageNames.get(i);
24810                         final PackageParser.Package pkg = mPackages.get(packageName);
24811                         if (pkg == null) {
24812                             Slog.e(TAG, "failed to find package " + packageName);
24813                             return false;
24814                         }
24815                         overlayPaths.add(pkg.baseCodePath);
24816                     }
24817                 }
24818
24819                 final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24820                 ps.setOverlayPaths(overlayPaths, userId);
24821                 return true;
24822             }
24823         }
24824
24825         @Override
24826         public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24827                 int flags, int userId) {
24828             return resolveIntentInternal(
24829                     intent, resolvedType, flags, userId, true /*resolveForStart*/);
24830         }
24831
24832         @Override
24833         public ResolveInfo resolveService(Intent intent, String resolvedType,
24834                 int flags, int userId, int callingUid) {
24835             return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24836         }
24837
24838         @Override
24839         public void addIsolatedUid(int isolatedUid, int ownerUid) {
24840             synchronized (mPackages) {
24841                 mIsolatedOwners.put(isolatedUid, ownerUid);
24842             }
24843         }
24844
24845         @Override
24846         public void removeIsolatedUid(int isolatedUid) {
24847             synchronized (mPackages) {
24848                 mIsolatedOwners.delete(isolatedUid);
24849             }
24850         }
24851
24852         @Override
24853         public int getUidTargetSdkVersion(int uid) {
24854             synchronized (mPackages) {
24855                 return getUidTargetSdkVersionLockedLPr(uid);
24856             }
24857         }
24858
24859         @Override
24860         public boolean canAccessInstantApps(int callingUid, int userId) {
24861             return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24862         }
24863     }
24864
24865     @Override
24866     public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24867         enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24868         synchronized (mPackages) {
24869             final long identity = Binder.clearCallingIdentity();
24870             try {
24871                 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24872                         packageNames, userId);
24873             } finally {
24874                 Binder.restoreCallingIdentity(identity);
24875             }
24876         }
24877     }
24878
24879     @Override
24880     public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24881         enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24882         synchronized (mPackages) {
24883             final long identity = Binder.clearCallingIdentity();
24884             try {
24885                 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24886                         packageNames, userId);
24887             } finally {
24888                 Binder.restoreCallingIdentity(identity);
24889             }
24890         }
24891     }
24892
24893     private static void enforceSystemOrPhoneCaller(String tag) {
24894         int callingUid = Binder.getCallingUid();
24895         if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24896             throw new SecurityException(
24897                     "Cannot call " + tag + " from UID " + callingUid);
24898         }
24899     }
24900
24901     boolean isHistoricalPackageUsageAvailable() {
24902         return mPackageUsage.isHistoricalPackageUsageAvailable();
24903     }
24904
24905     /**
24906      * Return a <b>copy</b> of the collection of packages known to the package manager.
24907      * @return A copy of the values of mPackages.
24908      */
24909     Collection<PackageParser.Package> getPackages() {
24910         synchronized (mPackages) {
24911             return new ArrayList<>(mPackages.values());
24912         }
24913     }
24914
24915     /**
24916      * Logs process start information (including base APK hash) to the security log.
24917      * @hide
24918      */
24919     @Override
24920     public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24921             String apkFile, int pid) {
24922         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24923             return;
24924         }
24925         if (!SecurityLog.isLoggingEnabled()) {
24926             return;
24927         }
24928         Bundle data = new Bundle();
24929         data.putLong("startTimestamp", System.currentTimeMillis());
24930         data.putString("processName", processName);
24931         data.putInt("uid", uid);
24932         data.putString("seinfo", seinfo);
24933         data.putString("apkFile", apkFile);
24934         data.putInt("pid", pid);
24935         Message msg = mProcessLoggingHandler.obtainMessage(
24936                 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24937         msg.setData(data);
24938         mProcessLoggingHandler.sendMessage(msg);
24939     }
24940
24941     public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24942         return mCompilerStats.getPackageStats(pkgName);
24943     }
24944
24945     public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24946         return getOrCreateCompilerPackageStats(pkg.packageName);
24947     }
24948
24949     public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24950         return mCompilerStats.getOrCreatePackageStats(pkgName);
24951     }
24952
24953     public void deleteCompilerPackageStats(String pkgName) {
24954         mCompilerStats.deletePackageStats(pkgName);
24955     }
24956
24957     @Override
24958     public int getInstallReason(String packageName, int userId) {
24959         final int callingUid = Binder.getCallingUid();
24960         enforceCrossUserPermission(callingUid, userId,
24961                 true /* requireFullPermission */, false /* checkShell */,
24962                 "get install reason");
24963         synchronized (mPackages) {
24964             final PackageSetting ps = mSettings.mPackages.get(packageName);
24965             if (filterAppAccessLPr(ps, callingUid, userId)) {
24966                 return PackageManager.INSTALL_REASON_UNKNOWN;
24967             }
24968             if (ps != null) {
24969                 return ps.getInstallReason(userId);
24970             }
24971         }
24972         return PackageManager.INSTALL_REASON_UNKNOWN;
24973     }
24974
24975     @Override
24976     public boolean canRequestPackageInstalls(String packageName, int userId) {
24977         return canRequestPackageInstallsInternal(packageName, 0, userId,
24978                 true /* throwIfPermNotDeclared*/);
24979     }
24980
24981     private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24982             boolean throwIfPermNotDeclared) {
24983         int callingUid = Binder.getCallingUid();
24984         int uid = getPackageUid(packageName, 0, userId);
24985         if (callingUid != uid && callingUid != Process.ROOT_UID
24986                 && callingUid != Process.SYSTEM_UID) {
24987             throw new SecurityException(
24988                     "Caller uid " + callingUid + " does not own package " + packageName);
24989         }
24990         ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24991         if (info == null) {
24992             return false;
24993         }
24994         if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24995             return false;
24996         }
24997         String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24998         String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24999         if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25000             if (throwIfPermNotDeclared) {
25001                 throw new SecurityException("Need to declare " + appOpPermission
25002                         + " to call this api");
25003             } else {
25004                 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25005                 return false;
25006             }
25007         }
25008         if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25009             return false;
25010         }
25011         if (mExternalSourcesPolicy != null) {
25012             int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25013             return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25014         }
25015         return false;
25016     }
25017
25018     @Override
25019     public ComponentName getInstantAppResolverSettingsComponent() {
25020         return mInstantAppResolverSettingsComponent;
25021     }
25022
25023     @Override
25024     public ComponentName getInstantAppInstallerComponent() {
25025         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25026             return null;
25027         }
25028         return mInstantAppInstallerActivity == null
25029                 ? null : mInstantAppInstallerActivity.getComponentName();
25030     }
25031
25032     @Override
25033     public String getInstantAppAndroidId(String packageName, int userId) {
25034         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25035                 "getInstantAppAndroidId");
25036         enforceCrossUserPermission(Binder.getCallingUid(), userId,
25037                 true /* requireFullPermission */, false /* checkShell */,
25038                 "getInstantAppAndroidId");
25039         // Make sure the target is an Instant App.
25040         if (!isInstantApp(packageName, userId)) {
25041             return null;
25042         }
25043         synchronized (mPackages) {
25044             return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25045         }
25046     }
25047 }
25048
25049 interface PackageSender {
25050     void sendPackageBroadcast(final String action, final String pkg,
25051         final Bundle extras, final int flags, final String targetPkg,
25052         final IIntentReceiver finishedReceiver, final int[] userIds);
25053     void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
25054         int appId, int... userIds);
25055 }