OSDN Git Service

DO NOT MERGE. Grant MMS Uri permissions as the calling UID. am: a78841ebd4 -s ours...
[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.READ_EXTERNAL_STORAGE;
20 import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21 import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27 import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28 import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29 import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32 import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35 import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36 import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37 import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
39 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40 import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
41 import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
42 import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
43 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
44 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
45 import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
46 import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
47 import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
48 import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
49 import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
50 import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51 import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52 import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53 import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54 import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55 import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
58 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
59 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
60 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
61 import static android.content.pm.PackageManager.MATCH_ALL;
62 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
63 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
64 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
65 import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
66 import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
67 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
68 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
69 import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
70 import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
71 import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
72 import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
73 import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
74 import static android.content.pm.PackageManager.PERMISSION_DENIED;
75 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
76 import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
77 import static android.content.pm.PackageParser.isApkFile;
78 import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
79 import static android.system.OsConstants.O_CREAT;
80 import static android.system.OsConstants.O_RDWR;
81
82 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
83 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
84 import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
85 import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
86 import static com.android.internal.util.ArrayUtils.appendInt;
87 import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
88 import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
89 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
90 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
91 import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
92 import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
93 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
94 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
95 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
96 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
97 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
98 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
99
100 import android.Manifest;
101 import android.annotation.NonNull;
102 import android.annotation.Nullable;
103 import android.app.ActivityManager;
104 import android.app.ActivityManagerNative;
105 import android.app.IActivityManager;
106 import android.app.ResourcesManager;
107 import android.app.admin.IDevicePolicyManager;
108 import android.app.admin.SecurityLog;
109 import android.app.backup.IBackupManager;
110 import android.content.BroadcastReceiver;
111 import android.content.ComponentName;
112 import android.content.ContentResolver;
113 import android.content.Context;
114 import android.content.IIntentReceiver;
115 import android.content.Intent;
116 import android.content.IntentFilter;
117 import android.content.IntentSender;
118 import android.content.IntentSender.SendIntentException;
119 import android.content.ServiceConnection;
120 import android.content.pm.ActivityInfo;
121 import android.content.pm.ApplicationInfo;
122 import android.content.pm.AppsQueryHelper;
123 import android.content.pm.ComponentInfo;
124 import android.content.pm.EphemeralApplicationInfo;
125 import android.content.pm.EphemeralResolveInfo;
126 import android.content.pm.EphemeralResolveInfo.EphemeralDigest;
127 import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
128 import android.content.pm.FeatureInfo;
129 import android.content.pm.IOnPermissionsChangeListener;
130 import android.content.pm.IPackageDataObserver;
131 import android.content.pm.IPackageDeleteObserver;
132 import android.content.pm.IPackageDeleteObserver2;
133 import android.content.pm.IPackageInstallObserver2;
134 import android.content.pm.IPackageInstaller;
135 import android.content.pm.IPackageManager;
136 import android.content.pm.IPackageMoveObserver;
137 import android.content.pm.IPackageStatsObserver;
138 import android.content.pm.InstrumentationInfo;
139 import android.content.pm.IntentFilterVerificationInfo;
140 import android.content.pm.KeySet;
141 import android.content.pm.PackageCleanItem;
142 import android.content.pm.PackageInfo;
143 import android.content.pm.PackageInfoLite;
144 import android.content.pm.PackageInstaller;
145 import android.content.pm.PackageManager;
146 import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
147 import android.content.pm.PackageManagerInternal;
148 import android.content.pm.PackageParser;
149 import android.content.pm.PackageParser.ActivityIntentInfo;
150 import android.content.pm.PackageParser.PackageLite;
151 import android.content.pm.PackageParser.PackageParserException;
152 import android.content.pm.PackageStats;
153 import android.content.pm.PackageUserState;
154 import android.content.pm.ParceledListSlice;
155 import android.content.pm.PermissionGroupInfo;
156 import android.content.pm.PermissionInfo;
157 import android.content.pm.ProviderInfo;
158 import android.content.pm.ResolveInfo;
159 import android.content.pm.ServiceInfo;
160 import android.content.pm.Signature;
161 import android.content.pm.UserInfo;
162 import android.content.pm.VerifierDeviceIdentity;
163 import android.content.pm.VerifierInfo;
164 import android.content.res.Resources;
165 import android.graphics.Bitmap;
166 import android.hardware.display.DisplayManager;
167 import android.net.Uri;
168 import android.os.Binder;
169 import android.os.Build;
170 import android.os.Bundle;
171 import android.os.Debug;
172 import android.os.Environment;
173 import android.os.Environment.UserEnvironment;
174 import android.os.FileUtils;
175 import android.os.Handler;
176 import android.os.IBinder;
177 import android.os.Looper;
178 import android.os.Message;
179 import android.os.Parcel;
180 import android.os.ParcelFileDescriptor;
181 import android.os.PatternMatcher;
182 import android.os.Process;
183 import android.os.RemoteCallbackList;
184 import android.os.RemoteException;
185 import android.os.ResultReceiver;
186 import android.os.SELinux;
187 import android.os.ServiceManager;
188 import android.os.SystemClock;
189 import android.os.SystemProperties;
190 import android.os.Trace;
191 import android.os.UserHandle;
192 import android.os.UserManager;
193 import android.os.UserManagerInternal;
194 import android.os.storage.IMountService;
195 import android.os.storage.MountServiceInternal;
196 import android.os.storage.StorageEventListener;
197 import android.os.storage.StorageManager;
198 import android.os.storage.VolumeInfo;
199 import android.os.storage.VolumeRecord;
200 import android.provider.Settings.Global;
201 import android.provider.Settings.Secure;
202 import android.security.KeyStore;
203 import android.security.SystemKeyStore;
204 import android.system.ErrnoException;
205 import android.system.Os;
206 import android.text.TextUtils;
207 import android.text.format.DateUtils;
208 import android.util.ArrayMap;
209 import android.util.ArraySet;
210 import android.util.DisplayMetrics;
211 import android.util.EventLog;
212 import android.util.ExceptionUtils;
213 import android.util.Log;
214 import android.util.LogPrinter;
215 import android.util.MathUtils;
216 import android.util.Pair;
217 import android.util.PrintStreamPrinter;
218 import android.util.Slog;
219 import android.util.SparseArray;
220 import android.util.SparseBooleanArray;
221 import android.util.SparseIntArray;
222 import android.util.Xml;
223 import android.util.jar.StrictJarFile;
224 import android.view.Display;
225
226 import com.android.internal.R;
227 import com.android.internal.annotations.GuardedBy;
228 import com.android.internal.app.IMediaContainerService;
229 import com.android.internal.app.ResolverActivity;
230 import com.android.internal.content.NativeLibraryHelper;
231 import com.android.internal.content.PackageHelper;
232 import com.android.internal.logging.MetricsLogger;
233 import com.android.internal.os.IParcelFileDescriptorFactory;
234 import com.android.internal.os.InstallerConnection.InstallerException;
235 import com.android.internal.os.SomeArgs;
236 import com.android.internal.os.Zygote;
237 import com.android.internal.telephony.CarrierAppUtils;
238 import com.android.internal.util.ArrayUtils;
239 import com.android.internal.util.FastPrintWriter;
240 import com.android.internal.util.FastXmlSerializer;
241 import com.android.internal.util.IndentingPrintWriter;
242 import com.android.internal.util.Preconditions;
243 import com.android.internal.util.XmlUtils;
244 import com.android.server.AttributeCache;
245 import com.android.server.EventLogTags;
246 import com.android.server.FgThread;
247 import com.android.server.IntentResolver;
248 import com.android.server.LocalServices;
249 import com.android.server.ServiceThread;
250 import com.android.server.SystemConfig;
251 import com.android.server.Watchdog;
252 import com.android.server.net.NetworkPolicyManagerInternal;
253 import com.android.server.pm.PermissionsState.PermissionState;
254 import com.android.server.pm.Settings.DatabaseVersion;
255 import com.android.server.pm.Settings.VersionInfo;
256 import com.android.server.storage.DeviceStorageMonitorInternal;
257
258 import dalvik.system.CloseGuard;
259 import dalvik.system.DexFile;
260 import dalvik.system.VMRuntime;
261
262 import libcore.io.IoUtils;
263 import libcore.util.EmptyArray;
264
265 import org.xmlpull.v1.XmlPullParser;
266 import org.xmlpull.v1.XmlPullParserException;
267 import org.xmlpull.v1.XmlSerializer;
268
269 import java.io.BufferedOutputStream;
270 import java.io.BufferedReader;
271 import java.io.ByteArrayInputStream;
272 import java.io.ByteArrayOutputStream;
273 import java.io.File;
274 import java.io.FileDescriptor;
275 import java.io.FileInputStream;
276 import java.io.FileNotFoundException;
277 import java.io.FileOutputStream;
278 import java.io.FileReader;
279 import java.io.FilenameFilter;
280 import java.io.IOException;
281 import java.io.PrintWriter;
282 import java.nio.charset.StandardCharsets;
283 import java.security.DigestInputStream;
284 import java.security.MessageDigest;
285 import java.security.NoSuchAlgorithmException;
286 import java.security.PublicKey;
287 import java.security.cert.Certificate;
288 import java.security.cert.CertificateEncodingException;
289 import java.security.cert.CertificateException;
290 import java.text.SimpleDateFormat;
291 import java.util.ArrayList;
292 import java.util.Arrays;
293 import java.util.Collection;
294 import java.util.Collections;
295 import java.util.Comparator;
296 import java.util.Date;
297 import java.util.HashSet;
298 import java.util.Iterator;
299 import java.util.List;
300 import java.util.Map;
301 import java.util.Objects;
302 import java.util.Set;
303 import java.util.concurrent.CountDownLatch;
304 import java.util.concurrent.TimeUnit;
305 import java.util.concurrent.atomic.AtomicBoolean;
306 import java.util.concurrent.atomic.AtomicInteger;
307
308 /**
309  * Keep track of all those APKs everywhere.
310  * <p>
311  * Internally there are two important locks:
312  * <ul>
313  * <li>{@link #mPackages} is used to guard all in-memory parsed package details
314  * and other related state. It is a fine-grained lock that should only be held
315  * momentarily, as it's one of the most contended locks in the system.
316  * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
317  * operations typically involve heavy lifting of application data on disk. Since
318  * {@code installd} is single-threaded, and it's operations can often be slow,
319  * this lock should never be acquired while already holding {@link #mPackages}.
320  * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
321  * holding {@link #mInstallLock}.
322  * </ul>
323  * Many internal methods rely on the caller to hold the appropriate locks, and
324  * this contract is expressed through method name suffixes:
325  * <ul>
326  * <li>fooLI(): the caller must hold {@link #mInstallLock}
327  * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
328  * being modified must be frozen
329  * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
330  * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
331  * </ul>
332  * <p>
333  * Because this class is very central to the platform's security; please run all
334  * CTS and unit tests whenever making modifications:
335  *
336  * <pre>
337  * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
338  * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
339  * </pre>
340  */
341 public class PackageManagerService extends IPackageManager.Stub {
342     static final String TAG = "PackageManager";
343     static final boolean DEBUG_SETTINGS = false;
344     static final boolean DEBUG_PREFERRED = false;
345     static final boolean DEBUG_UPGRADE = false;
346     static final boolean DEBUG_DOMAIN_VERIFICATION = false;
347     private static final boolean DEBUG_BACKUP = false;
348     private static final boolean DEBUG_INSTALL = false;
349     private static final boolean DEBUG_REMOVE = false;
350     private static final boolean DEBUG_BROADCASTS = false;
351     private static final boolean DEBUG_SHOW_INFO = false;
352     private static final boolean DEBUG_PACKAGE_INFO = false;
353     private static final boolean DEBUG_INTENT_MATCHING = false;
354     private static final boolean DEBUG_PACKAGE_SCANNING = false;
355     private static final boolean DEBUG_VERIFY = false;
356     private static final boolean DEBUG_FILTERS = false;
357
358     // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
359     // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
360     // user, but by default initialize to this.
361     static final boolean DEBUG_DEXOPT = false;
362
363     private static final boolean DEBUG_ABI_SELECTION = false;
364     private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
365     private static final boolean DEBUG_TRIAGED_MISSING = false;
366     private static final boolean DEBUG_APP_DATA = false;
367
368     static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
369
370     private static final boolean DISABLE_EPHEMERAL_APPS = false;
371     private static final boolean HIDE_EPHEMERAL_APIS = true;
372
373     private static final int RADIO_UID = Process.PHONE_UID;
374     private static final int LOG_UID = Process.LOG_UID;
375     private static final int NFC_UID = Process.NFC_UID;
376     private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
377     private static final int SHELL_UID = Process.SHELL_UID;
378
379     // Cap the size of permission trees that 3rd party apps can define
380     private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
381
382     // Suffix used during package installation when copying/moving
383     // package apks to install directory.
384     private static final String INSTALL_PACKAGE_SUFFIX = "-";
385
386     static final int SCAN_NO_DEX = 1<<1;
387     static final int SCAN_FORCE_DEX = 1<<2;
388     static final int SCAN_UPDATE_SIGNATURE = 1<<3;
389     static final int SCAN_NEW_INSTALL = 1<<4;
390     static final int SCAN_NO_PATHS = 1<<5;
391     static final int SCAN_UPDATE_TIME = 1<<6;
392     static final int SCAN_DEFER_DEX = 1<<7;
393     static final int SCAN_BOOTING = 1<<8;
394     static final int SCAN_TRUSTED_OVERLAY = 1<<9;
395     static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
396     static final int SCAN_REPLACING = 1<<11;
397     static final int SCAN_REQUIRE_KNOWN = 1<<12;
398     static final int SCAN_MOVE = 1<<13;
399     static final int SCAN_INITIAL = 1<<14;
400     static final int SCAN_CHECK_ONLY = 1<<15;
401     static final int SCAN_DONT_KILL_APP = 1<<17;
402     static final int SCAN_IGNORE_FROZEN = 1<<18;
403
404     static final int REMOVE_CHATTY = 1<<16;
405
406     private static final int[] EMPTY_INT_ARRAY = new int[0];
407
408     /**
409      * Timeout (in milliseconds) after which the watchdog should declare that
410      * our handler thread is wedged.  The usual default for such things is one
411      * minute but we sometimes do very lengthy I/O operations on this thread,
412      * such as installing multi-gigabyte applications, so ours needs to be longer.
413      */
414     private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
415
416     /**
417      * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
418      * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
419      * settings entry if available, otherwise we use the hardcoded default.  If it's been
420      * more than this long since the last fstrim, we force one during the boot sequence.
421      *
422      * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
423      * one gets run at the next available charging+idle time.  This final mandatory
424      * no-fstrim check kicks in only of the other scheduling criteria is never met.
425      */
426     private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
427
428     /**
429      * Whether verification is enabled by default.
430      */
431     private static final boolean DEFAULT_VERIFY_ENABLE = true;
432
433     /**
434      * The default maximum time to wait for the verification agent to return in
435      * milliseconds.
436      */
437     private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
438
439     /**
440      * The default response for package verification timeout.
441      *
442      * This can be either PackageManager.VERIFICATION_ALLOW or
443      * PackageManager.VERIFICATION_REJECT.
444      */
445     private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
446
447     static final String PLATFORM_PACKAGE_NAME = "android";
448
449     static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
450
451     static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
452             DEFAULT_CONTAINER_PACKAGE,
453             "com.android.defcontainer.DefaultContainerService");
454
455     private static final String KILL_APP_REASON_GIDS_CHANGED =
456             "permission grant or revoke changed gids";
457
458     private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
459             "permissions revoked";
460
461     private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
462
463     private static final String PACKAGE_SCHEME = "package";
464
465     private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
466     /**
467      * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
468      * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
469      * VENDOR_OVERLAY_DIR.
470      */
471     private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
472
473     private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
474     private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
475
476     /** Permission grant: not grant the permission. */
477     private static final int GRANT_DENIED = 1;
478
479     /** Permission grant: grant the permission as an install permission. */
480     private static final int GRANT_INSTALL = 2;
481
482     /** Permission grant: grant the permission as a runtime one. */
483     private static final int GRANT_RUNTIME = 3;
484
485     /** Permission grant: grant as runtime a permission that was granted as an install time one. */
486     private static final int GRANT_UPGRADE = 4;
487
488     /** Canonical intent used to identify what counts as a "web browser" app */
489     private static final Intent sBrowserIntent;
490     static {
491         sBrowserIntent = new Intent();
492         sBrowserIntent.setAction(Intent.ACTION_VIEW);
493         sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
494         sBrowserIntent.setData(Uri.parse("http:"));
495     }
496
497     /**
498      * The set of all protected actions [i.e. those actions for which a high priority
499      * intent filter is disallowed].
500      */
501     private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
502     static {
503         PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
504         PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
505         PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
506         PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
507     }
508
509     // Compilation reasons.
510     public static final int REASON_FIRST_BOOT = 0;
511     public static final int REASON_BOOT = 1;
512     public static final int REASON_INSTALL = 2;
513     public static final int REASON_BACKGROUND_DEXOPT = 3;
514     public static final int REASON_AB_OTA = 4;
515     public static final int REASON_NON_SYSTEM_LIBRARY = 5;
516     public static final int REASON_SHARED_APK = 6;
517     public static final int REASON_FORCED_DEXOPT = 7;
518     public static final int REASON_CORE_APP = 8;
519
520     public static final int REASON_LAST = REASON_CORE_APP;
521
522     /** Special library name that skips shared libraries check during compilation. */
523     private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
524
525     final ServiceThread mHandlerThread;
526
527     final PackageHandler mHandler;
528
529     private final ProcessLoggingHandler mProcessLoggingHandler;
530
531     /**
532      * Messages for {@link #mHandler} that need to wait for system ready before
533      * being dispatched.
534      */
535     private ArrayList<Message> mPostSystemReadyMessages;
536
537     final int mSdkVersion = Build.VERSION.SDK_INT;
538
539     final Context mContext;
540     final boolean mFactoryTest;
541     final boolean mOnlyCore;
542     final DisplayMetrics mMetrics;
543     final int mDefParseFlags;
544     final String[] mSeparateProcesses;
545     final boolean mIsUpgrade;
546     final boolean mIsPreNUpgrade;
547     final boolean mIsPreNMR1Upgrade;
548
549     @GuardedBy("mPackages")
550     private boolean mDexOptDialogShown;
551
552     /** The location for ASEC container files on internal storage. */
553     final String mAsecInternalPath;
554
555     // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
556     // LOCK HELD.  Can be called with mInstallLock held.
557     @GuardedBy("mInstallLock")
558     final Installer mInstaller;
559
560     /** Directory where installed third-party apps stored */
561     final File mAppInstallDir;
562     final File mEphemeralInstallDir;
563
564     /**
565      * Directory to which applications installed internally have their
566      * 32 bit native libraries copied.
567      */
568     private File mAppLib32InstallDir;
569
570     // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
571     // apps.
572     final File mDrmAppPrivateInstallDir;
573
574     // ----------------------------------------------------------------
575
576     // Lock for state used when installing and doing other long running
577     // operations.  Methods that must be called with this lock held have
578     // the suffix "LI".
579     final Object mInstallLock = new Object();
580
581     // ----------------------------------------------------------------
582
583     // Keys are String (package name), values are Package.  This also serves
584     // as the lock for the global state.  Methods that must be called with
585     // this lock held have the prefix "LP".
586     @GuardedBy("mPackages")
587     final ArrayMap<String, PackageParser.Package> mPackages =
588             new ArrayMap<String, PackageParser.Package>();
589
590     final ArrayMap<String, Set<String>> mKnownCodebase =
591             new ArrayMap<String, Set<String>>();
592
593     // Tracks available target package names -> overlay package paths.
594     final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
595         new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
596
597     /**
598      * Tracks new system packages [received in an OTA] that we expect to
599      * find updated user-installed versions. Keys are package name, values
600      * are package location.
601      */
602     final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
603     /**
604      * Tracks high priority intent filters for protected actions. During boot, certain
605      * filter actions are protected and should never be allowed to have a high priority
606      * intent filter for them. However, there is one, and only one exception -- the
607      * setup wizard. It must be able to define a high priority intent filter for these
608      * actions to ensure there are no escapes from the wizard. We need to delay processing
609      * of these during boot as we need to look at all of the system packages in order
610      * to know which component is the setup wizard.
611      */
612     private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
613     /**
614      * Whether or not processing protected filters should be deferred.
615      */
616     private boolean mDeferProtectedFilters = true;
617
618     /**
619      * Tracks existing system packages prior to receiving an OTA. Keys are package name.
620      */
621     final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
622     /**
623      * Whether or not system app permissions should be promoted from install to runtime.
624      */
625     boolean mPromoteSystemApps;
626
627     @GuardedBy("mPackages")
628     final Settings mSettings;
629
630     /**
631      * Set of package names that are currently "frozen", which means active
632      * surgery is being done on the code/data for that package. The platform
633      * will refuse to launch frozen packages to avoid race conditions.
634      *
635      * @see PackageFreezer
636      */
637     @GuardedBy("mPackages")
638     final ArraySet<String> mFrozenPackages = new ArraySet<>();
639
640     final ProtectedPackages mProtectedPackages;
641
642     boolean mFirstBoot;
643
644     // System configuration read by SystemConfig.
645     final int[] mGlobalGids;
646     final SparseArray<ArraySet<String>> mSystemPermissions;
647     final ArrayMap<String, FeatureInfo> mAvailableFeatures;
648
649     // If mac_permissions.xml was found for seinfo labeling.
650     boolean mFoundPolicyFile;
651
652     private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
653
654     public static final class SharedLibraryEntry {
655         public final String path;
656         public final String apk;
657
658         SharedLibraryEntry(String _path, String _apk) {
659             path = _path;
660             apk = _apk;
661         }
662     }
663
664     // Currently known shared libraries.
665     final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
666             new ArrayMap<String, SharedLibraryEntry>();
667
668     // All available activities, for your resolving pleasure.
669     final ActivityIntentResolver mActivities =
670             new ActivityIntentResolver();
671
672     // All available receivers, for your resolving pleasure.
673     final ActivityIntentResolver mReceivers =
674             new ActivityIntentResolver();
675
676     // All available services, for your resolving pleasure.
677     final ServiceIntentResolver mServices = new ServiceIntentResolver();
678
679     // All available providers, for your resolving pleasure.
680     final ProviderIntentResolver mProviders = new ProviderIntentResolver();
681
682     // Mapping from provider base names (first directory in content URI codePath)
683     // to the provider information.
684     final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
685             new ArrayMap<String, PackageParser.Provider>();
686
687     // Mapping from instrumentation class names to info about them.
688     final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
689             new ArrayMap<ComponentName, PackageParser.Instrumentation>();
690
691     // Mapping from permission names to info about them.
692     final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
693             new ArrayMap<String, PackageParser.PermissionGroup>();
694
695     // Packages whose data we have transfered into another package, thus
696     // should no longer exist.
697     final ArraySet<String> mTransferedPackages = new ArraySet<String>();
698
699     // Broadcast actions that are only available to the system.
700     final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
701
702     /** List of packages waiting for verification. */
703     final SparseArray<PackageVerificationState> mPendingVerification
704             = new SparseArray<PackageVerificationState>();
705
706     /** Set of packages associated with each app op permission. */
707     final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
708
709     final PackageInstallerService mInstallerService;
710
711     private final PackageDexOptimizer mPackageDexOptimizer;
712
713     private AtomicInteger mNextMoveId = new AtomicInteger();
714     private final MoveCallbacks mMoveCallbacks;
715
716     private final OnPermissionChangeListeners mOnPermissionChangeListeners;
717
718     // Cache of users who need badging.
719     SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
720
721     /** Token for keys in mPendingVerification. */
722     private int mPendingVerificationToken = 0;
723
724     volatile boolean mSystemReady;
725     volatile boolean mSafeMode;
726     volatile boolean mHasSystemUidErrors;
727
728     ApplicationInfo mAndroidApplication;
729     final ActivityInfo mResolveActivity = new ActivityInfo();
730     final ResolveInfo mResolveInfo = new ResolveInfo();
731     ComponentName mResolveComponentName;
732     PackageParser.Package mPlatformPackage;
733     ComponentName mCustomResolverComponentName;
734
735     boolean mResolverReplaced = false;
736
737     private final @Nullable ComponentName mIntentFilterVerifierComponent;
738     private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
739
740     private int mIntentFilterVerificationToken = 0;
741
742     /** Component that knows whether or not an ephemeral application exists */
743     final ComponentName mEphemeralResolverComponent;
744     /** The service connection to the ephemeral resolver */
745     final EphemeralResolverConnection mEphemeralResolverConnection;
746
747     /** Component used to install ephemeral applications */
748     final ComponentName mEphemeralInstallerComponent;
749     final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
750     final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
751
752     final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
753             = new SparseArray<IntentFilterVerificationState>();
754
755     final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
756
757     // List of packages names to keep cached, even if they are uninstalled for all users
758     private List<String> mKeepUninstalledPackages;
759
760     private UserManagerInternal mUserManagerInternal;
761
762     private static class IFVerificationParams {
763         PackageParser.Package pkg;
764         boolean replacing;
765         int userId;
766         int verifierUid;
767
768         public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
769                 int _userId, int _verifierUid) {
770             pkg = _pkg;
771             replacing = _replacing;
772             userId = _userId;
773             replacing = _replacing;
774             verifierUid = _verifierUid;
775         }
776     }
777
778     private interface IntentFilterVerifier<T extends IntentFilter> {
779         boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
780                                                T filter, String packageName);
781         void startVerifications(int userId);
782         void receiveVerificationResponse(int verificationId);
783     }
784
785     private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
786         private Context mContext;
787         private ComponentName mIntentFilterVerifierComponent;
788         private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
789
790         public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
791             mContext = context;
792             mIntentFilterVerifierComponent = verifierComponent;
793         }
794
795         private String getDefaultScheme() {
796             return IntentFilter.SCHEME_HTTPS;
797         }
798
799         @Override
800         public void startVerifications(int userId) {
801             // Launch verifications requests
802             int count = mCurrentIntentFilterVerifications.size();
803             for (int n=0; n<count; n++) {
804                 int verificationId = mCurrentIntentFilterVerifications.get(n);
805                 final IntentFilterVerificationState ivs =
806                         mIntentFilterVerificationStates.get(verificationId);
807
808                 String packageName = ivs.getPackageName();
809
810                 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
811                 final int filterCount = filters.size();
812                 ArraySet<String> domainsSet = new ArraySet<>();
813                 for (int m=0; m<filterCount; m++) {
814                     PackageParser.ActivityIntentInfo filter = filters.get(m);
815                     domainsSet.addAll(filter.getHostsList());
816                 }
817                 ArrayList<String> domainsList = new ArrayList<>(domainsSet);
818                 synchronized (mPackages) {
819                     if (mSettings.createIntentFilterVerificationIfNeededLPw(
820                             packageName, domainsList) != null) {
821                         scheduleWriteSettingsLocked();
822                     }
823                 }
824                 sendVerificationRequest(userId, verificationId, ivs);
825             }
826             mCurrentIntentFilterVerifications.clear();
827         }
828
829         private void sendVerificationRequest(int userId, int verificationId,
830                 IntentFilterVerificationState ivs) {
831
832             Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
833             verificationIntent.putExtra(
834                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
835                     verificationId);
836             verificationIntent.putExtra(
837                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
838                     getDefaultScheme());
839             verificationIntent.putExtra(
840                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
841                     ivs.getHostsString());
842             verificationIntent.putExtra(
843                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
844                     ivs.getPackageName());
845             verificationIntent.setComponent(mIntentFilterVerifierComponent);
846             verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
847
848             UserHandle user = new UserHandle(userId);
849             mContext.sendBroadcastAsUser(verificationIntent, user);
850             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
851                     "Sending IntentFilter verification broadcast");
852         }
853
854         public void receiveVerificationResponse(int verificationId) {
855             IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
856
857             final boolean verified = ivs.isVerified();
858
859             ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
860             final int count = filters.size();
861             if (DEBUG_DOMAIN_VERIFICATION) {
862                 Slog.i(TAG, "Received verification response " + verificationId
863                         + " for " + count + " filters, verified=" + verified);
864             }
865             for (int n=0; n<count; n++) {
866                 PackageParser.ActivityIntentInfo filter = filters.get(n);
867                 filter.setVerified(verified);
868
869                 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
870                         + " verified with result:" + verified + " and hosts:"
871                         + ivs.getHostsString());
872             }
873
874             mIntentFilterVerificationStates.remove(verificationId);
875
876             final String packageName = ivs.getPackageName();
877             IntentFilterVerificationInfo ivi = null;
878
879             synchronized (mPackages) {
880                 ivi = mSettings.getIntentFilterVerificationLPr(packageName);
881             }
882             if (ivi == null) {
883                 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
884                         + verificationId + " packageName:" + packageName);
885                 return;
886             }
887             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
888                     "Updating IntentFilterVerificationInfo for package " + packageName
889                             +" verificationId:" + verificationId);
890
891             synchronized (mPackages) {
892                 if (verified) {
893                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
894                 } else {
895                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
896                 }
897                 scheduleWriteSettingsLocked();
898
899                 final int userId = ivs.getUserId();
900                 if (userId != UserHandle.USER_ALL) {
901                     final int userStatus =
902                             mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
903
904                     int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
905                     boolean needUpdate = false;
906
907                     // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
908                     // already been set by the User thru the Disambiguation dialog
909                     switch (userStatus) {
910                         case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
911                             if (verified) {
912                                 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
913                             } else {
914                                 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
915                             }
916                             needUpdate = true;
917                             break;
918
919                         case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
920                             if (verified) {
921                                 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
922                                 needUpdate = true;
923                             }
924                             break;
925
926                         default:
927                             // Nothing to do
928                     }
929
930                     if (needUpdate) {
931                         mSettings.updateIntentFilterVerificationStatusLPw(
932                                 packageName, updatedStatus, userId);
933                         scheduleWritePackageRestrictionsLocked(userId);
934                     }
935                 }
936             }
937         }
938
939         @Override
940         public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
941                     ActivityIntentInfo filter, String packageName) {
942             if (!hasValidDomains(filter)) {
943                 return false;
944             }
945             IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
946             if (ivs == null) {
947                 ivs = createDomainVerificationState(verifierUid, userId, verificationId,
948                         packageName);
949             }
950             if (DEBUG_DOMAIN_VERIFICATION) {
951                 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
952             }
953             ivs.addFilter(filter);
954             return true;
955         }
956
957         private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
958                 int userId, int verificationId, String packageName) {
959             IntentFilterVerificationState ivs = new IntentFilterVerificationState(
960                     verifierUid, userId, packageName);
961             ivs.setPendingState();
962             synchronized (mPackages) {
963                 mIntentFilterVerificationStates.append(verificationId, ivs);
964                 mCurrentIntentFilterVerifications.add(verificationId);
965             }
966             return ivs;
967         }
968     }
969
970     private static boolean hasValidDomains(ActivityIntentInfo filter) {
971         return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
972                 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
973                         filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
974     }
975
976     // Set of pending broadcasts for aggregating enable/disable of components.
977     static class PendingPackageBroadcasts {
978         // for each user id, a map of <package name -> components within that package>
979         final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
980
981         public PendingPackageBroadcasts() {
982             mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
983         }
984
985         public ArrayList<String> get(int userId, String packageName) {
986             ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
987             return packages.get(packageName);
988         }
989
990         public void put(int userId, String packageName, ArrayList<String> components) {
991             ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
992             packages.put(packageName, components);
993         }
994
995         public void remove(int userId, String packageName) {
996             ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
997             if (packages != null) {
998                 packages.remove(packageName);
999             }
1000         }
1001
1002         public void remove(int userId) {
1003             mUidMap.remove(userId);
1004         }
1005
1006         public int userIdCount() {
1007             return mUidMap.size();
1008         }
1009
1010         public int userIdAt(int n) {
1011             return mUidMap.keyAt(n);
1012         }
1013
1014         public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1015             return mUidMap.get(userId);
1016         }
1017
1018         public int size() {
1019             // total number of pending broadcast entries across all userIds
1020             int num = 0;
1021             for (int i = 0; i< mUidMap.size(); i++) {
1022                 num += mUidMap.valueAt(i).size();
1023             }
1024             return num;
1025         }
1026
1027         public void clear() {
1028             mUidMap.clear();
1029         }
1030
1031         private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1032             ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1033             if (map == null) {
1034                 map = new ArrayMap<String, ArrayList<String>>();
1035                 mUidMap.put(userId, map);
1036             }
1037             return map;
1038         }
1039     }
1040     final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1041
1042     // Service Connection to remote media container service to copy
1043     // package uri's from external media onto secure containers
1044     // or internal storage.
1045     private IMediaContainerService mContainerService = null;
1046
1047     static final int SEND_PENDING_BROADCAST = 1;
1048     static final int MCS_BOUND = 3;
1049     static final int END_COPY = 4;
1050     static final int INIT_COPY = 5;
1051     static final int MCS_UNBIND = 6;
1052     static final int START_CLEANING_PACKAGE = 7;
1053     static final int FIND_INSTALL_LOC = 8;
1054     static final int POST_INSTALL = 9;
1055     static final int MCS_RECONNECT = 10;
1056     static final int MCS_GIVE_UP = 11;
1057     static final int UPDATED_MEDIA_STATUS = 12;
1058     static final int WRITE_SETTINGS = 13;
1059     static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1060     static final int PACKAGE_VERIFIED = 15;
1061     static final int CHECK_PENDING_VERIFICATION = 16;
1062     static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1063     static final int INTENT_FILTER_VERIFIED = 18;
1064     static final int WRITE_PACKAGE_LIST = 19;
1065
1066     static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1067
1068     // Delay time in millisecs
1069     static final int BROADCAST_DELAY = 10 * 1000;
1070
1071     static UserManagerService sUserManager;
1072
1073     // Stores a list of users whose package restrictions file needs to be updated
1074     private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1075
1076     final private DefaultContainerConnection mDefContainerConn =
1077             new DefaultContainerConnection();
1078     class DefaultContainerConnection implements ServiceConnection {
1079         public void onServiceConnected(ComponentName name, IBinder service) {
1080             if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1081             IMediaContainerService imcs =
1082                 IMediaContainerService.Stub.asInterface(service);
1083             mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1084         }
1085
1086         public void onServiceDisconnected(ComponentName name) {
1087             if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1088         }
1089     }
1090
1091     // Recordkeeping of restore-after-install operations that are currently in flight
1092     // between the Package Manager and the Backup Manager
1093     static class PostInstallData {
1094         public InstallArgs args;
1095         public PackageInstalledInfo res;
1096
1097         PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1098             args = _a;
1099             res = _r;
1100         }
1101     }
1102
1103     final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1104     int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1105
1106     // XML tags for backup/restore of various bits of state
1107     private static final String TAG_PREFERRED_BACKUP = "pa";
1108     private static final String TAG_DEFAULT_APPS = "da";
1109     private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1110
1111     private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1112     private static final String TAG_ALL_GRANTS = "rt-grants";
1113     private static final String TAG_GRANT = "grant";
1114     private static final String ATTR_PACKAGE_NAME = "pkg";
1115
1116     private static final String TAG_PERMISSION = "perm";
1117     private static final String ATTR_PERMISSION_NAME = "name";
1118     private static final String ATTR_IS_GRANTED = "g";
1119     private static final String ATTR_USER_SET = "set";
1120     private static final String ATTR_USER_FIXED = "fixed";
1121     private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1122
1123     // System/policy permission grants are not backed up
1124     private static final int SYSTEM_RUNTIME_GRANT_MASK =
1125             FLAG_PERMISSION_POLICY_FIXED
1126             | FLAG_PERMISSION_SYSTEM_FIXED
1127             | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1128
1129     // And we back up these user-adjusted states
1130     private static final int USER_RUNTIME_GRANT_MASK =
1131             FLAG_PERMISSION_USER_SET
1132             | FLAG_PERMISSION_USER_FIXED
1133             | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1134
1135     final @Nullable String mRequiredVerifierPackage;
1136     final @NonNull String mRequiredInstallerPackage;
1137     final @NonNull String mRequiredUninstallerPackage;
1138     final @Nullable String mSetupWizardPackage;
1139     final @Nullable String mStorageManagerPackage;
1140     final @NonNull String mServicesSystemSharedLibraryPackageName;
1141     final @NonNull String mSharedSystemSharedLibraryPackageName;
1142
1143     final boolean mPermissionReviewRequired;
1144
1145     private final PackageUsage mPackageUsage = new PackageUsage();
1146     private final CompilerStats mCompilerStats = new CompilerStats();
1147
1148     class PackageHandler extends Handler {
1149         private boolean mBound = false;
1150         final ArrayList<HandlerParams> mPendingInstalls =
1151             new ArrayList<HandlerParams>();
1152
1153         private boolean connectToService() {
1154             if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1155                     " DefaultContainerService");
1156             Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1157             Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1158             if (mContext.bindServiceAsUser(service, mDefContainerConn,
1159                     Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1160                 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1161                 mBound = true;
1162                 return true;
1163             }
1164             Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1165             return false;
1166         }
1167
1168         private void disconnectService() {
1169             mContainerService = null;
1170             mBound = false;
1171             Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1172             mContext.unbindService(mDefContainerConn);
1173             Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1174         }
1175
1176         PackageHandler(Looper looper) {
1177             super(looper);
1178         }
1179
1180         public void handleMessage(Message msg) {
1181             try {
1182                 doHandleMessage(msg);
1183             } finally {
1184                 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1185             }
1186         }
1187
1188         void doHandleMessage(Message msg) {
1189             switch (msg.what) {
1190                 case INIT_COPY: {
1191                     HandlerParams params = (HandlerParams) msg.obj;
1192                     int idx = mPendingInstalls.size();
1193                     if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1194                     // If a bind was already initiated we dont really
1195                     // need to do anything. The pending install
1196                     // will be processed later on.
1197                     if (!mBound) {
1198                         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1199                                 System.identityHashCode(mHandler));
1200                         // If this is the only one pending we might
1201                         // have to bind to the service again.
1202                         if (!connectToService()) {
1203                             Slog.e(TAG, "Failed to bind to media container service");
1204                             params.serviceError();
1205                             Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1206                                     System.identityHashCode(mHandler));
1207                             if (params.traceMethod != null) {
1208                                 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1209                                         params.traceCookie);
1210                             }
1211                             return;
1212                         } else {
1213                             // Once we bind to the service, the first
1214                             // pending request will be processed.
1215                             mPendingInstalls.add(idx, params);
1216                         }
1217                     } else {
1218                         mPendingInstalls.add(idx, params);
1219                         // Already bound to the service. Just make
1220                         // sure we trigger off processing the first request.
1221                         if (idx == 0) {
1222                             mHandler.sendEmptyMessage(MCS_BOUND);
1223                         }
1224                     }
1225                     break;
1226                 }
1227                 case MCS_BOUND: {
1228                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1229                     if (msg.obj != null) {
1230                         mContainerService = (IMediaContainerService) msg.obj;
1231                         Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1232                                 System.identityHashCode(mHandler));
1233                     }
1234                     if (mContainerService == null) {
1235                         if (!mBound) {
1236                             // Something seriously wrong since we are not bound and we are not
1237                             // waiting for connection. Bail out.
1238                             Slog.e(TAG, "Cannot bind to media container service");
1239                             for (HandlerParams params : mPendingInstalls) {
1240                                 // Indicate service bind error
1241                                 params.serviceError();
1242                                 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1243                                         System.identityHashCode(params));
1244                                 if (params.traceMethod != null) {
1245                                     Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1246                                             params.traceMethod, params.traceCookie);
1247                                 }
1248                                 return;
1249                             }
1250                             mPendingInstalls.clear();
1251                         } else {
1252                             Slog.w(TAG, "Waiting to connect to media container service");
1253                         }
1254                     } else if (mPendingInstalls.size() > 0) {
1255                         HandlerParams params = mPendingInstalls.get(0);
1256                         if (params != null) {
1257                             Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1258                                     System.identityHashCode(params));
1259                             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1260                             if (params.startCopy()) {
1261                                 // We are done...  look for more work or to
1262                                 // go idle.
1263                                 if (DEBUG_SD_INSTALL) Log.i(TAG,
1264                                         "Checking for more work or unbind...");
1265                                 // Delete pending install
1266                                 if (mPendingInstalls.size() > 0) {
1267                                     mPendingInstalls.remove(0);
1268                                 }
1269                                 if (mPendingInstalls.size() == 0) {
1270                                     if (mBound) {
1271                                         if (DEBUG_SD_INSTALL) Log.i(TAG,
1272                                                 "Posting delayed MCS_UNBIND");
1273                                         removeMessages(MCS_UNBIND);
1274                                         Message ubmsg = obtainMessage(MCS_UNBIND);
1275                                         // Unbind after a little delay, to avoid
1276                                         // continual thrashing.
1277                                         sendMessageDelayed(ubmsg, 10000);
1278                                     }
1279                                 } else {
1280                                     // There are more pending requests in queue.
1281                                     // Just post MCS_BOUND message to trigger processing
1282                                     // of next pending install.
1283                                     if (DEBUG_SD_INSTALL) Log.i(TAG,
1284                                             "Posting MCS_BOUND for next work");
1285                                     mHandler.sendEmptyMessage(MCS_BOUND);
1286                                 }
1287                             }
1288                             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1289                         }
1290                     } else {
1291                         // Should never happen ideally.
1292                         Slog.w(TAG, "Empty queue");
1293                     }
1294                     break;
1295                 }
1296                 case MCS_RECONNECT: {
1297                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1298                     if (mPendingInstalls.size() > 0) {
1299                         if (mBound) {
1300                             disconnectService();
1301                         }
1302                         if (!connectToService()) {
1303                             Slog.e(TAG, "Failed to bind to media container service");
1304                             for (HandlerParams params : mPendingInstalls) {
1305                                 // Indicate service bind error
1306                                 params.serviceError();
1307                                 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1308                                         System.identityHashCode(params));
1309                             }
1310                             mPendingInstalls.clear();
1311                         }
1312                     }
1313                     break;
1314                 }
1315                 case MCS_UNBIND: {
1316                     // If there is no actual work left, then time to unbind.
1317                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1318
1319                     if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1320                         if (mBound) {
1321                             if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1322
1323                             disconnectService();
1324                         }
1325                     } else if (mPendingInstalls.size() > 0) {
1326                         // There are more pending requests in queue.
1327                         // Just post MCS_BOUND message to trigger processing
1328                         // of next pending install.
1329                         mHandler.sendEmptyMessage(MCS_BOUND);
1330                     }
1331
1332                     break;
1333                 }
1334                 case MCS_GIVE_UP: {
1335                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1336                     HandlerParams params = mPendingInstalls.remove(0);
1337                     Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1338                             System.identityHashCode(params));
1339                     break;
1340                 }
1341                 case SEND_PENDING_BROADCAST: {
1342                     String packages[];
1343                     ArrayList<String> components[];
1344                     int size = 0;
1345                     int uids[];
1346                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1347                     synchronized (mPackages) {
1348                         if (mPendingBroadcasts == null) {
1349                             return;
1350                         }
1351                         size = mPendingBroadcasts.size();
1352                         if (size <= 0) {
1353                             // Nothing to be done. Just return
1354                             return;
1355                         }
1356                         packages = new String[size];
1357                         components = new ArrayList[size];
1358                         uids = new int[size];
1359                         int i = 0;  // filling out the above arrays
1360
1361                         for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1362                             int packageUserId = mPendingBroadcasts.userIdAt(n);
1363                             Iterator<Map.Entry<String, ArrayList<String>>> it
1364                                     = mPendingBroadcasts.packagesForUserId(packageUserId)
1365                                             .entrySet().iterator();
1366                             while (it.hasNext() && i < size) {
1367                                 Map.Entry<String, ArrayList<String>> ent = it.next();
1368                                 packages[i] = ent.getKey();
1369                                 components[i] = ent.getValue();
1370                                 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1371                                 uids[i] = (ps != null)
1372                                         ? UserHandle.getUid(packageUserId, ps.appId)
1373                                         : -1;
1374                                 i++;
1375                             }
1376                         }
1377                         size = i;
1378                         mPendingBroadcasts.clear();
1379                     }
1380                     // Send broadcasts
1381                     for (int i = 0; i < size; i++) {
1382                         sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1383                     }
1384                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1385                     break;
1386                 }
1387                 case START_CLEANING_PACKAGE: {
1388                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1389                     final String packageName = (String)msg.obj;
1390                     final int userId = msg.arg1;
1391                     final boolean andCode = msg.arg2 != 0;
1392                     synchronized (mPackages) {
1393                         if (userId == UserHandle.USER_ALL) {
1394                             int[] users = sUserManager.getUserIds();
1395                             for (int user : users) {
1396                                 mSettings.addPackageToCleanLPw(
1397                                         new PackageCleanItem(user, packageName, andCode));
1398                             }
1399                         } else {
1400                             mSettings.addPackageToCleanLPw(
1401                                     new PackageCleanItem(userId, packageName, andCode));
1402                         }
1403                     }
1404                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1405                     startCleaningPackages();
1406                 } break;
1407                 case POST_INSTALL: {
1408                     if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1409
1410                     PostInstallData data = mRunningInstalls.get(msg.arg1);
1411                     final boolean didRestore = (msg.arg2 != 0);
1412                     mRunningInstalls.delete(msg.arg1);
1413
1414                     if (data != null) {
1415                         InstallArgs args = data.args;
1416                         PackageInstalledInfo parentRes = data.res;
1417
1418                         final boolean grantPermissions = (args.installFlags
1419                                 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1420                         final boolean killApp = (args.installFlags
1421                                 & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1422                         final String[] grantedPermissions = args.installGrantPermissions;
1423
1424                         // Handle the parent package
1425                         handlePackagePostInstall(parentRes, grantPermissions, killApp,
1426                                 grantedPermissions, didRestore, args.installerPackageName,
1427                                 args.observer);
1428
1429                         // Handle the child packages
1430                         final int childCount = (parentRes.addedChildPackages != null)
1431                                 ? parentRes.addedChildPackages.size() : 0;
1432                         for (int i = 0; i < childCount; i++) {
1433                             PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1434                             handlePackagePostInstall(childRes, grantPermissions, killApp,
1435                                     grantedPermissions, false, args.installerPackageName,
1436                                     args.observer);
1437                         }
1438
1439                         // Log tracing if needed
1440                         if (args.traceMethod != null) {
1441                             Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1442                                     args.traceCookie);
1443                         }
1444                     } else {
1445                         Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1446                     }
1447
1448                     Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1449                 } break;
1450                 case UPDATED_MEDIA_STATUS: {
1451                     if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1452                     boolean reportStatus = msg.arg1 == 1;
1453                     boolean doGc = msg.arg2 == 1;
1454                     if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1455                     if (doGc) {
1456                         // Force a gc to clear up stale containers.
1457                         Runtime.getRuntime().gc();
1458                     }
1459                     if (msg.obj != null) {
1460                         @SuppressWarnings("unchecked")
1461                         Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1462                         if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1463                         // Unload containers
1464                         unloadAllContainers(args);
1465                     }
1466                     if (reportStatus) {
1467                         try {
1468                             if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1469                             PackageHelper.getMountService().finishMediaUpdate();
1470                         } catch (RemoteException e) {
1471                             Log.e(TAG, "MountService not running?");
1472                         }
1473                     }
1474                 } break;
1475                 case WRITE_SETTINGS: {
1476                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1477                     synchronized (mPackages) {
1478                         removeMessages(WRITE_SETTINGS);
1479                         removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1480                         mSettings.writeLPr();
1481                         mDirtyUsers.clear();
1482                     }
1483                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1484                 } break;
1485                 case WRITE_PACKAGE_RESTRICTIONS: {
1486                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1487                     synchronized (mPackages) {
1488                         removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1489                         for (int userId : mDirtyUsers) {
1490                             mSettings.writePackageRestrictionsLPr(userId);
1491                         }
1492                         mDirtyUsers.clear();
1493                     }
1494                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1495                 } break;
1496                 case WRITE_PACKAGE_LIST: {
1497                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1498                     synchronized (mPackages) {
1499                         removeMessages(WRITE_PACKAGE_LIST);
1500                         mSettings.writePackageListLPr(msg.arg1);
1501                     }
1502                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1503                 } break;
1504                 case CHECK_PENDING_VERIFICATION: {
1505                     final int verificationId = msg.arg1;
1506                     final PackageVerificationState state = mPendingVerification.get(verificationId);
1507
1508                     if ((state != null) && !state.timeoutExtended()) {
1509                         final InstallArgs args = state.getInstallArgs();
1510                         final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1511
1512                         Slog.i(TAG, "Verification timed out for " + originUri);
1513                         mPendingVerification.remove(verificationId);
1514
1515                         int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1516
1517                         if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1518                             Slog.i(TAG, "Continuing with installation of " + originUri);
1519                             state.setVerifierResponse(Binder.getCallingUid(),
1520                                     PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1521                             broadcastPackageVerified(verificationId, originUri,
1522                                     PackageManager.VERIFICATION_ALLOW,
1523                                     state.getInstallArgs().getUser());
1524                             try {
1525                                 ret = args.copyApk(mContainerService, true);
1526                             } catch (RemoteException e) {
1527                                 Slog.e(TAG, "Could not contact the ContainerService");
1528                             }
1529                         } else {
1530                             broadcastPackageVerified(verificationId, originUri,
1531                                     PackageManager.VERIFICATION_REJECT,
1532                                     state.getInstallArgs().getUser());
1533                         }
1534
1535                         Trace.asyncTraceEnd(
1536                                 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1537
1538                         processPendingInstall(args, ret);
1539                         mHandler.sendEmptyMessage(MCS_UNBIND);
1540                     }
1541                     break;
1542                 }
1543                 case PACKAGE_VERIFIED: {
1544                     final int verificationId = msg.arg1;
1545
1546                     final PackageVerificationState state = mPendingVerification.get(verificationId);
1547                     if (state == null) {
1548                         Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1549                         break;
1550                     }
1551
1552                     final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1553
1554                     state.setVerifierResponse(response.callerUid, response.code);
1555
1556                     if (state.isVerificationComplete()) {
1557                         mPendingVerification.remove(verificationId);
1558
1559                         final InstallArgs args = state.getInstallArgs();
1560                         final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1561
1562                         int ret;
1563                         if (state.isInstallAllowed()) {
1564                             ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1565                             broadcastPackageVerified(verificationId, originUri,
1566                                     response.code, state.getInstallArgs().getUser());
1567                             try {
1568                                 ret = args.copyApk(mContainerService, true);
1569                             } catch (RemoteException e) {
1570                                 Slog.e(TAG, "Could not contact the ContainerService");
1571                             }
1572                         } else {
1573                             ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1574                         }
1575
1576                         Trace.asyncTraceEnd(
1577                                 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1578
1579                         processPendingInstall(args, ret);
1580                         mHandler.sendEmptyMessage(MCS_UNBIND);
1581                     }
1582
1583                     break;
1584                 }
1585                 case START_INTENT_FILTER_VERIFICATIONS: {
1586                     IFVerificationParams params = (IFVerificationParams) msg.obj;
1587                     verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1588                             params.replacing, params.pkg);
1589                     break;
1590                 }
1591                 case INTENT_FILTER_VERIFIED: {
1592                     final int verificationId = msg.arg1;
1593
1594                     final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1595                             verificationId);
1596                     if (state == null) {
1597                         Slog.w(TAG, "Invalid IntentFilter verification token "
1598                                 + verificationId + " received");
1599                         break;
1600                     }
1601
1602                     final int userId = state.getUserId();
1603
1604                     if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1605                             "Processing IntentFilter verification with token:"
1606                             + verificationId + " and userId:" + userId);
1607
1608                     final IntentFilterVerificationResponse response =
1609                             (IntentFilterVerificationResponse) msg.obj;
1610
1611                     state.setVerifierResponse(response.callerUid, response.code);
1612
1613                     if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1614                             "IntentFilter verification with token:" + verificationId
1615                             + " and userId:" + userId
1616                             + " is settings verifier response with response code:"
1617                             + response.code);
1618
1619                     if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1620                         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1621                                 + response.getFailedDomainsString());
1622                     }
1623
1624                     if (state.isVerificationComplete()) {
1625                         mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1626                     } else {
1627                         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1628                                 "IntentFilter verification with token:" + verificationId
1629                                 + " was not said to be complete");
1630                     }
1631
1632                     break;
1633                 }
1634             }
1635         }
1636     }
1637
1638     private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1639             boolean killApp, String[] grantedPermissions,
1640             boolean launchedForRestore, String installerPackage,
1641             IPackageInstallObserver2 installObserver) {
1642         if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1643             // Send the removed broadcasts
1644             if (res.removedInfo != null) {
1645                 res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1646             }
1647
1648             // Now that we successfully installed the package, grant runtime
1649             // permissions if requested before broadcasting the install.
1650             if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1651                     >= Build.VERSION_CODES.M) {
1652                 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1653             }
1654
1655             final boolean update = res.removedInfo != null
1656                     && res.removedInfo.removedPackage != null;
1657
1658             // If this is the first time we have child packages for a disabled privileged
1659             // app that had no children, we grant requested runtime permissions to the new
1660             // children if the parent on the system image had them already granted.
1661             if (res.pkg.parentPackage != null) {
1662                 synchronized (mPackages) {
1663                     grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1664                 }
1665             }
1666
1667             synchronized (mPackages) {
1668                 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1669             }
1670
1671             final String packageName = res.pkg.applicationInfo.packageName;
1672             Bundle extras = new Bundle(1);
1673             extras.putInt(Intent.EXTRA_UID, res.uid);
1674
1675             // Determine the set of users who are adding this package for
1676             // the first time vs. those who are seeing an update.
1677             int[] firstUsers = EMPTY_INT_ARRAY;
1678             int[] updateUsers = EMPTY_INT_ARRAY;
1679             if (res.origUsers == null || res.origUsers.length == 0) {
1680                 firstUsers = res.newUsers;
1681             } else {
1682                 for (int newUser : res.newUsers) {
1683                     boolean isNew = true;
1684                     for (int origUser : res.origUsers) {
1685                         if (origUser == newUser) {
1686                             isNew = false;
1687                             break;
1688                         }
1689                     }
1690                     if (isNew) {
1691                         firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1692                     } else {
1693                         updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1694                     }
1695                 }
1696             }
1697
1698             // Send installed broadcasts if the install/update is not ephemeral
1699             if (!isEphemeral(res.pkg)) {
1700                 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1701
1702                 // Send added for users that see the package for the first time
1703                 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1704                         extras, 0 /*flags*/, null /*targetPackage*/,
1705                         null /*finishedReceiver*/, firstUsers);
1706
1707                 // Send added for users that don't see the package for the first time
1708                 if (update) {
1709                     extras.putBoolean(Intent.EXTRA_REPLACING, true);
1710                 }
1711                 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1712                         extras, 0 /*flags*/, null /*targetPackage*/,
1713                         null /*finishedReceiver*/, updateUsers);
1714
1715                 // Send replaced for users that don't see the package for the first time
1716                 if (update) {
1717                     sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1718                             packageName, extras, 0 /*flags*/,
1719                             null /*targetPackage*/, null /*finishedReceiver*/,
1720                             updateUsers);
1721                     sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1722                             null /*package*/, null /*extras*/, 0 /*flags*/,
1723                             packageName /*targetPackage*/,
1724                             null /*finishedReceiver*/, updateUsers);
1725                 } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1726                     // First-install and we did a restore, so we're responsible for the
1727                     // first-launch broadcast.
1728                     if (DEBUG_BACKUP) {
1729                         Slog.i(TAG, "Post-restore of " + packageName
1730                                 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1731                     }
1732                     sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1733                 }
1734
1735                 // Send broadcast package appeared if forward locked/external for all users
1736                 // treat asec-hosted packages like removable media on upgrade
1737                 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1738                     if (DEBUG_INSTALL) {
1739                         Slog.i(TAG, "upgrading pkg " + res.pkg
1740                                 + " is ASEC-hosted -> AVAILABLE");
1741                     }
1742                     final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1743                     ArrayList<String> pkgList = new ArrayList<>(1);
1744                     pkgList.add(packageName);
1745                     sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1746                 }
1747             }
1748
1749             // Work that needs to happen on first install within each user
1750             if (firstUsers != null && firstUsers.length > 0) {
1751                 synchronized (mPackages) {
1752                     for (int userId : firstUsers) {
1753                         // If this app is a browser and it's newly-installed for some
1754                         // users, clear any default-browser state in those users. The
1755                         // app's nature doesn't depend on the user, so we can just check
1756                         // its browser nature in any user and generalize.
1757                         if (packageIsBrowser(packageName, userId)) {
1758                             mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1759                         }
1760
1761                         // We may also need to apply pending (restored) runtime
1762                         // permission grants within these users.
1763                         mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1764                     }
1765                 }
1766             }
1767
1768             // Log current value of "unknown sources" setting
1769             EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1770                     getUnknownSourcesSettings());
1771
1772             // Force a gc to clear up things
1773             Runtime.getRuntime().gc();
1774
1775             // Remove the replaced package's older resources safely now
1776             // We delete after a gc for applications  on sdcard.
1777             if (res.removedInfo != null && res.removedInfo.args != null) {
1778                 synchronized (mInstallLock) {
1779                     res.removedInfo.args.doPostDeleteLI(true);
1780                 }
1781             }
1782         }
1783
1784         // If someone is watching installs - notify them
1785         if (installObserver != null) {
1786             try {
1787                 Bundle extras = extrasForInstallResult(res);
1788                 installObserver.onPackageInstalled(res.name, res.returnCode,
1789                         res.returnMsg, extras);
1790             } catch (RemoteException e) {
1791                 Slog.i(TAG, "Observer no longer exists.");
1792             }
1793         }
1794     }
1795
1796     private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1797             PackageParser.Package pkg) {
1798         if (pkg.parentPackage == null) {
1799             return;
1800         }
1801         if (pkg.requestedPermissions == null) {
1802             return;
1803         }
1804         final PackageSetting disabledSysParentPs = mSettings
1805                 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1806         if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1807                 || !disabledSysParentPs.isPrivileged()
1808                 || (disabledSysParentPs.childPackageNames != null
1809                         && !disabledSysParentPs.childPackageNames.isEmpty())) {
1810             return;
1811         }
1812         final int[] allUserIds = sUserManager.getUserIds();
1813         final int permCount = pkg.requestedPermissions.size();
1814         for (int i = 0; i < permCount; i++) {
1815             String permission = pkg.requestedPermissions.get(i);
1816             BasePermission bp = mSettings.mPermissions.get(permission);
1817             if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1818                 continue;
1819             }
1820             for (int userId : allUserIds) {
1821                 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1822                         permission, userId)) {
1823                     grantRuntimePermission(pkg.packageName, permission, userId);
1824                 }
1825             }
1826         }
1827     }
1828
1829     private StorageEventListener mStorageListener = new StorageEventListener() {
1830         @Override
1831         public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1832             if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1833                 if (vol.state == VolumeInfo.STATE_MOUNTED) {
1834                     final String volumeUuid = vol.getFsUuid();
1835
1836                     // Clean up any users or apps that were removed or recreated
1837                     // while this volume was missing
1838                     reconcileUsers(volumeUuid);
1839                     reconcileApps(volumeUuid);
1840
1841                     // Clean up any install sessions that expired or were
1842                     // cancelled while this volume was missing
1843                     mInstallerService.onPrivateVolumeMounted(volumeUuid);
1844
1845                     loadPrivatePackages(vol);
1846
1847                 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1848                     unloadPrivatePackages(vol);
1849                 }
1850             }
1851
1852             if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1853                 if (vol.state == VolumeInfo.STATE_MOUNTED) {
1854                     updateExternalMediaStatus(true, false);
1855                 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1856                     updateExternalMediaStatus(false, false);
1857                 }
1858             }
1859         }
1860
1861         @Override
1862         public void onVolumeForgotten(String fsUuid) {
1863             if (TextUtils.isEmpty(fsUuid)) {
1864                 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1865                 return;
1866             }
1867
1868             // Remove any apps installed on the forgotten volume
1869             synchronized (mPackages) {
1870                 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1871                 for (PackageSetting ps : packages) {
1872                     Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1873                     deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1874                             UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1875                 }
1876
1877                 mSettings.onVolumeForgotten(fsUuid);
1878                 mSettings.writeLPr();
1879             }
1880         }
1881     };
1882
1883     private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1884             String[] grantedPermissions) {
1885         for (int userId : userIds) {
1886             grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1887         }
1888
1889         // We could have touched GID membership, so flush out packages.list
1890         synchronized (mPackages) {
1891             mSettings.writePackageListLPr();
1892         }
1893     }
1894
1895     private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1896             String[] grantedPermissions) {
1897         SettingBase sb = (SettingBase) pkg.mExtras;
1898         if (sb == null) {
1899             return;
1900         }
1901
1902         PermissionsState permissionsState = sb.getPermissionsState();
1903
1904         final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1905                 | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1906
1907         for (String permission : pkg.requestedPermissions) {
1908             final BasePermission bp;
1909             synchronized (mPackages) {
1910                 bp = mSettings.mPermissions.get(permission);
1911             }
1912             if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1913                     && (grantedPermissions == null
1914                            || ArrayUtils.contains(grantedPermissions, permission))) {
1915                 final int flags = permissionsState.getPermissionFlags(permission, userId);
1916                 // Installer cannot change immutable permissions.
1917                 if ((flags & immutableFlags) == 0) {
1918                     grantRuntimePermission(pkg.packageName, permission, userId);
1919                 }
1920             }
1921         }
1922     }
1923
1924     Bundle extrasForInstallResult(PackageInstalledInfo res) {
1925         Bundle extras = null;
1926         switch (res.returnCode) {
1927             case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1928                 extras = new Bundle();
1929                 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1930                         res.origPermission);
1931                 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1932                         res.origPackage);
1933                 break;
1934             }
1935             case PackageManager.INSTALL_SUCCEEDED: {
1936                 extras = new Bundle();
1937                 extras.putBoolean(Intent.EXTRA_REPLACING,
1938                         res.removedInfo != null && res.removedInfo.removedPackage != null);
1939                 break;
1940             }
1941         }
1942         return extras;
1943     }
1944
1945     void scheduleWriteSettingsLocked() {
1946         if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1947             mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1948         }
1949     }
1950
1951     void scheduleWritePackageListLocked(int userId) {
1952         if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1953             Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1954             msg.arg1 = userId;
1955             mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1956         }
1957     }
1958
1959     void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1960         final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1961         scheduleWritePackageRestrictionsLocked(userId);
1962     }
1963
1964     void scheduleWritePackageRestrictionsLocked(int userId) {
1965         final int[] userIds = (userId == UserHandle.USER_ALL)
1966                 ? sUserManager.getUserIds() : new int[]{userId};
1967         for (int nextUserId : userIds) {
1968             if (!sUserManager.exists(nextUserId)) return;
1969             mDirtyUsers.add(nextUserId);
1970             if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1971                 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1972             }
1973         }
1974     }
1975
1976     public static PackageManagerService main(Context context, Installer installer,
1977             boolean factoryTest, boolean onlyCore) {
1978         // Self-check for initial settings.
1979         PackageManagerServiceCompilerMapping.checkProperties();
1980
1981         PackageManagerService m = new PackageManagerService(context, installer,
1982                 factoryTest, onlyCore);
1983         m.enableSystemUserPackages();
1984         ServiceManager.addService("package", m);
1985         return m;
1986     }
1987
1988     private void enableSystemUserPackages() {
1989         if (!UserManager.isSplitSystemUser()) {
1990             return;
1991         }
1992         // For system user, enable apps based on the following conditions:
1993         // - app is whitelisted or belong to one of these groups:
1994         //   -- system app which has no launcher icons
1995         //   -- system app which has INTERACT_ACROSS_USERS permission
1996         //   -- system IME app
1997         // - app is not in the blacklist
1998         AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1999         Set<String> enableApps = new ArraySet<>();
2000         enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2001                 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2002                 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2003         ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2004         enableApps.addAll(wlApps);
2005         enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2006                 /* systemAppsOnly */ false, UserHandle.SYSTEM));
2007         ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2008         enableApps.removeAll(blApps);
2009         Log.i(TAG, "Applications installed for system user: " + enableApps);
2010         List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2011                 UserHandle.SYSTEM);
2012         final int allAppsSize = allAps.size();
2013         synchronized (mPackages) {
2014             for (int i = 0; i < allAppsSize; i++) {
2015                 String pName = allAps.get(i);
2016                 PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2017                 // Should not happen, but we shouldn't be failing if it does
2018                 if (pkgSetting == null) {
2019                     continue;
2020                 }
2021                 boolean install = enableApps.contains(pName);
2022                 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2023                     Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2024                             + " for system user");
2025                     pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2026                 }
2027             }
2028         }
2029     }
2030
2031     private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2032         DisplayManager displayManager = (DisplayManager) context.getSystemService(
2033                 Context.DISPLAY_SERVICE);
2034         displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2035     }
2036
2037     /**
2038      * Requests that files preopted on a secondary system partition be copied to the data partition
2039      * if possible.  Note that the actual copying of the files is accomplished by init for security
2040      * reasons. This simply requests that the copy takes place and awaits confirmation of its
2041      * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2042      */
2043     private static void requestCopyPreoptedFiles() {
2044         final int WAIT_TIME_MS = 100;
2045         final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2046         if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2047             SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2048             // We will wait for up to 100 seconds.
2049             final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2050             while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2051                 try {
2052                     Thread.sleep(WAIT_TIME_MS);
2053                 } catch (InterruptedException e) {
2054                     // Do nothing
2055                 }
2056                 if (SystemClock.uptimeMillis() > timeEnd) {
2057                     SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2058                     Slog.wtf(TAG, "cppreopt did not finish!");
2059                     break;
2060                 }
2061             }
2062         }
2063     }
2064
2065     public PackageManagerService(Context context, Installer installer,
2066             boolean factoryTest, boolean onlyCore) {
2067         EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2068                 SystemClock.uptimeMillis());
2069
2070         if (mSdkVersion <= 0) {
2071             Slog.w(TAG, "**** ro.build.version.sdk not set!");
2072         }
2073
2074         mContext = context;
2075
2076         mPermissionReviewRequired = context.getResources().getBoolean(
2077                 R.bool.config_permissionReviewRequired);
2078
2079         mFactoryTest = factoryTest;
2080         mOnlyCore = onlyCore;
2081         mMetrics = new DisplayMetrics();
2082         mSettings = new Settings(mPackages);
2083         mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2084                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2085         mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2086                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2087         mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2088                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2089         mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2090                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2091         mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2092                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2093         mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2094                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2095
2096         String separateProcesses = SystemProperties.get("debug.separate_processes");
2097         if (separateProcesses != null && separateProcesses.length() > 0) {
2098             if ("*".equals(separateProcesses)) {
2099                 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2100                 mSeparateProcesses = null;
2101                 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2102             } else {
2103                 mDefParseFlags = 0;
2104                 mSeparateProcesses = separateProcesses.split(",");
2105                 Slog.w(TAG, "Running with debug.separate_processes: "
2106                         + separateProcesses);
2107             }
2108         } else {
2109             mDefParseFlags = 0;
2110             mSeparateProcesses = null;
2111         }
2112
2113         mInstaller = installer;
2114         mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2115                 "*dexopt*");
2116         mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2117
2118         mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2119                 FgThread.get().getLooper());
2120
2121         getDefaultDisplayMetrics(context, mMetrics);
2122
2123         SystemConfig systemConfig = SystemConfig.getInstance();
2124         mGlobalGids = systemConfig.getGlobalGids();
2125         mSystemPermissions = systemConfig.getSystemPermissions();
2126         mAvailableFeatures = systemConfig.getAvailableFeatures();
2127
2128         mProtectedPackages = new ProtectedPackages(mContext);
2129
2130         synchronized (mInstallLock) {
2131         // writer
2132         synchronized (mPackages) {
2133             mHandlerThread = new ServiceThread(TAG,
2134                     Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2135             mHandlerThread.start();
2136             mHandler = new PackageHandler(mHandlerThread.getLooper());
2137             mProcessLoggingHandler = new ProcessLoggingHandler();
2138             Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2139
2140             mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2141
2142             File dataDir = Environment.getDataDirectory();
2143             mAppInstallDir = new File(dataDir, "app");
2144             mAppLib32InstallDir = new File(dataDir, "app-lib");
2145             mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2146             mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2147             mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2148
2149             sUserManager = new UserManagerService(context, this, mPackages);
2150
2151             // Propagate permission configuration in to package manager.
2152             ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2153                     = systemConfig.getPermissions();
2154             for (int i=0; i<permConfig.size(); i++) {
2155                 SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2156                 BasePermission bp = mSettings.mPermissions.get(perm.name);
2157                 if (bp == null) {
2158                     bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2159                     mSettings.mPermissions.put(perm.name, bp);
2160                 }
2161                 if (perm.gids != null) {
2162                     bp.setGids(perm.gids, perm.perUser);
2163                 }
2164             }
2165
2166             ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2167             for (int i=0; i<libConfig.size(); i++) {
2168                 mSharedLibraries.put(libConfig.keyAt(i),
2169                         new SharedLibraryEntry(libConfig.valueAt(i), null));
2170             }
2171
2172             mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2173
2174             mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2175
2176             // Clean up orphaned packages for which the code path doesn't exist
2177             // and they are an update to a system app - caused by bug/32321269
2178             final int packageSettingCount = mSettings.mPackages.size();
2179             for (int i = packageSettingCount - 1; i >= 0; i--) {
2180                 PackageSetting ps = mSettings.mPackages.valueAt(i);
2181                 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2182                         && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2183                     mSettings.mPackages.removeAt(i);
2184                     mSettings.enableSystemPackageLPw(ps.name);
2185                 }
2186             }
2187
2188             if (mFirstBoot) {
2189                 requestCopyPreoptedFiles();
2190             }
2191
2192             String customResolverActivity = Resources.getSystem().getString(
2193                     R.string.config_customResolverActivity);
2194             if (TextUtils.isEmpty(customResolverActivity)) {
2195                 customResolverActivity = null;
2196             } else {
2197                 mCustomResolverComponentName = ComponentName.unflattenFromString(
2198                         customResolverActivity);
2199             }
2200
2201             long startTime = SystemClock.uptimeMillis();
2202
2203             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2204                     startTime);
2205
2206             // Set flag to monitor and not change apk file paths when
2207             // scanning install directories.
2208             final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2209
2210             final String bootClassPath = System.getenv("BOOTCLASSPATH");
2211             final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2212
2213             if (bootClassPath == null) {
2214                 Slog.w(TAG, "No BOOTCLASSPATH found!");
2215             }
2216
2217             if (systemServerClassPath == null) {
2218                 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2219             }
2220
2221             final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2222             final String[] dexCodeInstructionSets =
2223                     getDexCodeInstructionSets(
2224                             allInstructionSets.toArray(new String[allInstructionSets.size()]));
2225
2226             /**
2227              * Ensure all external libraries have had dexopt run on them.
2228              */
2229             if (mSharedLibraries.size() > 0) {
2230                 // NOTE: For now, we're compiling these system "shared libraries"
2231                 // (and framework jars) into all available architectures. It's possible
2232                 // to compile them only when we come across an app that uses them (there's
2233                 // already logic for that in scanPackageLI) but that adds some complexity.
2234                 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2235                     for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2236                         final String lib = libEntry.path;
2237                         if (lib == null) {
2238                             continue;
2239                         }
2240
2241                         try {
2242                             // Shared libraries do not have profiles so we perform a full
2243                             // AOT compilation (if needed).
2244                             int dexoptNeeded = DexFile.getDexOptNeeded(
2245                                     lib, dexCodeInstructionSet,
2246                                     getCompilerFilterForReason(REASON_SHARED_APK),
2247                                     false /* newProfile */);
2248                             if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2249                                 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2250                                         dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2251                                         getCompilerFilterForReason(REASON_SHARED_APK),
2252                                         StorageManager.UUID_PRIVATE_INTERNAL,
2253                                         SKIP_SHARED_LIBRARY_CHECK);
2254                             }
2255                         } catch (FileNotFoundException e) {
2256                             Slog.w(TAG, "Library not found: " + lib);
2257                         } catch (IOException | InstallerException e) {
2258                             Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2259                                     + e.getMessage());
2260                         }
2261                     }
2262                 }
2263             }
2264
2265             File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2266
2267             final VersionInfo ver = mSettings.getInternalVersion();
2268             mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2269
2270             // when upgrading from pre-M, promote system app permissions from install to runtime
2271             mPromoteSystemApps =
2272                     mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2273
2274             // When upgrading from pre-N, we need to handle package extraction like first boot,
2275             // as there is no profiling data available.
2276             mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2277
2278             mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2279
2280             // save off the names of pre-existing system packages prior to scanning; we don't
2281             // want to automatically grant runtime permissions for new system apps
2282             if (mPromoteSystemApps) {
2283                 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2284                 while (pkgSettingIter.hasNext()) {
2285                     PackageSetting ps = pkgSettingIter.next();
2286                     if (isSystemApp(ps)) {
2287                         mExistingSystemPackages.add(ps.name);
2288                     }
2289                 }
2290             }
2291
2292             // Collect vendor overlay packages. (Do this before scanning any apps.)
2293             // For security and version matching reason, only consider
2294             // overlay packages if they reside in the right directory.
2295             String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2296             if (!overlayThemeDir.isEmpty()) {
2297                 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2298                         | PackageParser.PARSE_IS_SYSTEM
2299                         | PackageParser.PARSE_IS_SYSTEM_DIR
2300                         | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2301             }
2302             scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2303                     | PackageParser.PARSE_IS_SYSTEM
2304                     | PackageParser.PARSE_IS_SYSTEM_DIR
2305                     | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2306
2307             // Find base frameworks (resource packages without code).
2308             scanDirTracedLI(frameworkDir, mDefParseFlags
2309                     | PackageParser.PARSE_IS_SYSTEM
2310                     | PackageParser.PARSE_IS_SYSTEM_DIR
2311                     | PackageParser.PARSE_IS_PRIVILEGED,
2312                     scanFlags | SCAN_NO_DEX, 0);
2313
2314             // Collected privileged system packages.
2315             final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2316             scanDirTracedLI(privilegedAppDir, mDefParseFlags
2317                     | PackageParser.PARSE_IS_SYSTEM
2318                     | PackageParser.PARSE_IS_SYSTEM_DIR
2319                     | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2320
2321             // Collect ordinary system packages.
2322             final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2323             scanDirTracedLI(systemAppDir, mDefParseFlags
2324                     | PackageParser.PARSE_IS_SYSTEM
2325                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2326
2327             // Collect all vendor packages.
2328             File vendorAppDir = new File("/vendor/app");
2329             try {
2330                 vendorAppDir = vendorAppDir.getCanonicalFile();
2331             } catch (IOException e) {
2332                 // failed to look up canonical path, continue with original one
2333             }
2334             scanDirTracedLI(vendorAppDir, mDefParseFlags
2335                     | PackageParser.PARSE_IS_SYSTEM
2336                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2337
2338             // Collect all OEM packages.
2339             final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2340             scanDirTracedLI(oemAppDir, mDefParseFlags
2341                     | PackageParser.PARSE_IS_SYSTEM
2342                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2343
2344             // Prune any system packages that no longer exist.
2345             final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2346             if (!mOnlyCore) {
2347                 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2348                 while (psit.hasNext()) {
2349                     PackageSetting ps = psit.next();
2350
2351                     /*
2352                      * If this is not a system app, it can't be a
2353                      * disable system app.
2354                      */
2355                     if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2356                         continue;
2357                     }
2358
2359                     /*
2360                      * If the package is scanned, it's not erased.
2361                      */
2362                     final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2363                     if (scannedPkg != null) {
2364                         /*
2365                          * If the system app is both scanned and in the
2366                          * disabled packages list, then it must have been
2367                          * added via OTA. Remove it from the currently
2368                          * scanned package so the previously user-installed
2369                          * application can be scanned.
2370                          */
2371                         if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2372                             logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2373                                     + ps.name + "; removing system app.  Last known codePath="
2374                                     + ps.codePathString + ", installStatus=" + ps.installStatus
2375                                     + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2376                                     + scannedPkg.mVersionCode);
2377                             removePackageLI(scannedPkg, true);
2378                             mExpectingBetter.put(ps.name, ps.codePath);
2379                         }
2380
2381                         continue;
2382                     }
2383
2384                     if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2385                         psit.remove();
2386                         logCriticalInfo(Log.WARN, "System package " + ps.name
2387                                 + " no longer exists; it's data will be wiped");
2388                         // Actual deletion of code and data will be handled by later
2389                         // reconciliation step
2390                     } else {
2391                         final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2392                         if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2393                             possiblyDeletedUpdatedSystemApps.add(ps.name);
2394                         }
2395                     }
2396                 }
2397             }
2398
2399             //look for any incomplete package installations
2400             ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2401             for (int i = 0; i < deletePkgsList.size(); i++) {
2402                 // Actual deletion of code and data will be handled by later
2403                 // reconciliation step
2404                 final String packageName = deletePkgsList.get(i).name;
2405                 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2406                 synchronized (mPackages) {
2407                     mSettings.removePackageLPw(packageName);
2408                 }
2409             }
2410
2411             //delete tmp files
2412             deleteTempPackageFiles();
2413
2414             // Remove any shared userIDs that have no associated packages
2415             mSettings.pruneSharedUsersLPw();
2416
2417             if (!mOnlyCore) {
2418                 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2419                         SystemClock.uptimeMillis());
2420                 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2421
2422                 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2423                         | PackageParser.PARSE_FORWARD_LOCK,
2424                         scanFlags | SCAN_REQUIRE_KNOWN, 0);
2425
2426                 scanDirLI(mEphemeralInstallDir, mDefParseFlags
2427                         | PackageParser.PARSE_IS_EPHEMERAL,
2428                         scanFlags | SCAN_REQUIRE_KNOWN, 0);
2429
2430                 /**
2431                  * Remove disable package settings for any updated system
2432                  * apps that were removed via an OTA. If they're not a
2433                  * previously-updated app, remove them completely.
2434                  * Otherwise, just revoke their system-level permissions.
2435                  */
2436                 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2437                     PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2438                     mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2439
2440                     String msg;
2441                     if (deletedPkg == null) {
2442                         msg = "Updated system package " + deletedAppName
2443                                 + " no longer exists; it's data will be wiped";
2444                         // Actual deletion of code and data will be handled by later
2445                         // reconciliation step
2446                     } else {
2447                         msg = "Updated system app + " + deletedAppName
2448                                 + " no longer present; removing system privileges for "
2449                                 + deletedAppName;
2450
2451                         deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2452
2453                         PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2454                         deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2455                     }
2456                     logCriticalInfo(Log.WARN, msg);
2457                 }
2458
2459                 /**
2460                  * Make sure all system apps that we expected to appear on
2461                  * the userdata partition actually showed up. If they never
2462                  * appeared, crawl back and revive the system version.
2463                  */
2464                 for (int i = 0; i < mExpectingBetter.size(); i++) {
2465                     final String packageName = mExpectingBetter.keyAt(i);
2466                     if (!mPackages.containsKey(packageName)) {
2467                         final File scanFile = mExpectingBetter.valueAt(i);
2468
2469                         logCriticalInfo(Log.WARN, "Expected better " + packageName
2470                                 + " but never showed up; reverting to system");
2471
2472                         int reparseFlags = mDefParseFlags;
2473                         if (FileUtils.contains(privilegedAppDir, scanFile)) {
2474                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2475                                     | PackageParser.PARSE_IS_SYSTEM_DIR
2476                                     | PackageParser.PARSE_IS_PRIVILEGED;
2477                         } else if (FileUtils.contains(systemAppDir, scanFile)) {
2478                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2479                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
2480                         } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2481                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2482                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
2483                         } else if (FileUtils.contains(oemAppDir, scanFile)) {
2484                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2485                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
2486                         } else {
2487                             Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2488                             continue;
2489                         }
2490
2491                         mSettings.enableSystemPackageLPw(packageName);
2492
2493                         try {
2494                             scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2495                         } catch (PackageManagerException e) {
2496                             Slog.e(TAG, "Failed to parse original system package: "
2497                                     + e.getMessage());
2498                         }
2499                     }
2500                 }
2501             }
2502             mExpectingBetter.clear();
2503
2504             // Resolve the storage manager.
2505             mStorageManagerPackage = getStorageManagerPackageName();
2506
2507             // Resolve protected action filters. Only the setup wizard is allowed to
2508             // have a high priority filter for these actions.
2509             mSetupWizardPackage = getSetupWizardPackageName();
2510             if (mProtectedFilters.size() > 0) {
2511                 if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2512                     Slog.i(TAG, "No setup wizard;"
2513                         + " All protected intents capped to priority 0");
2514                 }
2515                 for (ActivityIntentInfo filter : mProtectedFilters) {
2516                     if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2517                         if (DEBUG_FILTERS) {
2518                             Slog.i(TAG, "Found setup wizard;"
2519                                 + " allow priority " + filter.getPriority() + ";"
2520                                 + " package: " + filter.activity.info.packageName
2521                                 + " activity: " + filter.activity.className
2522                                 + " priority: " + filter.getPriority());
2523                         }
2524                         // skip setup wizard; allow it to keep the high priority filter
2525                         continue;
2526                     }
2527                     Slog.w(TAG, "Protected action; cap priority to 0;"
2528                             + " package: " + filter.activity.info.packageName
2529                             + " activity: " + filter.activity.className
2530                             + " origPrio: " + filter.getPriority());
2531                     filter.setPriority(0);
2532                 }
2533             }
2534             mDeferProtectedFilters = false;
2535             mProtectedFilters.clear();
2536
2537             // Now that we know all of the shared libraries, update all clients to have
2538             // the correct library paths.
2539             updateAllSharedLibrariesLPw();
2540
2541             for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2542                 // NOTE: We ignore potential failures here during a system scan (like
2543                 // the rest of the commands above) because there's precious little we
2544                 // can do about it. A settings error is reported, though.
2545                 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2546                         false /* boot complete */);
2547             }
2548
2549             // Now that we know all the packages we are keeping,
2550             // read and update their last usage times.
2551             mPackageUsage.read(mPackages);
2552             mCompilerStats.read();
2553
2554             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2555                     SystemClock.uptimeMillis());
2556             Slog.i(TAG, "Time to scan packages: "
2557                     + ((SystemClock.uptimeMillis()-startTime)/1000f)
2558                     + " seconds");
2559
2560             // If the platform SDK has changed since the last time we booted,
2561             // we need to re-grant app permission to catch any new ones that
2562             // appear.  This is really a hack, and means that apps can in some
2563             // cases get permissions that the user didn't initially explicitly
2564             // allow...  it would be nice to have some better way to handle
2565             // this situation.
2566             int updateFlags = UPDATE_PERMISSIONS_ALL;
2567             if (ver.sdkVersion != mSdkVersion) {
2568                 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2569                         + mSdkVersion + "; regranting permissions for internal storage");
2570                 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2571             }
2572             updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2573             ver.sdkVersion = mSdkVersion;
2574
2575             // If this is the first boot or an update from pre-M, and it is a normal
2576             // boot, then we need to initialize the default preferred apps across
2577             // all defined users.
2578             if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2579                 for (UserInfo user : sUserManager.getUsers(true)) {
2580                     mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2581                     applyFactoryDefaultBrowserLPw(user.id);
2582                     primeDomainVerificationsLPw(user.id);
2583                 }
2584             }
2585
2586             // Prepare storage for system user really early during boot,
2587             // since core system apps like SettingsProvider and SystemUI
2588             // can't wait for user to start
2589             final int storageFlags;
2590             if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2591                 storageFlags = StorageManager.FLAG_STORAGE_DE;
2592             } else {
2593                 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2594             }
2595             reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2596                     storageFlags);
2597
2598             // If this is first boot after an OTA, and a normal boot, then
2599             // we need to clear code cache directories.
2600             // Note that we do *not* clear the application profiles. These remain valid
2601             // across OTAs and are used to drive profile verification (post OTA) and
2602             // profile compilation (without waiting to collect a fresh set of profiles).
2603             if (mIsUpgrade && !onlyCore) {
2604                 Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2605                 for (int i = 0; i < mSettings.mPackages.size(); i++) {
2606                     final PackageSetting ps = mSettings.mPackages.valueAt(i);
2607                     if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2608                         // No apps are running this early, so no need to freeze
2609                         clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2610                                 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2611                                         | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2612                     }
2613                 }
2614                 ver.fingerprint = Build.FINGERPRINT;
2615             }
2616
2617             checkDefaultBrowser();
2618
2619             // clear only after permissions and other defaults have been updated
2620             mExistingSystemPackages.clear();
2621             mPromoteSystemApps = false;
2622
2623             // All the changes are done during package scanning.
2624             ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2625
2626             // can downgrade to reader
2627             mSettings.writeLPr();
2628
2629             // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2630             // early on (before the package manager declares itself as early) because other
2631             // components in the system server might ask for package contexts for these apps.
2632             //
2633             // Note that "onlyCore" in this context means the system is encrypted or encrypting
2634             // (i.e, that the data partition is unavailable).
2635             if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2636                 long start = System.nanoTime();
2637                 List<PackageParser.Package> coreApps = new ArrayList<>();
2638                 for (PackageParser.Package pkg : mPackages.values()) {
2639                     if (pkg.coreApp) {
2640                         coreApps.add(pkg);
2641                     }
2642                 }
2643
2644                 int[] stats = performDexOptUpgrade(coreApps, false,
2645                         getCompilerFilterForReason(REASON_CORE_APP));
2646
2647                 final int elapsedTimeSeconds =
2648                         (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2649                 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2650
2651                 if (DEBUG_DEXOPT) {
2652                     Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2653                             stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2654                 }
2655
2656
2657                 // TODO: Should we log these stats to tron too ?
2658                 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2659                 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2660                 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2661                 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2662             }
2663
2664             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2665                     SystemClock.uptimeMillis());
2666
2667             if (!mOnlyCore) {
2668                 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2669                 mRequiredInstallerPackage = getRequiredInstallerLPr();
2670                 mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2671                 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2672                 mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2673                         mIntentFilterVerifierComponent);
2674                 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2675                         PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2676                 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2677                         PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2678             } else {
2679                 mRequiredVerifierPackage = null;
2680                 mRequiredInstallerPackage = null;
2681                 mRequiredUninstallerPackage = null;
2682                 mIntentFilterVerifierComponent = null;
2683                 mIntentFilterVerifier = null;
2684                 mServicesSystemSharedLibraryPackageName = null;
2685                 mSharedSystemSharedLibraryPackageName = null;
2686             }
2687
2688             mInstallerService = new PackageInstallerService(context, this);
2689
2690             final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2691             final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2692             // both the installer and resolver must be present to enable ephemeral
2693             if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2694                 if (DEBUG_EPHEMERAL) {
2695                     Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2696                             + " installer:" + ephemeralInstallerComponent);
2697                 }
2698                 mEphemeralResolverComponent = ephemeralResolverComponent;
2699                 mEphemeralInstallerComponent = ephemeralInstallerComponent;
2700                 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2701                 mEphemeralResolverConnection =
2702                         new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2703             } else {
2704                 if (DEBUG_EPHEMERAL) {
2705                     final String missingComponent =
2706                             (ephemeralResolverComponent == null)
2707                             ? (ephemeralInstallerComponent == null)
2708                                     ? "resolver and installer"
2709                                     : "resolver"
2710                             : "installer";
2711                     Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2712                 }
2713                 mEphemeralResolverComponent = null;
2714                 mEphemeralInstallerComponent = null;
2715                 mEphemeralResolverConnection = null;
2716             }
2717
2718             mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2719         } // synchronized (mPackages)
2720         } // synchronized (mInstallLock)
2721
2722         // Now after opening every single application zip, make sure they
2723         // are all flushed.  Not really needed, but keeps things nice and
2724         // tidy.
2725         Runtime.getRuntime().gc();
2726
2727         // The initial scanning above does many calls into installd while
2728         // holding the mPackages lock, but we're mostly interested in yelling
2729         // once we have a booted system.
2730         mInstaller.setWarnIfHeld(mPackages);
2731
2732         // Expose private service for system components to use.
2733         LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2734     }
2735
2736     @Override
2737     public boolean isFirstBoot() {
2738         return mFirstBoot;
2739     }
2740
2741     @Override
2742     public boolean isOnlyCoreApps() {
2743         return mOnlyCore;
2744     }
2745
2746     @Override
2747     public boolean isUpgrade() {
2748         return mIsUpgrade;
2749     }
2750
2751     private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2752         final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2753
2754         final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2755                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2756                 UserHandle.USER_SYSTEM);
2757         if (matches.size() == 1) {
2758             return matches.get(0).getComponentInfo().packageName;
2759         } else if (matches.size() == 0) {
2760             Log.e(TAG, "There should probably be a verifier, but, none were found");
2761             return null;
2762         }
2763         throw new RuntimeException("There must be exactly one verifier; found " + matches);
2764     }
2765
2766     private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2767         synchronized (mPackages) {
2768             SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2769             if (libraryEntry == null) {
2770                 throw new IllegalStateException("Missing required shared library:" + libraryName);
2771             }
2772             return libraryEntry.apk;
2773         }
2774     }
2775
2776     private @NonNull String getRequiredInstallerLPr() {
2777         final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2778         intent.addCategory(Intent.CATEGORY_DEFAULT);
2779         intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2780
2781         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2782                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2783                 UserHandle.USER_SYSTEM);
2784         if (matches.size() == 1) {
2785             ResolveInfo resolveInfo = matches.get(0);
2786             if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2787                 throw new RuntimeException("The installer must be a privileged app");
2788             }
2789             return matches.get(0).getComponentInfo().packageName;
2790         } else {
2791             throw new RuntimeException("There must be exactly one installer; found " + matches);
2792         }
2793     }
2794
2795     private @NonNull String getRequiredUninstallerLPr() {
2796         final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2797         intent.addCategory(Intent.CATEGORY_DEFAULT);
2798         intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2799
2800         final ResolveInfo resolveInfo = resolveIntent(intent, null,
2801                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2802                 UserHandle.USER_SYSTEM);
2803         if (resolveInfo == null ||
2804                 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2805             throw new RuntimeException("There must be exactly one uninstaller; found "
2806                     + resolveInfo);
2807         }
2808         return resolveInfo.getComponentInfo().packageName;
2809     }
2810
2811     private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2812         final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2813
2814         final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2815                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2816                 UserHandle.USER_SYSTEM);
2817         ResolveInfo best = null;
2818         final int N = matches.size();
2819         for (int i = 0; i < N; i++) {
2820             final ResolveInfo cur = matches.get(i);
2821             final String packageName = cur.getComponentInfo().packageName;
2822             if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2823                     packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2824                 continue;
2825             }
2826
2827             if (best == null || cur.priority > best.priority) {
2828                 best = cur;
2829             }
2830         }
2831
2832         if (best != null) {
2833             return best.getComponentInfo().getComponentName();
2834         } else {
2835             throw new RuntimeException("There must be at least one intent filter verifier");
2836         }
2837     }
2838
2839     private @Nullable ComponentName getEphemeralResolverLPr() {
2840         final String[] packageArray =
2841                 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2842         if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2843             if (DEBUG_EPHEMERAL) {
2844                 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2845             }
2846             return null;
2847         }
2848
2849         final int resolveFlags =
2850                 MATCH_DIRECT_BOOT_AWARE
2851                 | MATCH_DIRECT_BOOT_UNAWARE
2852                 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2853         final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2854         final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2855                 resolveFlags, UserHandle.USER_SYSTEM);
2856
2857         final int N = resolvers.size();
2858         if (N == 0) {
2859             if (DEBUG_EPHEMERAL) {
2860                 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2861             }
2862             return null;
2863         }
2864
2865         final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2866         for (int i = 0; i < N; i++) {
2867             final ResolveInfo info = resolvers.get(i);
2868
2869             if (info.serviceInfo == null) {
2870                 continue;
2871             }
2872
2873             final String packageName = info.serviceInfo.packageName;
2874             if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2875                 if (DEBUG_EPHEMERAL) {
2876                     Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2877                             + " pkg: " + packageName + ", info:" + info);
2878                 }
2879                 continue;
2880             }
2881
2882             if (DEBUG_EPHEMERAL) {
2883                 Slog.v(TAG, "Ephemeral resolver found;"
2884                         + " pkg: " + packageName + ", info:" + info);
2885             }
2886             return new ComponentName(packageName, info.serviceInfo.name);
2887         }
2888         if (DEBUG_EPHEMERAL) {
2889             Slog.v(TAG, "Ephemeral resolver NOT found");
2890         }
2891         return null;
2892     }
2893
2894     private @Nullable ComponentName getEphemeralInstallerLPr() {
2895         final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2896         intent.addCategory(Intent.CATEGORY_DEFAULT);
2897         intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2898
2899         final int resolveFlags =
2900                 MATCH_DIRECT_BOOT_AWARE
2901                 | MATCH_DIRECT_BOOT_UNAWARE
2902                 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2903         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2904                 resolveFlags, UserHandle.USER_SYSTEM);
2905         if (matches.size() == 0) {
2906             return null;
2907         } else if (matches.size() == 1) {
2908             return matches.get(0).getComponentInfo().getComponentName();
2909         } else {
2910             throw new RuntimeException(
2911                     "There must be at most one ephemeral installer; found " + matches);
2912         }
2913     }
2914
2915     private void primeDomainVerificationsLPw(int userId) {
2916         if (DEBUG_DOMAIN_VERIFICATION) {
2917             Slog.d(TAG, "Priming domain verifications in user " + userId);
2918         }
2919
2920         SystemConfig systemConfig = SystemConfig.getInstance();
2921         ArraySet<String> packages = systemConfig.getLinkedApps();
2922         ArraySet<String> domains = new ArraySet<String>();
2923
2924         for (String packageName : packages) {
2925             PackageParser.Package pkg = mPackages.get(packageName);
2926             if (pkg != null) {
2927                 if (!pkg.isSystemApp()) {
2928                     Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2929                     continue;
2930                 }
2931
2932                 domains.clear();
2933                 for (PackageParser.Activity a : pkg.activities) {
2934                     for (ActivityIntentInfo filter : a.intents) {
2935                         if (hasValidDomains(filter)) {
2936                             domains.addAll(filter.getHostsList());
2937                         }
2938                     }
2939                 }
2940
2941                 if (domains.size() > 0) {
2942                     if (DEBUG_DOMAIN_VERIFICATION) {
2943                         Slog.v(TAG, "      + " + packageName);
2944                     }
2945                     // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2946                     // state w.r.t. the formal app-linkage "no verification attempted" state;
2947                     // and then 'always' in the per-user state actually used for intent resolution.
2948                     final IntentFilterVerificationInfo ivi;
2949                     ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2950                             new ArrayList<String>(domains));
2951                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2952                     mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2953                             INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2954                 } else {
2955                     Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2956                             + "' does not handle web links");
2957                 }
2958             } else {
2959                 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2960             }
2961         }
2962
2963         scheduleWritePackageRestrictionsLocked(userId);
2964         scheduleWriteSettingsLocked();
2965     }
2966
2967     private void applyFactoryDefaultBrowserLPw(int userId) {
2968         // The default browser app's package name is stored in a string resource,
2969         // with a product-specific overlay used for vendor customization.
2970         String browserPkg = mContext.getResources().getString(
2971                 com.android.internal.R.string.default_browser);
2972         if (!TextUtils.isEmpty(browserPkg)) {
2973             // non-empty string => required to be a known package
2974             PackageSetting ps = mSettings.mPackages.get(browserPkg);
2975             if (ps == null) {
2976                 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2977                 browserPkg = null;
2978             } else {
2979                 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2980             }
2981         }
2982
2983         // Nothing valid explicitly set? Make the factory-installed browser the explicit
2984         // default.  If there's more than one, just leave everything alone.
2985         if (browserPkg == null) {
2986             calculateDefaultBrowserLPw(userId);
2987         }
2988     }
2989
2990     private void calculateDefaultBrowserLPw(int userId) {
2991         List<String> allBrowsers = resolveAllBrowserApps(userId);
2992         final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2993         mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2994     }
2995
2996     private List<String> resolveAllBrowserApps(int userId) {
2997         // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2998         List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2999                 PackageManager.MATCH_ALL, userId);
3000
3001         final int count = list.size();
3002         List<String> result = new ArrayList<String>(count);
3003         for (int i=0; i<count; i++) {
3004             ResolveInfo info = list.get(i);
3005             if (info.activityInfo == null
3006                     || !info.handleAllWebDataURI
3007                     || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3008                     || result.contains(info.activityInfo.packageName)) {
3009                 continue;
3010             }
3011             result.add(info.activityInfo.packageName);
3012         }
3013
3014         return result;
3015     }
3016
3017     private boolean packageIsBrowser(String packageName, int userId) {
3018         List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3019                 PackageManager.MATCH_ALL, userId);
3020         final int N = list.size();
3021         for (int i = 0; i < N; i++) {
3022             ResolveInfo info = list.get(i);
3023             if (packageName.equals(info.activityInfo.packageName)) {
3024                 return true;
3025             }
3026         }
3027         return false;
3028     }
3029
3030     private void checkDefaultBrowser() {
3031         final int myUserId = UserHandle.myUserId();
3032         final String packageName = getDefaultBrowserPackageName(myUserId);
3033         if (packageName != null) {
3034             PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3035             if (info == null) {
3036                 Slog.w(TAG, "Default browser no longer installed: " + packageName);
3037                 synchronized (mPackages) {
3038                     applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3039                 }
3040             }
3041         }
3042     }
3043
3044     @Override
3045     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3046             throws RemoteException {
3047         try {
3048             return super.onTransact(code, data, reply, flags);
3049         } catch (RuntimeException e) {
3050             if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3051                 Slog.wtf(TAG, "Package Manager Crash", e);
3052             }
3053             throw e;
3054         }
3055     }
3056
3057     static int[] appendInts(int[] cur, int[] add) {
3058         if (add == null) return cur;
3059         if (cur == null) return add;
3060         final int N = add.length;
3061         for (int i=0; i<N; i++) {
3062             cur = appendInt(cur, add[i]);
3063         }
3064         return cur;
3065     }
3066
3067     private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3068         if (!sUserManager.exists(userId)) return null;
3069         if (ps == null) {
3070             return null;
3071         }
3072         final PackageParser.Package p = ps.pkg;
3073         if (p == null) {
3074             return null;
3075         }
3076
3077         final PermissionsState permissionsState = ps.getPermissionsState();
3078
3079         // Compute GIDs only if requested
3080         final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3081                 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3082         // Compute granted permissions only if package has requested permissions
3083         final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3084                 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3085         final PackageUserState state = ps.readUserState(userId);
3086
3087         return PackageParser.generatePackageInfo(p, gids, flags,
3088                 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3089     }
3090
3091     @Override
3092     public void checkPackageStartable(String packageName, int userId) {
3093         final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3094
3095         synchronized (mPackages) {
3096             final PackageSetting ps = mSettings.mPackages.get(packageName);
3097             if (ps == null) {
3098                 throw new SecurityException("Package " + packageName + " was not found!");
3099             }
3100
3101             if (!ps.getInstalled(userId)) {
3102                 throw new SecurityException(
3103                         "Package " + packageName + " was not installed for user " + userId + "!");
3104             }
3105
3106             if (mSafeMode && !ps.isSystem()) {
3107                 throw new SecurityException("Package " + packageName + " not a system app!");
3108             }
3109
3110             if (mFrozenPackages.contains(packageName)) {
3111                 throw new SecurityException("Package " + packageName + " is currently frozen!");
3112             }
3113
3114             if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3115                     || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3116                 throw new SecurityException("Package " + packageName + " is not encryption aware!");
3117             }
3118         }
3119     }
3120
3121     @Override
3122     public boolean isPackageAvailable(String packageName, int userId) {
3123         if (!sUserManager.exists(userId)) return false;
3124         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3125                 false /* requireFullPermission */, false /* checkShell */, "is package available");
3126         synchronized (mPackages) {
3127             PackageParser.Package p = mPackages.get(packageName);
3128             if (p != null) {
3129                 final PackageSetting ps = (PackageSetting) p.mExtras;
3130                 if (ps != null) {
3131                     final PackageUserState state = ps.readUserState(userId);
3132                     if (state != null) {
3133                         return PackageParser.isAvailable(state);
3134                     }
3135                 }
3136             }
3137         }
3138         return false;
3139     }
3140
3141     @Override
3142     public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3143         if (!sUserManager.exists(userId)) return null;
3144         flags = updateFlagsForPackage(flags, userId, packageName);
3145         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3146                 false /* requireFullPermission */, false /* checkShell */, "get package info");
3147
3148         // reader
3149         synchronized (mPackages) {
3150             // Normalize package name to hanlde renamed packages
3151             packageName = normalizePackageNameLPr(packageName);
3152
3153             final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3154             PackageParser.Package p = null;
3155             if (matchFactoryOnly) {
3156                 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3157                 if (ps != null) {
3158                     return generatePackageInfo(ps, flags, userId);
3159                 }
3160             }
3161             if (p == null) {
3162                 p = mPackages.get(packageName);
3163                 if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3164                     return null;
3165                 }
3166             }
3167             if (DEBUG_PACKAGE_INFO)
3168                 Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3169             if (p != null) {
3170                 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3171             }
3172             if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3173                 final PackageSetting ps = mSettings.mPackages.get(packageName);
3174                 return generatePackageInfo(ps, flags, userId);
3175             }
3176         }
3177         return null;
3178     }
3179
3180     @Override
3181     public String[] currentToCanonicalPackageNames(String[] names) {
3182         String[] out = new String[names.length];
3183         // reader
3184         synchronized (mPackages) {
3185             for (int i=names.length-1; i>=0; i--) {
3186                 PackageSetting ps = mSettings.mPackages.get(names[i]);
3187                 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3188             }
3189         }
3190         return out;
3191     }
3192
3193     @Override
3194     public String[] canonicalToCurrentPackageNames(String[] names) {
3195         String[] out = new String[names.length];
3196         // reader
3197         synchronized (mPackages) {
3198             for (int i=names.length-1; i>=0; i--) {
3199                 String cur = mSettings.mRenamedPackages.get(names[i]);
3200                 out[i] = cur != null ? cur : names[i];
3201             }
3202         }
3203         return out;
3204     }
3205
3206     @Override
3207     public int getPackageUid(String packageName, int flags, int userId) {
3208         if (!sUserManager.exists(userId)) return -1;
3209         flags = updateFlagsForPackage(flags, userId, packageName);
3210         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3211                 false /* requireFullPermission */, false /* checkShell */, "get package uid");
3212
3213         // reader
3214         synchronized (mPackages) {
3215             final PackageParser.Package p = mPackages.get(packageName);
3216             if (p != null && p.isMatch(flags)) {
3217                 return UserHandle.getUid(userId, p.applicationInfo.uid);
3218             }
3219             if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3220                 final PackageSetting ps = mSettings.mPackages.get(packageName);
3221                 if (ps != null && ps.isMatch(flags)) {
3222                     return UserHandle.getUid(userId, ps.appId);
3223                 }
3224             }
3225         }
3226
3227         return -1;
3228     }
3229
3230     @Override
3231     public int[] getPackageGids(String packageName, int flags, int userId) {
3232         if (!sUserManager.exists(userId)) return null;
3233         flags = updateFlagsForPackage(flags, userId, packageName);
3234         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3235                 false /* requireFullPermission */, false /* checkShell */,
3236                 "getPackageGids");
3237
3238         // reader
3239         synchronized (mPackages) {
3240             final PackageParser.Package p = mPackages.get(packageName);
3241             if (p != null && p.isMatch(flags)) {
3242                 PackageSetting ps = (PackageSetting) p.mExtras;
3243                 return ps.getPermissionsState().computeGids(userId);
3244             }
3245             if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3246                 final PackageSetting ps = mSettings.mPackages.get(packageName);
3247                 if (ps != null && ps.isMatch(flags)) {
3248                     return ps.getPermissionsState().computeGids(userId);
3249                 }
3250             }
3251         }
3252
3253         return null;
3254     }
3255
3256     static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3257         if (bp.perm != null) {
3258             return PackageParser.generatePermissionInfo(bp.perm, flags);
3259         }
3260         PermissionInfo pi = new PermissionInfo();
3261         pi.name = bp.name;
3262         pi.packageName = bp.sourcePackage;
3263         pi.nonLocalizedLabel = bp.name;
3264         pi.protectionLevel = bp.protectionLevel;
3265         return pi;
3266     }
3267
3268     @Override
3269     public PermissionInfo getPermissionInfo(String name, int flags) {
3270         // reader
3271         synchronized (mPackages) {
3272             final BasePermission p = mSettings.mPermissions.get(name);
3273             if (p != null) {
3274                 return generatePermissionInfo(p, flags);
3275             }
3276             return null;
3277         }
3278     }
3279
3280     @Override
3281     public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3282             int flags) {
3283         // reader
3284         synchronized (mPackages) {
3285             if (group != null && !mPermissionGroups.containsKey(group)) {
3286                 // This is thrown as NameNotFoundException
3287                 return null;
3288             }
3289
3290             ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3291             for (BasePermission p : mSettings.mPermissions.values()) {
3292                 if (group == null) {
3293                     if (p.perm == null || p.perm.info.group == null) {
3294                         out.add(generatePermissionInfo(p, flags));
3295                     }
3296                 } else {
3297                     if (p.perm != null && group.equals(p.perm.info.group)) {
3298                         out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3299                     }
3300                 }
3301             }
3302             return new ParceledListSlice<>(out);
3303         }
3304     }
3305
3306     @Override
3307     public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3308         // reader
3309         synchronized (mPackages) {
3310             return PackageParser.generatePermissionGroupInfo(
3311                     mPermissionGroups.get(name), flags);
3312         }
3313     }
3314
3315     @Override
3316     public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3317         // reader
3318         synchronized (mPackages) {
3319             final int N = mPermissionGroups.size();
3320             ArrayList<PermissionGroupInfo> out
3321                     = new ArrayList<PermissionGroupInfo>(N);
3322             for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3323                 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3324             }
3325             return new ParceledListSlice<>(out);
3326         }
3327     }
3328
3329     private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3330             int userId) {
3331         if (!sUserManager.exists(userId)) return null;
3332         PackageSetting ps = mSettings.mPackages.get(packageName);
3333         if (ps != null) {
3334             if (ps.pkg == null) {
3335                 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3336                 if (pInfo != null) {
3337                     return pInfo.applicationInfo;
3338                 }
3339                 return null;
3340             }
3341             return PackageParser.generateApplicationInfo(ps.pkg, flags,
3342                     ps.readUserState(userId), userId);
3343         }
3344         return null;
3345     }
3346
3347     @Override
3348     public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3349         if (!sUserManager.exists(userId)) return null;
3350         flags = updateFlagsForApplication(flags, userId, packageName);
3351         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3352                 false /* requireFullPermission */, false /* checkShell */, "get application info");
3353
3354         // writer
3355         synchronized (mPackages) {
3356             // Normalize package name to hanlde renamed packages
3357             packageName = normalizePackageNameLPr(packageName);
3358
3359             PackageParser.Package p = mPackages.get(packageName);
3360             if (DEBUG_PACKAGE_INFO) Log.v(
3361                     TAG, "getApplicationInfo " + packageName
3362                     + ": " + p);
3363             if (p != null) {
3364                 PackageSetting ps = mSettings.mPackages.get(packageName);
3365                 if (ps == null) return null;
3366                 // Note: isEnabledLP() does not apply here - always return info
3367                 return PackageParser.generateApplicationInfo(
3368                         p, flags, ps.readUserState(userId), userId);
3369             }
3370             if ("android".equals(packageName)||"system".equals(packageName)) {
3371                 return mAndroidApplication;
3372             }
3373             if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3374                 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3375             }
3376         }
3377         return null;
3378     }
3379
3380     private String normalizePackageNameLPr(String packageName) {
3381         String normalizedPackageName = mSettings.mRenamedPackages.get(packageName);
3382         return normalizedPackageName != null ? normalizedPackageName : packageName;
3383     }
3384
3385     @Override
3386     public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3387             final IPackageDataObserver observer) {
3388         mContext.enforceCallingOrSelfPermission(
3389                 android.Manifest.permission.CLEAR_APP_CACHE, null);
3390         // Queue up an async operation since clearing cache may take a little while.
3391         mHandler.post(new Runnable() {
3392             public void run() {
3393                 mHandler.removeCallbacks(this);
3394                 boolean success = true;
3395                 synchronized (mInstallLock) {
3396                     try {
3397                         mInstaller.freeCache(volumeUuid, freeStorageSize);
3398                     } catch (InstallerException e) {
3399                         Slog.w(TAG, "Couldn't clear application caches: " + e);
3400                         success = false;
3401                     }
3402                 }
3403                 if (observer != null) {
3404                     try {
3405                         observer.onRemoveCompleted(null, success);
3406                     } catch (RemoteException e) {
3407                         Slog.w(TAG, "RemoveException when invoking call back");
3408                     }
3409                 }
3410             }
3411         });
3412     }
3413
3414     @Override
3415     public void freeStorage(final String volumeUuid, final long freeStorageSize,
3416             final IntentSender pi) {
3417         mContext.enforceCallingOrSelfPermission(
3418                 android.Manifest.permission.CLEAR_APP_CACHE, null);
3419         // Queue up an async operation since clearing cache may take a little while.
3420         mHandler.post(new Runnable() {
3421             public void run() {
3422                 mHandler.removeCallbacks(this);
3423                 boolean success = true;
3424                 synchronized (mInstallLock) {
3425                     try {
3426                         mInstaller.freeCache(volumeUuid, freeStorageSize);
3427                     } catch (InstallerException e) {
3428                         Slog.w(TAG, "Couldn't clear application caches: " + e);
3429                         success = false;
3430                     }
3431                 }
3432                 if(pi != null) {
3433                     try {
3434                         // Callback via pending intent
3435                         int code = success ? 1 : 0;
3436                         pi.sendIntent(null, code, null,
3437                                 null, null);
3438                     } catch (SendIntentException e1) {
3439                         Slog.i(TAG, "Failed to send pending intent");
3440                     }
3441                 }
3442             }
3443         });
3444     }
3445
3446     void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3447         synchronized (mInstallLock) {
3448             try {
3449                 mInstaller.freeCache(volumeUuid, freeStorageSize);
3450             } catch (InstallerException e) {
3451                 throw new IOException("Failed to free enough space", e);
3452             }
3453         }
3454     }
3455
3456     /**
3457      * Update given flags based on encryption status of current user.
3458      */
3459     private int updateFlags(int flags, int userId) {
3460         if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3461                 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3462             // Caller expressed an explicit opinion about what encryption
3463             // aware/unaware components they want to see, so fall through and
3464             // give them what they want
3465         } else {
3466             // Caller expressed no opinion, so match based on user state
3467             if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3468                 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3469             } else {
3470                 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3471             }
3472         }
3473         return flags;
3474     }
3475
3476     private UserManagerInternal getUserManagerInternal() {
3477         if (mUserManagerInternal == null) {
3478             mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3479         }
3480         return mUserManagerInternal;
3481     }
3482
3483     /**
3484      * Update given flags when being used to request {@link PackageInfo}.
3485      */
3486     private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3487         boolean triaged = true;
3488         if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3489                 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3490             // Caller is asking for component details, so they'd better be
3491             // asking for specific encryption matching behavior, or be triaged
3492             if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3493                     | PackageManager.MATCH_DIRECT_BOOT_AWARE
3494                     | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3495                 triaged = false;
3496             }
3497         }
3498         if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3499                 | PackageManager.MATCH_SYSTEM_ONLY
3500                 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3501             triaged = false;
3502         }
3503         if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3504             Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3505                     + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3506         }
3507         return updateFlags(flags, userId);
3508     }
3509
3510     /**
3511      * Update given flags when being used to request {@link ApplicationInfo}.
3512      */
3513     private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3514         return updateFlagsForPackage(flags, userId, cookie);
3515     }
3516
3517     /**
3518      * Update given flags when being used to request {@link ComponentInfo}.
3519      */
3520     private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3521         if (cookie instanceof Intent) {
3522             if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3523                 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3524             }
3525         }
3526
3527         boolean triaged = true;
3528         // Caller is asking for component details, so they'd better be
3529         // asking for specific encryption matching behavior, or be triaged
3530         if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3531                 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3532                 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3533             triaged = false;
3534         }
3535         if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3536             Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3537                     + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3538         }
3539
3540         return updateFlags(flags, userId);
3541     }
3542
3543     /**
3544      * Update given flags when being used to request {@link ResolveInfo}.
3545      */
3546     int updateFlagsForResolve(int flags, int userId, Object cookie) {
3547         // Safe mode means we shouldn't match any third-party components
3548         if (mSafeMode) {
3549             flags |= PackageManager.MATCH_SYSTEM_ONLY;
3550         }
3551
3552         return updateFlagsForComponent(flags, userId, cookie);
3553     }
3554
3555     @Override
3556     public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3557         if (!sUserManager.exists(userId)) return null;
3558         flags = updateFlagsForComponent(flags, userId, component);
3559         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3560                 false /* requireFullPermission */, false /* checkShell */, "get activity info");
3561         synchronized (mPackages) {
3562             PackageParser.Activity a = mActivities.mActivities.get(component);
3563
3564             if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3565             if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3566                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3567                 if (ps == null) return null;
3568                 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3569                         userId);
3570             }
3571             if (mResolveComponentName.equals(component)) {
3572                 return PackageParser.generateActivityInfo(mResolveActivity, flags,
3573                         new PackageUserState(), userId);
3574             }
3575         }
3576         return null;
3577     }
3578
3579     @Override
3580     public boolean activitySupportsIntent(ComponentName component, Intent intent,
3581             String resolvedType) {
3582         synchronized (mPackages) {
3583             if (component.equals(mResolveComponentName)) {
3584                 // The resolver supports EVERYTHING!
3585                 return true;
3586             }
3587             PackageParser.Activity a = mActivities.mActivities.get(component);
3588             if (a == null) {
3589                 return false;
3590             }
3591             for (int i=0; i<a.intents.size(); i++) {
3592                 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3593                         intent.getData(), intent.getCategories(), TAG) >= 0) {
3594                     return true;
3595                 }
3596             }
3597             return false;
3598         }
3599     }
3600
3601     @Override
3602     public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3603         if (!sUserManager.exists(userId)) return null;
3604         flags = updateFlagsForComponent(flags, userId, component);
3605         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3606                 false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3607         synchronized (mPackages) {
3608             PackageParser.Activity a = mReceivers.mActivities.get(component);
3609             if (DEBUG_PACKAGE_INFO) Log.v(
3610                 TAG, "getReceiverInfo " + component + ": " + a);
3611             if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3612                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3613                 if (ps == null) return null;
3614                 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3615                         userId);
3616             }
3617         }
3618         return null;
3619     }
3620
3621     @Override
3622     public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3623         if (!sUserManager.exists(userId)) return null;
3624         flags = updateFlagsForComponent(flags, userId, component);
3625         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3626                 false /* requireFullPermission */, false /* checkShell */, "get service info");
3627         synchronized (mPackages) {
3628             PackageParser.Service s = mServices.mServices.get(component);
3629             if (DEBUG_PACKAGE_INFO) Log.v(
3630                 TAG, "getServiceInfo " + component + ": " + s);
3631             if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3632                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3633                 if (ps == null) return null;
3634                 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3635                         userId);
3636             }
3637         }
3638         return null;
3639     }
3640
3641     @Override
3642     public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3643         if (!sUserManager.exists(userId)) return null;
3644         flags = updateFlagsForComponent(flags, userId, component);
3645         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3646                 false /* requireFullPermission */, false /* checkShell */, "get provider info");
3647         synchronized (mPackages) {
3648             PackageParser.Provider p = mProviders.mProviders.get(component);
3649             if (DEBUG_PACKAGE_INFO) Log.v(
3650                 TAG, "getProviderInfo " + component + ": " + p);
3651             if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3652                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3653                 if (ps == null) return null;
3654                 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3655                         userId);
3656             }
3657         }
3658         return null;
3659     }
3660
3661     @Override
3662     public String[] getSystemSharedLibraryNames() {
3663         Set<String> libSet;
3664         synchronized (mPackages) {
3665             libSet = mSharedLibraries.keySet();
3666             int size = libSet.size();
3667             if (size > 0) {
3668                 String[] libs = new String[size];
3669                 libSet.toArray(libs);
3670                 return libs;
3671             }
3672         }
3673         return null;
3674     }
3675
3676     @Override
3677     public @NonNull String getServicesSystemSharedLibraryPackageName() {
3678         synchronized (mPackages) {
3679             return mServicesSystemSharedLibraryPackageName;
3680         }
3681     }
3682
3683     @Override
3684     public @NonNull String getSharedSystemSharedLibraryPackageName() {
3685         synchronized (mPackages) {
3686             return mSharedSystemSharedLibraryPackageName;
3687         }
3688     }
3689
3690     @Override
3691     public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3692         synchronized (mPackages) {
3693             final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3694
3695             final FeatureInfo fi = new FeatureInfo();
3696             fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3697                     FeatureInfo.GL_ES_VERSION_UNDEFINED);
3698             res.add(fi);
3699
3700             return new ParceledListSlice<>(res);
3701         }
3702     }
3703
3704     @Override
3705     public boolean hasSystemFeature(String name, int version) {
3706         synchronized (mPackages) {
3707             final FeatureInfo feat = mAvailableFeatures.get(name);
3708             if (feat == null) {
3709                 return false;
3710             } else {
3711                 return feat.version >= version;
3712             }
3713         }
3714     }
3715
3716     @Override
3717     public int checkPermission(String permName, String pkgName, int userId) {
3718         if (!sUserManager.exists(userId)) {
3719             return PackageManager.PERMISSION_DENIED;
3720         }
3721
3722         synchronized (mPackages) {
3723             final PackageParser.Package p = mPackages.get(pkgName);
3724             if (p != null && p.mExtras != null) {
3725                 final PackageSetting ps = (PackageSetting) p.mExtras;
3726                 final PermissionsState permissionsState = ps.getPermissionsState();
3727                 if (permissionsState.hasPermission(permName, userId)) {
3728                     return PackageManager.PERMISSION_GRANTED;
3729                 }
3730                 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3731                 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3732                         .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3733                     return PackageManager.PERMISSION_GRANTED;
3734                 }
3735             }
3736         }
3737
3738         return PackageManager.PERMISSION_DENIED;
3739     }
3740
3741     @Override
3742     public int checkUidPermission(String permName, int uid) {
3743         final int userId = UserHandle.getUserId(uid);
3744
3745         if (!sUserManager.exists(userId)) {
3746             return PackageManager.PERMISSION_DENIED;
3747         }
3748
3749         synchronized (mPackages) {
3750             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3751             if (obj != null) {
3752                 final SettingBase ps = (SettingBase) obj;
3753                 final PermissionsState permissionsState = ps.getPermissionsState();
3754                 if (permissionsState.hasPermission(permName, userId)) {
3755                     return PackageManager.PERMISSION_GRANTED;
3756                 }
3757                 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3758                 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3759                         .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3760                     return PackageManager.PERMISSION_GRANTED;
3761                 }
3762             } else {
3763                 ArraySet<String> perms = mSystemPermissions.get(uid);
3764                 if (perms != null) {
3765                     if (perms.contains(permName)) {
3766                         return PackageManager.PERMISSION_GRANTED;
3767                     }
3768                     if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3769                             .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3770                         return PackageManager.PERMISSION_GRANTED;
3771                     }
3772                 }
3773             }
3774         }
3775
3776         return PackageManager.PERMISSION_DENIED;
3777     }
3778
3779     @Override
3780     public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3781         if (UserHandle.getCallingUserId() != userId) {
3782             mContext.enforceCallingPermission(
3783                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3784                     "isPermissionRevokedByPolicy for user " + userId);
3785         }
3786
3787         if (checkPermission(permission, packageName, userId)
3788                 == PackageManager.PERMISSION_GRANTED) {
3789             return false;
3790         }
3791
3792         final long identity = Binder.clearCallingIdentity();
3793         try {
3794             final int flags = getPermissionFlags(permission, packageName, userId);
3795             return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3796         } finally {
3797             Binder.restoreCallingIdentity(identity);
3798         }
3799     }
3800
3801     @Override
3802     public String getPermissionControllerPackageName() {
3803         synchronized (mPackages) {
3804             return mRequiredInstallerPackage;
3805         }
3806     }
3807
3808     /**
3809      * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3810      * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3811      * @param checkShell whether to prevent shell from access if there's a debugging restriction
3812      * @param message the message to log on security exception
3813      */
3814     void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3815             boolean checkShell, String message) {
3816         if (userId < 0) {
3817             throw new IllegalArgumentException("Invalid userId " + userId);
3818         }
3819         if (checkShell) {
3820             enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3821         }
3822         if (userId == UserHandle.getUserId(callingUid)) return;
3823         if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3824             if (requireFullPermission) {
3825                 mContext.enforceCallingOrSelfPermission(
3826                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3827             } else {
3828                 try {
3829                     mContext.enforceCallingOrSelfPermission(
3830                             android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3831                 } catch (SecurityException se) {
3832                     mContext.enforceCallingOrSelfPermission(
3833                             android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3834                 }
3835             }
3836         }
3837     }
3838
3839     void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3840         if (callingUid == Process.SHELL_UID) {
3841             if (userHandle >= 0
3842                     && sUserManager.hasUserRestriction(restriction, userHandle)) {
3843                 throw new SecurityException("Shell does not have permission to access user "
3844                         + userHandle);
3845             } else if (userHandle < 0) {
3846                 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3847                         + Debug.getCallers(3));
3848             }
3849         }
3850     }
3851
3852     private BasePermission findPermissionTreeLP(String permName) {
3853         for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3854             if (permName.startsWith(bp.name) &&
3855                     permName.length() > bp.name.length() &&
3856                     permName.charAt(bp.name.length()) == '.') {
3857                 return bp;
3858             }
3859         }
3860         return null;
3861     }
3862
3863     private BasePermission checkPermissionTreeLP(String permName) {
3864         if (permName != null) {
3865             BasePermission bp = findPermissionTreeLP(permName);
3866             if (bp != null) {
3867                 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3868                     return bp;
3869                 }
3870                 throw new SecurityException("Calling uid "
3871                         + Binder.getCallingUid()
3872                         + " is not allowed to add to permission tree "
3873                         + bp.name + " owned by uid " + bp.uid);
3874             }
3875         }
3876         throw new SecurityException("No permission tree found for " + permName);
3877     }
3878
3879     static boolean compareStrings(CharSequence s1, CharSequence s2) {
3880         if (s1 == null) {
3881             return s2 == null;
3882         }
3883         if (s2 == null) {
3884             return false;
3885         }
3886         if (s1.getClass() != s2.getClass()) {
3887             return false;
3888         }
3889         return s1.equals(s2);
3890     }
3891
3892     static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3893         if (pi1.icon != pi2.icon) return false;
3894         if (pi1.logo != pi2.logo) return false;
3895         if (pi1.protectionLevel != pi2.protectionLevel) return false;
3896         if (!compareStrings(pi1.name, pi2.name)) return false;
3897         if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3898         // We'll take care of setting this one.
3899         if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3900         // These are not currently stored in settings.
3901         //if (!compareStrings(pi1.group, pi2.group)) return false;
3902         //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3903         //if (pi1.labelRes != pi2.labelRes) return false;
3904         //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3905         return true;
3906     }
3907
3908     int permissionInfoFootprint(PermissionInfo info) {
3909         int size = info.name.length();
3910         if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3911         if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3912         return size;
3913     }
3914
3915     int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3916         int size = 0;
3917         for (BasePermission perm : mSettings.mPermissions.values()) {
3918             if (perm.uid == tree.uid) {
3919                 size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3920             }
3921         }
3922         return size;
3923     }
3924
3925     void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3926         // We calculate the max size of permissions defined by this uid and throw
3927         // if that plus the size of 'info' would exceed our stated maximum.
3928         if (tree.uid != Process.SYSTEM_UID) {
3929             final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3930             if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3931                 throw new SecurityException("Permission tree size cap exceeded");
3932             }
3933         }
3934     }
3935
3936     boolean addPermissionLocked(PermissionInfo info, boolean async) {
3937         if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3938             throw new SecurityException("Label must be specified in permission");
3939         }
3940         BasePermission tree = checkPermissionTreeLP(info.name);
3941         BasePermission bp = mSettings.mPermissions.get(info.name);
3942         boolean added = bp == null;
3943         boolean changed = true;
3944         int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3945         if (added) {
3946             enforcePermissionCapLocked(info, tree);
3947             bp = new BasePermission(info.name, tree.sourcePackage,
3948                     BasePermission.TYPE_DYNAMIC);
3949         } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3950             throw new SecurityException(
3951                     "Not allowed to modify non-dynamic permission "
3952                     + info.name);
3953         } else {
3954             if (bp.protectionLevel == fixedLevel
3955                     && bp.perm.owner.equals(tree.perm.owner)
3956                     && bp.uid == tree.uid
3957                     && comparePermissionInfos(bp.perm.info, info)) {
3958                 changed = false;
3959             }
3960         }
3961         bp.protectionLevel = fixedLevel;
3962         info = new PermissionInfo(info);
3963         info.protectionLevel = fixedLevel;
3964         bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3965         bp.perm.info.packageName = tree.perm.info.packageName;
3966         bp.uid = tree.uid;
3967         if (added) {
3968             mSettings.mPermissions.put(info.name, bp);
3969         }
3970         if (changed) {
3971             if (!async) {
3972                 mSettings.writeLPr();
3973             } else {
3974                 scheduleWriteSettingsLocked();
3975             }
3976         }
3977         return added;
3978     }
3979
3980     @Override
3981     public boolean addPermission(PermissionInfo info) {
3982         synchronized (mPackages) {
3983             return addPermissionLocked(info, false);
3984         }
3985     }
3986
3987     @Override
3988     public boolean addPermissionAsync(PermissionInfo info) {
3989         synchronized (mPackages) {
3990             return addPermissionLocked(info, true);
3991         }
3992     }
3993
3994     @Override
3995     public void removePermission(String name) {
3996         synchronized (mPackages) {
3997             checkPermissionTreeLP(name);
3998             BasePermission bp = mSettings.mPermissions.get(name);
3999             if (bp != null) {
4000                 if (bp.type != BasePermission.TYPE_DYNAMIC) {
4001                     throw new SecurityException(
4002                             "Not allowed to modify non-dynamic permission "
4003                             + name);
4004                 }
4005                 mSettings.mPermissions.remove(name);
4006                 mSettings.writeLPr();
4007             }
4008         }
4009     }
4010
4011     private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4012             BasePermission bp) {
4013         int index = pkg.requestedPermissions.indexOf(bp.name);
4014         if (index == -1) {
4015             throw new SecurityException("Package " + pkg.packageName
4016                     + " has not requested permission " + bp.name);
4017         }
4018         if (!bp.isRuntime() && !bp.isDevelopment()) {
4019             throw new SecurityException("Permission " + bp.name
4020                     + " is not a changeable permission type");
4021         }
4022     }
4023
4024     @Override
4025     public void grantRuntimePermission(String packageName, String name, final int userId) {
4026         if (!sUserManager.exists(userId)) {
4027             Log.e(TAG, "No such user:" + userId);
4028             return;
4029         }
4030
4031         mContext.enforceCallingOrSelfPermission(
4032                 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4033                 "grantRuntimePermission");
4034
4035         enforceCrossUserPermission(Binder.getCallingUid(), userId,
4036                 true /* requireFullPermission */, true /* checkShell */,
4037                 "grantRuntimePermission");
4038
4039         final int uid;
4040         final SettingBase sb;
4041
4042         synchronized (mPackages) {
4043             final PackageParser.Package pkg = mPackages.get(packageName);
4044             if (pkg == null) {
4045                 throw new IllegalArgumentException("Unknown package: " + packageName);
4046             }
4047
4048             final BasePermission bp = mSettings.mPermissions.get(name);
4049             if (bp == null) {
4050                 throw new IllegalArgumentException("Unknown permission: " + name);
4051             }
4052
4053             enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4054
4055             // If a permission review is required for legacy apps we represent
4056             // their permissions as always granted runtime ones since we need
4057             // to keep the review required permission flag per user while an
4058             // install permission's state is shared across all users.
4059             if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
4060                     && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4061                     && bp.isRuntime()) {
4062                 return;
4063             }
4064
4065             uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4066             sb = (SettingBase) pkg.mExtras;
4067             if (sb == null) {
4068                 throw new IllegalArgumentException("Unknown package: " + packageName);
4069             }
4070
4071             final PermissionsState permissionsState = sb.getPermissionsState();
4072
4073             final int flags = permissionsState.getPermissionFlags(name, userId);
4074             if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4075                 throw new SecurityException("Cannot grant system fixed permission "
4076                         + name + " for package " + packageName);
4077             }
4078
4079             if (bp.isDevelopment()) {
4080                 // Development permissions must be handled specially, since they are not
4081                 // normal runtime permissions.  For now they apply to all users.
4082                 if (permissionsState.grantInstallPermission(bp) !=
4083                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
4084                     scheduleWriteSettingsLocked();
4085                 }
4086                 return;
4087             }
4088
4089             if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4090                 Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4091                 return;
4092             }
4093
4094             final int result = permissionsState.grantRuntimePermission(bp, userId);
4095             switch (result) {
4096                 case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4097                     return;
4098                 }
4099
4100                 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4101                     final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4102                     mHandler.post(new Runnable() {
4103                         @Override
4104                         public void run() {
4105                             killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4106                         }
4107                     });
4108                 }
4109                 break;
4110             }
4111
4112             mOnPermissionChangeListeners.onPermissionsChanged(uid);
4113
4114             // Not critical if that is lost - app has to request again.
4115             mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4116         }
4117
4118         // Only need to do this if user is initialized. Otherwise it's a new user
4119         // and there are no processes running as the user yet and there's no need
4120         // to make an expensive call to remount processes for the changed permissions.
4121         if (READ_EXTERNAL_STORAGE.equals(name)
4122                 || WRITE_EXTERNAL_STORAGE.equals(name)) {
4123             final long token = Binder.clearCallingIdentity();
4124             try {
4125                 if (sUserManager.isInitialized(userId)) {
4126                     MountServiceInternal mountServiceInternal = LocalServices.getService(
4127                             MountServiceInternal.class);
4128                     mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4129                 }
4130             } finally {
4131                 Binder.restoreCallingIdentity(token);
4132             }
4133         }
4134     }
4135
4136     @Override
4137     public void revokeRuntimePermission(String packageName, String name, int userId) {
4138         if (!sUserManager.exists(userId)) {
4139             Log.e(TAG, "No such user:" + userId);
4140             return;
4141         }
4142
4143         mContext.enforceCallingOrSelfPermission(
4144                 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4145                 "revokeRuntimePermission");
4146
4147         enforceCrossUserPermission(Binder.getCallingUid(), userId,
4148                 true /* requireFullPermission */, true /* checkShell */,
4149                 "revokeRuntimePermission");
4150
4151         final int appId;
4152
4153         synchronized (mPackages) {
4154             final PackageParser.Package pkg = mPackages.get(packageName);
4155             if (pkg == null) {
4156                 throw new IllegalArgumentException("Unknown package: " + packageName);
4157             }
4158
4159             final BasePermission bp = mSettings.mPermissions.get(name);
4160             if (bp == null) {
4161                 throw new IllegalArgumentException("Unknown permission: " + name);
4162             }
4163
4164             enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4165
4166             // If a permission review is required for legacy apps we represent
4167             // their permissions as always granted runtime ones since we need
4168             // to keep the review required permission flag per user while an
4169             // install permission's state is shared across all users.
4170             if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
4171                     && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4172                     && bp.isRuntime()) {
4173                 return;
4174             }
4175
4176             SettingBase sb = (SettingBase) pkg.mExtras;
4177             if (sb == null) {
4178                 throw new IllegalArgumentException("Unknown package: " + packageName);
4179             }
4180
4181             final PermissionsState permissionsState = sb.getPermissionsState();
4182
4183             final int flags = permissionsState.getPermissionFlags(name, userId);
4184             if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4185                 throw new SecurityException("Cannot revoke system fixed permission "
4186                         + name + " for package " + packageName);
4187             }
4188
4189             if (bp.isDevelopment()) {
4190                 // Development permissions must be handled specially, since they are not
4191                 // normal runtime permissions.  For now they apply to all users.
4192                 if (permissionsState.revokeInstallPermission(bp) !=
4193                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
4194                     scheduleWriteSettingsLocked();
4195                 }
4196                 return;
4197             }
4198
4199             if (permissionsState.revokeRuntimePermission(bp, userId) ==
4200                     PermissionsState.PERMISSION_OPERATION_FAILURE) {
4201                 return;
4202             }
4203
4204             mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4205
4206             // Critical, after this call app should never have the permission.
4207             mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4208
4209             appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4210         }
4211
4212         killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4213     }
4214
4215     @Override
4216     public void resetRuntimePermissions() {
4217         mContext.enforceCallingOrSelfPermission(
4218                 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4219                 "revokeRuntimePermission");
4220
4221         int callingUid = Binder.getCallingUid();
4222         if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4223             mContext.enforceCallingOrSelfPermission(
4224                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4225                     "resetRuntimePermissions");
4226         }
4227
4228         synchronized (mPackages) {
4229             updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4230             for (int userId : UserManagerService.getInstance().getUserIds()) {
4231                 final int packageCount = mPackages.size();
4232                 for (int i = 0; i < packageCount; i++) {
4233                     PackageParser.Package pkg = mPackages.valueAt(i);
4234                     if (!(pkg.mExtras instanceof PackageSetting)) {
4235                         continue;
4236                     }
4237                     PackageSetting ps = (PackageSetting) pkg.mExtras;
4238                     resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4239                 }
4240             }
4241         }
4242     }
4243
4244     @Override
4245     public int getPermissionFlags(String name, String packageName, int userId) {
4246         if (!sUserManager.exists(userId)) {
4247             return 0;
4248         }
4249
4250         enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4251
4252         enforceCrossUserPermission(Binder.getCallingUid(), userId,
4253                 true /* requireFullPermission */, false /* checkShell */,
4254                 "getPermissionFlags");
4255
4256         synchronized (mPackages) {
4257             final PackageParser.Package pkg = mPackages.get(packageName);
4258             if (pkg == null) {
4259                 return 0;
4260             }
4261
4262             final BasePermission bp = mSettings.mPermissions.get(name);
4263             if (bp == null) {
4264                 return 0;
4265             }
4266
4267             SettingBase sb = (SettingBase) pkg.mExtras;
4268             if (sb == null) {
4269                 return 0;
4270             }
4271
4272             PermissionsState permissionsState = sb.getPermissionsState();
4273             return permissionsState.getPermissionFlags(name, userId);
4274         }
4275     }
4276
4277     @Override
4278     public void updatePermissionFlags(String name, String packageName, int flagMask,
4279             int flagValues, int userId) {
4280         if (!sUserManager.exists(userId)) {
4281             return;
4282         }
4283
4284         enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4285
4286         enforceCrossUserPermission(Binder.getCallingUid(), userId,
4287                 true /* requireFullPermission */, true /* checkShell */,
4288                 "updatePermissionFlags");
4289
4290         // Only the system can change these flags and nothing else.
4291         if (getCallingUid() != Process.SYSTEM_UID) {
4292             flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4293             flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4294             flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4295             flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4296             flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4297         }
4298
4299         synchronized (mPackages) {
4300             final PackageParser.Package pkg = mPackages.get(packageName);
4301             if (pkg == null) {
4302                 throw new IllegalArgumentException("Unknown package: " + packageName);
4303             }
4304
4305             final BasePermission bp = mSettings.mPermissions.get(name);
4306             if (bp == null) {
4307                 throw new IllegalArgumentException("Unknown permission: " + name);
4308             }
4309
4310             SettingBase sb = (SettingBase) pkg.mExtras;
4311             if (sb == null) {
4312                 throw new IllegalArgumentException("Unknown package: " + packageName);
4313             }
4314
4315             PermissionsState permissionsState = sb.getPermissionsState();
4316
4317             boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4318
4319             if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4320                 // Install and runtime permissions are stored in different places,
4321                 // so figure out what permission changed and persist the change.
4322                 if (permissionsState.getInstallPermissionState(name) != null) {
4323                     scheduleWriteSettingsLocked();
4324                 } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4325                         || hadState) {
4326                     mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4327                 }
4328             }
4329         }
4330     }
4331
4332     /**
4333      * Update the permission flags for all packages and runtime permissions of a user in order
4334      * to allow device or profile owner to remove POLICY_FIXED.
4335      */
4336     @Override
4337     public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4338         if (!sUserManager.exists(userId)) {
4339             return;
4340         }
4341
4342         enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4343
4344         enforceCrossUserPermission(Binder.getCallingUid(), userId,
4345                 true /* requireFullPermission */, true /* checkShell */,
4346                 "updatePermissionFlagsForAllApps");
4347
4348         // Only the system can change system fixed flags.
4349         if (getCallingUid() != Process.SYSTEM_UID) {
4350             flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4351             flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4352         }
4353
4354         synchronized (mPackages) {
4355             boolean changed = false;
4356             final int packageCount = mPackages.size();
4357             for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4358                 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4359                 SettingBase sb = (SettingBase) pkg.mExtras;
4360                 if (sb == null) {
4361                     continue;
4362                 }
4363                 PermissionsState permissionsState = sb.getPermissionsState();
4364                 changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4365                         userId, flagMask, flagValues);
4366             }
4367             if (changed) {
4368                 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4369             }
4370         }
4371     }
4372
4373     private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4374         if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4375                 != PackageManager.PERMISSION_GRANTED
4376             && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4377                 != PackageManager.PERMISSION_GRANTED) {
4378             throw new SecurityException(message + " requires "
4379                     + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4380                     + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4381         }
4382     }
4383
4384     @Override
4385     public boolean shouldShowRequestPermissionRationale(String permissionName,
4386             String packageName, int userId) {
4387         if (UserHandle.getCallingUserId() != userId) {
4388             mContext.enforceCallingPermission(
4389                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4390                     "canShowRequestPermissionRationale for user " + userId);
4391         }
4392
4393         final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4394         if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4395             return false;
4396         }
4397
4398         if (checkPermission(permissionName, packageName, userId)
4399                 == PackageManager.PERMISSION_GRANTED) {
4400             return false;
4401         }
4402
4403         final int flags;
4404
4405         final long identity = Binder.clearCallingIdentity();
4406         try {
4407             flags = getPermissionFlags(permissionName,
4408                     packageName, userId);
4409         } finally {
4410             Binder.restoreCallingIdentity(identity);
4411         }
4412
4413         final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4414                 | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4415                 | PackageManager.FLAG_PERMISSION_USER_FIXED;
4416
4417         if ((flags & fixedFlags) != 0) {
4418             return false;
4419         }
4420
4421         return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4422     }
4423
4424     @Override
4425     public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4426         mContext.enforceCallingOrSelfPermission(
4427                 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4428                 "addOnPermissionsChangeListener");
4429
4430         synchronized (mPackages) {
4431             mOnPermissionChangeListeners.addListenerLocked(listener);
4432         }
4433     }
4434
4435     @Override
4436     public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4437         synchronized (mPackages) {
4438             mOnPermissionChangeListeners.removeListenerLocked(listener);
4439         }
4440     }
4441
4442     @Override
4443     public boolean isProtectedBroadcast(String actionName) {
4444         synchronized (mPackages) {
4445             if (mProtectedBroadcasts.contains(actionName)) {
4446                 return true;
4447             } else if (actionName != null) {
4448                 // TODO: remove these terrible hacks
4449                 if (actionName.startsWith("android.net.netmon.lingerExpired")
4450                         || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4451                         || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4452                         || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4453                     return true;
4454                 }
4455             }
4456         }
4457         return false;
4458     }
4459
4460     @Override
4461     public int checkSignatures(String pkg1, String pkg2) {
4462         synchronized (mPackages) {
4463             final PackageParser.Package p1 = mPackages.get(pkg1);
4464             final PackageParser.Package p2 = mPackages.get(pkg2);
4465             if (p1 == null || p1.mExtras == null
4466                     || p2 == null || p2.mExtras == null) {
4467                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4468             }
4469             return compareSignatures(p1.mSignatures, p2.mSignatures);
4470         }
4471     }
4472
4473     @Override
4474     public int checkUidSignatures(int uid1, int uid2) {
4475         // Map to base uids.
4476         uid1 = UserHandle.getAppId(uid1);
4477         uid2 = UserHandle.getAppId(uid2);
4478         // reader
4479         synchronized (mPackages) {
4480             Signature[] s1;
4481             Signature[] s2;
4482             Object obj = mSettings.getUserIdLPr(uid1);
4483             if (obj != null) {
4484                 if (obj instanceof SharedUserSetting) {
4485                     s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4486                 } else if (obj instanceof PackageSetting) {
4487                     s1 = ((PackageSetting)obj).signatures.mSignatures;
4488                 } else {
4489                     return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4490                 }
4491             } else {
4492                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4493             }
4494             obj = mSettings.getUserIdLPr(uid2);
4495             if (obj != null) {
4496                 if (obj instanceof SharedUserSetting) {
4497                     s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4498                 } else if (obj instanceof PackageSetting) {
4499                     s2 = ((PackageSetting)obj).signatures.mSignatures;
4500                 } else {
4501                     return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4502                 }
4503             } else {
4504                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4505             }
4506             return compareSignatures(s1, s2);
4507         }
4508     }
4509
4510     /**
4511      * This method should typically only be used when granting or revoking
4512      * permissions, since the app may immediately restart after this call.
4513      * <p>
4514      * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4515      * guard your work against the app being relaunched.
4516      */
4517     private void killUid(int appId, int userId, String reason) {
4518         final long identity = Binder.clearCallingIdentity();
4519         try {
4520             IActivityManager am = ActivityManagerNative.getDefault();
4521             if (am != null) {
4522                 try {
4523                     am.killUid(appId, userId, reason);
4524                 } catch (RemoteException e) {
4525                     /* ignore - same process */
4526                 }
4527             }
4528         } finally {
4529             Binder.restoreCallingIdentity(identity);
4530         }
4531     }
4532
4533     /**
4534      * Compares two sets of signatures. Returns:
4535      * <br />
4536      * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4537      * <br />
4538      * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4539      * <br />
4540      * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4541      * <br />
4542      * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4543      * <br />
4544      * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4545      */
4546     static int compareSignatures(Signature[] s1, Signature[] s2) {
4547         if (s1 == null) {
4548             return s2 == null
4549                     ? PackageManager.SIGNATURE_NEITHER_SIGNED
4550                     : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4551         }
4552
4553         if (s2 == null) {
4554             return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4555         }
4556
4557         if (s1.length != s2.length) {
4558             return PackageManager.SIGNATURE_NO_MATCH;
4559         }
4560
4561         // Since both signature sets are of size 1, we can compare without HashSets.
4562         if (s1.length == 1) {
4563             return s1[0].equals(s2[0]) ?
4564                     PackageManager.SIGNATURE_MATCH :
4565                     PackageManager.SIGNATURE_NO_MATCH;
4566         }
4567
4568         ArraySet<Signature> set1 = new ArraySet<Signature>();
4569         for (Signature sig : s1) {
4570             set1.add(sig);
4571         }
4572         ArraySet<Signature> set2 = new ArraySet<Signature>();
4573         for (Signature sig : s2) {
4574             set2.add(sig);
4575         }
4576         // Make sure s2 contains all signatures in s1.
4577         if (set1.equals(set2)) {
4578             return PackageManager.SIGNATURE_MATCH;
4579         }
4580         return PackageManager.SIGNATURE_NO_MATCH;
4581     }
4582
4583     /**
4584      * If the database version for this type of package (internal storage or
4585      * external storage) is less than the version where package signatures
4586      * were updated, return true.
4587      */
4588     private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4589         final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4590         return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4591     }
4592
4593     /**
4594      * Used for backward compatibility to make sure any packages with
4595      * certificate chains get upgraded to the new style. {@code existingSigs}
4596      * will be in the old format (since they were stored on disk from before the
4597      * system upgrade) and {@code scannedSigs} will be in the newer format.
4598      */
4599     private int compareSignaturesCompat(PackageSignatures existingSigs,
4600             PackageParser.Package scannedPkg) {
4601         if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4602             return PackageManager.SIGNATURE_NO_MATCH;
4603         }
4604
4605         ArraySet<Signature> existingSet = new ArraySet<Signature>();
4606         for (Signature sig : existingSigs.mSignatures) {
4607             existingSet.add(sig);
4608         }
4609         ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4610         for (Signature sig : scannedPkg.mSignatures) {
4611             try {
4612                 Signature[] chainSignatures = sig.getChainSignatures();
4613                 for (Signature chainSig : chainSignatures) {
4614                     scannedCompatSet.add(chainSig);
4615                 }
4616             } catch (CertificateEncodingException e) {
4617                 scannedCompatSet.add(sig);
4618             }
4619         }
4620         /*
4621          * Make sure the expanded scanned set contains all signatures in the
4622          * existing one.
4623          */
4624         if (scannedCompatSet.equals(existingSet)) {
4625             // Migrate the old signatures to the new scheme.
4626             existingSigs.assignSignatures(scannedPkg.mSignatures);
4627             // The new KeySets will be re-added later in the scanning process.
4628             synchronized (mPackages) {
4629                 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4630             }
4631             return PackageManager.SIGNATURE_MATCH;
4632         }
4633         return PackageManager.SIGNATURE_NO_MATCH;
4634     }
4635
4636     private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4637         final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4638         return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4639     }
4640
4641     private int compareSignaturesRecover(PackageSignatures existingSigs,
4642             PackageParser.Package scannedPkg) {
4643         if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4644             return PackageManager.SIGNATURE_NO_MATCH;
4645         }
4646
4647         String msg = null;
4648         try {
4649             if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4650                 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4651                         + scannedPkg.packageName);
4652                 return PackageManager.SIGNATURE_MATCH;
4653             }
4654         } catch (CertificateException e) {
4655             msg = e.getMessage();
4656         }
4657
4658         logCriticalInfo(Log.INFO,
4659                 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4660         return PackageManager.SIGNATURE_NO_MATCH;
4661     }
4662
4663     @Override
4664     public List<String> getAllPackages() {
4665         synchronized (mPackages) {
4666             return new ArrayList<String>(mPackages.keySet());
4667         }
4668     }
4669
4670     @Override
4671     public String[] getPackagesForUid(int uid) {
4672         uid = UserHandle.getAppId(uid);
4673         // reader
4674         synchronized (mPackages) {
4675             Object obj = mSettings.getUserIdLPr(uid);
4676             if (obj instanceof SharedUserSetting) {
4677                 final SharedUserSetting sus = (SharedUserSetting) obj;
4678                 final int N = sus.packages.size();
4679                 final String[] res = new String[N];
4680                 for (int i = 0; i < N; i++) {
4681                     res[i] = sus.packages.valueAt(i).name;
4682                 }
4683                 return res;
4684             } else if (obj instanceof PackageSetting) {
4685                 final PackageSetting ps = (PackageSetting) obj;
4686                 return new String[] { ps.name };
4687             }
4688         }
4689         return null;
4690     }
4691
4692     @Override
4693     public String getNameForUid(int uid) {
4694         // reader
4695         synchronized (mPackages) {
4696             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4697             if (obj instanceof SharedUserSetting) {
4698                 final SharedUserSetting sus = (SharedUserSetting) obj;
4699                 return sus.name + ":" + sus.userId;
4700             } else if (obj instanceof PackageSetting) {
4701                 final PackageSetting ps = (PackageSetting) obj;
4702                 return ps.name;
4703             }
4704         }
4705         return null;
4706     }
4707
4708     @Override
4709     public int getUidForSharedUser(String sharedUserName) {
4710         if(sharedUserName == null) {
4711             return -1;
4712         }
4713         // reader
4714         synchronized (mPackages) {
4715             final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4716             if (suid == null) {
4717                 return -1;
4718             }
4719             return suid.userId;
4720         }
4721     }
4722
4723     @Override
4724     public int getFlagsForUid(int uid) {
4725         synchronized (mPackages) {
4726             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4727             if (obj instanceof SharedUserSetting) {
4728                 final SharedUserSetting sus = (SharedUserSetting) obj;
4729                 return sus.pkgFlags;
4730             } else if (obj instanceof PackageSetting) {
4731                 final PackageSetting ps = (PackageSetting) obj;
4732                 return ps.pkgFlags;
4733             }
4734         }
4735         return 0;
4736     }
4737
4738     @Override
4739     public int getPrivateFlagsForUid(int uid) {
4740         synchronized (mPackages) {
4741             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4742             if (obj instanceof SharedUserSetting) {
4743                 final SharedUserSetting sus = (SharedUserSetting) obj;
4744                 return sus.pkgPrivateFlags;
4745             } else if (obj instanceof PackageSetting) {
4746                 final PackageSetting ps = (PackageSetting) obj;
4747                 return ps.pkgPrivateFlags;
4748             }
4749         }
4750         return 0;
4751     }
4752
4753     @Override
4754     public boolean isUidPrivileged(int uid) {
4755         uid = UserHandle.getAppId(uid);
4756         // reader
4757         synchronized (mPackages) {
4758             Object obj = mSettings.getUserIdLPr(uid);
4759             if (obj instanceof SharedUserSetting) {
4760                 final SharedUserSetting sus = (SharedUserSetting) obj;
4761                 final Iterator<PackageSetting> it = sus.packages.iterator();
4762                 while (it.hasNext()) {
4763                     if (it.next().isPrivileged()) {
4764                         return true;
4765                     }
4766                 }
4767             } else if (obj instanceof PackageSetting) {
4768                 final PackageSetting ps = (PackageSetting) obj;
4769                 return ps.isPrivileged();
4770             }
4771         }
4772         return false;
4773     }
4774
4775     @Override
4776     public String[] getAppOpPermissionPackages(String permissionName) {
4777         synchronized (mPackages) {
4778             ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4779             if (pkgs == null) {
4780                 return null;
4781             }
4782             return pkgs.toArray(new String[pkgs.size()]);
4783         }
4784     }
4785
4786     @Override
4787     public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4788             int flags, int userId) {
4789         try {
4790             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4791
4792             if (!sUserManager.exists(userId)) return null;
4793             flags = updateFlagsForResolve(flags, userId, intent);
4794             enforceCrossUserPermission(Binder.getCallingUid(), userId,
4795                     false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4796
4797             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4798             final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4799                     flags, userId);
4800             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4801
4802             final ResolveInfo bestChoice =
4803                     chooseBestActivity(intent, resolvedType, flags, query, userId);
4804             return bestChoice;
4805         } finally {
4806             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4807         }
4808     }
4809
4810     @Override
4811     public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4812             IntentFilter filter, int match, ComponentName activity) {
4813         final int userId = UserHandle.getCallingUserId();
4814         if (DEBUG_PREFERRED) {
4815             Log.v(TAG, "setLastChosenActivity intent=" + intent
4816                 + " resolvedType=" + resolvedType
4817                 + " flags=" + flags
4818                 + " filter=" + filter
4819                 + " match=" + match
4820                 + " activity=" + activity);
4821             filter.dump(new PrintStreamPrinter(System.out), "    ");
4822         }
4823         intent.setComponent(null);
4824         final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4825                 userId);
4826         // Find any earlier preferred or last chosen entries and nuke them
4827         findPreferredActivity(intent, resolvedType,
4828                 flags, query, 0, false, true, false, userId);
4829         // Add the new activity as the last chosen for this filter
4830         addPreferredActivityInternal(filter, match, null, activity, false, userId,
4831                 "Setting last chosen");
4832     }
4833
4834     @Override
4835     public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4836         final int userId = UserHandle.getCallingUserId();
4837         if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4838         final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4839                 userId);
4840         return findPreferredActivity(intent, resolvedType, flags, query, 0,
4841                 false, false, false, userId);
4842     }
4843
4844     private boolean isEphemeralDisabled() {
4845         // ephemeral apps have been disabled across the board
4846         if (DISABLE_EPHEMERAL_APPS) {
4847             return true;
4848         }
4849         // system isn't up yet; can't read settings, so, assume no ephemeral apps
4850         if (!mSystemReady) {
4851             return true;
4852         }
4853         // we can't get a content resolver until the system is ready; these checks must happen last
4854         final ContentResolver resolver = mContext.getContentResolver();
4855         if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
4856             return true;
4857         }
4858         return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
4859     }
4860
4861     private boolean isEphemeralAllowed(
4862             Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4863             boolean skipPackageCheck) {
4864         // Short circuit and return early if possible.
4865         if (isEphemeralDisabled()) {
4866             return false;
4867         }
4868         final int callingUser = UserHandle.getCallingUserId();
4869         if (callingUser != UserHandle.USER_SYSTEM) {
4870             return false;
4871         }
4872         if (mEphemeralResolverConnection == null) {
4873             return false;
4874         }
4875         if (intent.getComponent() != null) {
4876             return false;
4877         }
4878         if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4879             return false;
4880         }
4881         if (!skipPackageCheck && intent.getPackage() != null) {
4882             return false;
4883         }
4884         final boolean isWebUri = hasWebURI(intent);
4885         if (!isWebUri || intent.getData().getHost() == null) {
4886             return false;
4887         }
4888         // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4889         synchronized (mPackages) {
4890             final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4891             for (int n = 0; n < count; n++) {
4892                 ResolveInfo info = resolvedActivities.get(n);
4893                 String packageName = info.activityInfo.packageName;
4894                 PackageSetting ps = mSettings.mPackages.get(packageName);
4895                 if (ps != null) {
4896                     // Try to get the status from User settings first
4897                     long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4898                     int status = (int) (packedStatus >> 32);
4899                     if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4900                             || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4901                         if (DEBUG_EPHEMERAL) {
4902                             Slog.v(TAG, "DENY ephemeral apps;"
4903                                 + " pkg: " + packageName + ", status: " + status);
4904                         }
4905                         return false;
4906                     }
4907                 }
4908             }
4909         }
4910         // We've exhausted all ways to deny ephemeral application; let the system look for them.
4911         return true;
4912     }
4913
4914     private static EphemeralResolveInfo getEphemeralResolveInfo(
4915             Context context, EphemeralResolverConnection resolverConnection, Intent intent,
4916             String resolvedType, int userId, String packageName) {
4917         final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(),
4918                 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
4919         final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(),
4920                 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
4921         final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
4922                 ephemeralPrefixCount);
4923         final int[] shaPrefix = digest.getDigestPrefix();
4924         final byte[][] digestBytes = digest.getDigestBytes();
4925         final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4926                 resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask);
4927         if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4928             // No hash prefix match; there are no ephemeral apps for this domain.
4929             return null;
4930         }
4931
4932         // Go in reverse order so we match the narrowest scope first.
4933         for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4934             for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4935                 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4936                     continue;
4937                 }
4938                 final List<IntentFilter> filters = ephemeralApplication.getFilters();
4939                 // No filters; this should never happen.
4940                 if (filters.isEmpty()) {
4941                     continue;
4942                 }
4943                 if (packageName != null
4944                         && !packageName.equals(ephemeralApplication.getPackageName())) {
4945                     continue;
4946                 }
4947                 // We have a domain match; resolve the filters to see if anything matches.
4948                 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4949                 for (int j = filters.size() - 1; j >= 0; --j) {
4950                     final EphemeralResolveIntentInfo intentInfo =
4951                             new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4952                     ephemeralResolver.addFilter(intentInfo);
4953                 }
4954                 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4955                         intent, resolvedType, false /*defaultOnly*/, userId);
4956                 if (!matchedResolveInfoList.isEmpty()) {
4957                     return matchedResolveInfoList.get(0);
4958                 }
4959             }
4960         }
4961         // Hash or filter mis-match; no ephemeral apps for this domain.
4962         return null;
4963     }
4964
4965     private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4966             int flags, List<ResolveInfo> query, int userId) {
4967         if (query != null) {
4968             final int N = query.size();
4969             if (N == 1) {
4970                 return query.get(0);
4971             } else if (N > 1) {
4972                 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4973                 // If there is more than one activity with the same priority,
4974                 // then let the user decide between them.
4975                 ResolveInfo r0 = query.get(0);
4976                 ResolveInfo r1 = query.get(1);
4977                 if (DEBUG_INTENT_MATCHING || debug) {
4978                     Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4979                             + r1.activityInfo.name + "=" + r1.priority);
4980                 }
4981                 // If the first activity has a higher priority, or a different
4982                 // default, then it is always desirable to pick it.
4983                 if (r0.priority != r1.priority
4984                         || r0.preferredOrder != r1.preferredOrder
4985                         || r0.isDefault != r1.isDefault) {
4986                     return query.get(0);
4987                 }
4988                 // If we have saved a preference for a preferred activity for
4989                 // this Intent, use that.
4990                 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4991                         flags, query, r0.priority, true, false, debug, userId);
4992                 if (ri != null) {
4993                     return ri;
4994                 }
4995                 ri = new ResolveInfo(mResolveInfo);
4996                 ri.activityInfo = new ActivityInfo(ri.activityInfo);
4997                 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
4998                 // If all of the options come from the same package, show the application's
4999                 // label and icon instead of the generic resolver's.
5000                 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5001                 // and then throw away the ResolveInfo itself, meaning that the caller loses
5002                 // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5003                 // a fallback for this case; we only set the target package's resources on
5004                 // the ResolveInfo, not the ActivityInfo.
5005                 final String intentPackage = intent.getPackage();
5006                 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5007                     final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5008                     ri.resolvePackageName = intentPackage;
5009                     if (userNeedsBadging(userId)) {
5010                         ri.noResourceId = true;
5011                     } else {
5012                         ri.icon = appi.icon;
5013                     }
5014                     ri.iconResourceId = appi.icon;
5015                     ri.labelRes = appi.labelRes;
5016                 }
5017                 ri.activityInfo.applicationInfo = new ApplicationInfo(
5018                         ri.activityInfo.applicationInfo);
5019                 if (userId != 0) {
5020                     ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5021                             UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5022                 }
5023                 // Make sure that the resolver is displayable in car mode
5024                 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5025                 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5026                 return ri;
5027             }
5028         }
5029         return null;
5030     }
5031
5032     /**
5033      * Return true if the given list is not empty and all of its contents have
5034      * an activityInfo with the given package name.
5035      */
5036     private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5037         if (ArrayUtils.isEmpty(list)) {
5038             return false;
5039         }
5040         for (int i = 0, N = list.size(); i < N; i++) {
5041             final ResolveInfo ri = list.get(i);
5042             final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5043             if (ai == null || !packageName.equals(ai.packageName)) {
5044                 return false;
5045             }
5046         }
5047         return true;
5048     }
5049
5050     private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5051             int flags, List<ResolveInfo> query, boolean debug, int userId) {
5052         final int N = query.size();
5053         PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5054                 .get(userId);
5055         // Get the list of persistent preferred activities that handle the intent
5056         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5057         List<PersistentPreferredActivity> pprefs = ppir != null
5058                 ? ppir.queryIntent(intent, resolvedType,
5059                         (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5060                 : null;
5061         if (pprefs != null && pprefs.size() > 0) {
5062             final int M = pprefs.size();
5063             for (int i=0; i<M; i++) {
5064                 final PersistentPreferredActivity ppa = pprefs.get(i);
5065                 if (DEBUG_PREFERRED || debug) {
5066                     Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5067                             + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5068                             + "\n  component=" + ppa.mComponent);
5069                     ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5070                 }
5071                 final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5072                         flags | MATCH_DISABLED_COMPONENTS, userId);
5073                 if (DEBUG_PREFERRED || debug) {
5074                     Slog.v(TAG, "Found persistent preferred activity:");
5075                     if (ai != null) {
5076                         ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5077                     } else {
5078                         Slog.v(TAG, "  null");
5079                     }
5080                 }
5081                 if (ai == null) {
5082                     // This previously registered persistent preferred activity
5083                     // component is no longer known. Ignore it and do NOT remove it.
5084                     continue;
5085                 }
5086                 for (int j=0; j<N; j++) {
5087                     final ResolveInfo ri = query.get(j);
5088                     if (!ri.activityInfo.applicationInfo.packageName
5089                             .equals(ai.applicationInfo.packageName)) {
5090                         continue;
5091                     }
5092                     if (!ri.activityInfo.name.equals(ai.name)) {
5093                         continue;
5094                     }
5095                     //  Found a persistent preference that can handle the intent.
5096                     if (DEBUG_PREFERRED || debug) {
5097                         Slog.v(TAG, "Returning persistent preferred activity: " +
5098                                 ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5099                     }
5100                     return ri;
5101                 }
5102             }
5103         }
5104         return null;
5105     }
5106
5107     // TODO: handle preferred activities missing while user has amnesia
5108     ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5109             List<ResolveInfo> query, int priority, boolean always,
5110             boolean removeMatches, boolean debug, int userId) {
5111         if (!sUserManager.exists(userId)) return null;
5112         flags = updateFlagsForResolve(flags, userId, intent);
5113         // writer
5114         synchronized (mPackages) {
5115             if (intent.getSelector() != null) {
5116                 intent = intent.getSelector();
5117             }
5118             if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5119
5120             // Try to find a matching persistent preferred activity.
5121             ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5122                     debug, userId);
5123
5124             // If a persistent preferred activity matched, use it.
5125             if (pri != null) {
5126                 return pri;
5127             }
5128
5129             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5130             // Get the list of preferred activities that handle the intent
5131             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5132             List<PreferredActivity> prefs = pir != null
5133                     ? pir.queryIntent(intent, resolvedType,
5134                             (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5135                     : null;
5136             if (prefs != null && prefs.size() > 0) {
5137                 boolean changed = false;
5138                 try {
5139                     // First figure out how good the original match set is.
5140                     // We will only allow preferred activities that came
5141                     // from the same match quality.
5142                     int match = 0;
5143
5144                     if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5145
5146                     final int N = query.size();
5147                     for (int j=0; j<N; j++) {
5148                         final ResolveInfo ri = query.get(j);
5149                         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5150                                 + ": 0x" + Integer.toHexString(match));
5151                         if (ri.match > match) {
5152                             match = ri.match;
5153                         }
5154                     }
5155
5156                     if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5157                             + Integer.toHexString(match));
5158
5159                     match &= IntentFilter.MATCH_CATEGORY_MASK;
5160                     final int M = prefs.size();
5161                     for (int i=0; i<M; i++) {
5162                         final PreferredActivity pa = prefs.get(i);
5163                         if (DEBUG_PREFERRED || debug) {
5164                             Slog.v(TAG, "Checking PreferredActivity ds="
5165                                     + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5166                                     + "\n  component=" + pa.mPref.mComponent);
5167                             pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5168                         }
5169                         if (pa.mPref.mMatch != match) {
5170                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5171                                     + Integer.toHexString(pa.mPref.mMatch));
5172                             continue;
5173                         }
5174                         // If it's not an "always" type preferred activity and that's what we're
5175                         // looking for, skip it.
5176                         if (always && !pa.mPref.mAlways) {
5177                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5178                             continue;
5179                         }
5180                         final ActivityInfo ai = getActivityInfo(
5181                                 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5182                                         | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5183                                 userId);
5184                         if (DEBUG_PREFERRED || debug) {
5185                             Slog.v(TAG, "Found preferred activity:");
5186                             if (ai != null) {
5187                                 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5188                             } else {
5189                                 Slog.v(TAG, "  null");
5190                             }
5191                         }
5192                         if (ai == null) {
5193                             // This previously registered preferred activity
5194                             // component is no longer known.  Most likely an update
5195                             // to the app was installed and in the new version this
5196                             // component no longer exists.  Clean it up by removing
5197                             // it from the preferred activities list, and skip it.
5198                             Slog.w(TAG, "Removing dangling preferred activity: "
5199                                     + pa.mPref.mComponent);
5200                             pir.removeFilter(pa);
5201                             changed = true;
5202                             continue;
5203                         }
5204                         for (int j=0; j<N; j++) {
5205                             final ResolveInfo ri = query.get(j);
5206                             if (!ri.activityInfo.applicationInfo.packageName
5207                                     .equals(ai.applicationInfo.packageName)) {
5208                                 continue;
5209                             }
5210                             if (!ri.activityInfo.name.equals(ai.name)) {
5211                                 continue;
5212                             }
5213
5214                             if (removeMatches) {
5215                                 pir.removeFilter(pa);
5216                                 changed = true;
5217                                 if (DEBUG_PREFERRED) {
5218                                     Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5219                                 }
5220                                 break;
5221                             }
5222
5223                             // Okay we found a previously set preferred or last chosen app.
5224                             // If the result set is different from when this
5225                             // was created, we need to clear it and re-ask the
5226                             // user their preference, if we're looking for an "always" type entry.
5227                             if (always && !pa.mPref.sameSet(query)) {
5228                                 Slog.i(TAG, "Result set changed, dropping preferred activity for "
5229                                         + intent + " type " + resolvedType);
5230                                 if (DEBUG_PREFERRED) {
5231                                     Slog.v(TAG, "Removing preferred activity since set changed "
5232                                             + pa.mPref.mComponent);
5233                                 }
5234                                 pir.removeFilter(pa);
5235                                 // Re-add the filter as a "last chosen" entry (!always)
5236                                 PreferredActivity lastChosen = new PreferredActivity(
5237                                         pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5238                                 pir.addFilter(lastChosen);
5239                                 changed = true;
5240                                 return null;
5241                             }
5242
5243                             // Yay! Either the set matched or we're looking for the last chosen
5244                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5245                                     + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5246                             return ri;
5247                         }
5248                     }
5249                 } finally {
5250                     if (changed) {
5251                         if (DEBUG_PREFERRED) {
5252                             Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5253                         }
5254                         scheduleWritePackageRestrictionsLocked(userId);
5255                     }
5256                 }
5257             }
5258         }
5259         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5260         return null;
5261     }
5262
5263     /*
5264      * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5265      */
5266     @Override
5267     public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5268             int targetUserId) {
5269         mContext.enforceCallingOrSelfPermission(
5270                 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5271         List<CrossProfileIntentFilter> matches =
5272                 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5273         if (matches != null) {
5274             int size = matches.size();
5275             for (int i = 0; i < size; i++) {
5276                 if (matches.get(i).getTargetUserId() == targetUserId) return true;
5277             }
5278         }
5279         if (hasWebURI(intent)) {
5280             // cross-profile app linking works only towards the parent.
5281             final UserInfo parent = getProfileParent(sourceUserId);
5282             synchronized(mPackages) {
5283                 int flags = updateFlagsForResolve(0, parent.id, intent);
5284                 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5285                         intent, resolvedType, flags, sourceUserId, parent.id);
5286                 return xpDomainInfo != null;
5287             }
5288         }
5289         return false;
5290     }
5291
5292     private UserInfo getProfileParent(int userId) {
5293         final long identity = Binder.clearCallingIdentity();
5294         try {
5295             return sUserManager.getProfileParent(userId);
5296         } finally {
5297             Binder.restoreCallingIdentity(identity);
5298         }
5299     }
5300
5301     private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5302             String resolvedType, int userId) {
5303         CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5304         if (resolver != null) {
5305             return resolver.queryIntent(intent, resolvedType, false, userId);
5306         }
5307         return null;
5308     }
5309
5310     @Override
5311     public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5312             String resolvedType, int flags, int userId) {
5313         try {
5314             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5315
5316             return new ParceledListSlice<>(
5317                     queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5318         } finally {
5319             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5320         }
5321     }
5322
5323     private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5324             String resolvedType, int flags, int userId) {
5325         if (!sUserManager.exists(userId)) return Collections.emptyList();
5326         flags = updateFlagsForResolve(flags, userId, intent);
5327         enforceCrossUserPermission(Binder.getCallingUid(), userId,
5328                 false /* requireFullPermission */, false /* checkShell */,
5329                 "query intent activities");
5330         ComponentName comp = intent.getComponent();
5331         if (comp == null) {
5332             if (intent.getSelector() != null) {
5333                 intent = intent.getSelector();
5334                 comp = intent.getComponent();
5335             }
5336         }
5337
5338         if (comp != null) {
5339             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5340             final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5341             if (ai != null) {
5342                 final ResolveInfo ri = new ResolveInfo();
5343                 ri.activityInfo = ai;
5344                 list.add(ri);
5345             }
5346             return list;
5347         }
5348
5349         // reader
5350         boolean sortResult = false;
5351         boolean addEphemeral = false;
5352         boolean matchEphemeralPackage = false;
5353         List<ResolveInfo> result;
5354         final String pkgName = intent.getPackage();
5355         synchronized (mPackages) {
5356             if (pkgName == null) {
5357                 List<CrossProfileIntentFilter> matchingFilters =
5358                         getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5359                 // Check for results that need to skip the current profile.
5360                 ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5361                         resolvedType, flags, userId);
5362                 if (xpResolveInfo != null) {
5363                     List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5364                     xpResult.add(xpResolveInfo);
5365                     return filterIfNotSystemUser(xpResult, userId);
5366                 }
5367
5368                 // Check for results in the current profile.
5369                 result = filterIfNotSystemUser(mActivities.queryIntent(
5370                         intent, resolvedType, flags, userId), userId);
5371                 addEphemeral =
5372                         isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5373
5374                 // Check for cross profile results.
5375                 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5376                 xpResolveInfo = queryCrossProfileIntents(
5377                         matchingFilters, intent, resolvedType, flags, userId,
5378                         hasNonNegativePriorityResult);
5379                 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5380                     boolean isVisibleToUser = filterIfNotSystemUser(
5381                             Collections.singletonList(xpResolveInfo), userId).size() > 0;
5382                     if (isVisibleToUser) {
5383                         result.add(xpResolveInfo);
5384                         sortResult = true;
5385                     }
5386                 }
5387                 if (hasWebURI(intent)) {
5388                     CrossProfileDomainInfo xpDomainInfo = null;
5389                     final UserInfo parent = getProfileParent(userId);
5390                     if (parent != null) {
5391                         xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5392                                 flags, userId, parent.id);
5393                     }
5394                     if (xpDomainInfo != null) {
5395                         if (xpResolveInfo != null) {
5396                             // If we didn't remove it, the cross-profile ResolveInfo would be twice
5397                             // in the result.
5398                             result.remove(xpResolveInfo);
5399                         }
5400                         if (result.size() == 0 && !addEphemeral) {
5401                             // No result in current profile, but found candidate in parent user.
5402                             // And we are not going to add emphemeral app, so we can return the
5403                             // result straight away.
5404                             result.add(xpDomainInfo.resolveInfo);
5405                             return result;
5406                         }
5407                     } else if (result.size() <= 1 && !addEphemeral) {
5408                         // No result in parent user and <= 1 result in current profile, and we
5409                         // are not going to add emphemeral app, so we can return the result without
5410                         // further processing.
5411                         return result;
5412                     }
5413                     // We have more than one candidate (combining results from current and parent
5414                     // profile), so we need filtering and sorting.
5415                     result = filterCandidatesWithDomainPreferredActivitiesLPr(
5416                             intent, flags, result, xpDomainInfo, userId);
5417                     sortResult = true;
5418                 }
5419             } else {
5420                 final PackageParser.Package pkg = mPackages.get(pkgName);
5421                 if (pkg != null) {
5422                     result = filterIfNotSystemUser(
5423                             mActivities.queryIntentForPackage(
5424                                     intent, resolvedType, flags, pkg.activities, userId),
5425                             userId);
5426                 } else {
5427                     // the caller wants to resolve for a particular package; however, there
5428                     // were no installed results, so, try to find an ephemeral result
5429                     addEphemeral = isEphemeralAllowed(
5430                             intent, null /*result*/, userId, true /*skipPackageCheck*/);
5431                     matchEphemeralPackage = true;
5432                     result = new ArrayList<ResolveInfo>();
5433                 }
5434             }
5435         }
5436         if (addEphemeral) {
5437             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5438             final EphemeralResolveInfo ai = getEphemeralResolveInfo(
5439                     mContext, mEphemeralResolverConnection, intent, resolvedType, userId,
5440                     matchEphemeralPackage ? pkgName : null);
5441             if (ai != null) {
5442                 if (DEBUG_EPHEMERAL) {
5443                     Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5444                 }
5445                 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5446                 ephemeralInstaller.ephemeralResolveInfo = ai;
5447                 // make sure this resolver is the default
5448                 ephemeralInstaller.isDefault = true;
5449                 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5450                         | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5451                 // add a non-generic filter
5452                 ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5453                 ephemeralInstaller.filter.addDataPath(
5454                         intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5455                 result.add(ephemeralInstaller);
5456             }
5457             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5458         }
5459         if (sortResult) {
5460             Collections.sort(result, mResolvePrioritySorter);
5461         }
5462         return result;
5463     }
5464
5465     private static class CrossProfileDomainInfo {
5466         /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5467         ResolveInfo resolveInfo;
5468         /* Best domain verification status of the activities found in the other profile */
5469         int bestDomainVerificationStatus;
5470     }
5471
5472     private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5473             String resolvedType, int flags, int sourceUserId, int parentUserId) {
5474         if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5475                 sourceUserId)) {
5476             return null;
5477         }
5478         List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5479                 resolvedType, flags, parentUserId);
5480
5481         if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5482             return null;
5483         }
5484         CrossProfileDomainInfo result = null;
5485         int size = resultTargetUser.size();
5486         for (int i = 0; i < size; i++) {
5487             ResolveInfo riTargetUser = resultTargetUser.get(i);
5488             // Intent filter verification is only for filters that specify a host. So don't return
5489             // those that handle all web uris.
5490             if (riTargetUser.handleAllWebDataURI) {
5491                 continue;
5492             }
5493             String packageName = riTargetUser.activityInfo.packageName;
5494             PackageSetting ps = mSettings.mPackages.get(packageName);
5495             if (ps == null) {
5496                 continue;
5497             }
5498             long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5499             int status = (int)(verificationState >> 32);
5500             if (result == null) {
5501                 result = new CrossProfileDomainInfo();
5502                 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5503                         sourceUserId, parentUserId);
5504                 result.bestDomainVerificationStatus = status;
5505             } else {
5506                 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5507                         result.bestDomainVerificationStatus);
5508             }
5509         }
5510         // Don't consider matches with status NEVER across profiles.
5511         if (result != null && result.bestDomainVerificationStatus
5512                 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5513             return null;
5514         }
5515         return result;
5516     }
5517
5518     /**
5519      * Verification statuses are ordered from the worse to the best, except for
5520      * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5521      */
5522     private int bestDomainVerificationStatus(int status1, int status2) {
5523         if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5524             return status2;
5525         }
5526         if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5527             return status1;
5528         }
5529         return (int) MathUtils.max(status1, status2);
5530     }
5531
5532     private boolean isUserEnabled(int userId) {
5533         long callingId = Binder.clearCallingIdentity();
5534         try {
5535             UserInfo userInfo = sUserManager.getUserInfo(userId);
5536             return userInfo != null && userInfo.isEnabled();
5537         } finally {
5538             Binder.restoreCallingIdentity(callingId);
5539         }
5540     }
5541
5542     /**
5543      * Filter out activities with systemUserOnly flag set, when current user is not System.
5544      *
5545      * @return filtered list
5546      */
5547     private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5548         if (userId == UserHandle.USER_SYSTEM) {
5549             return resolveInfos;
5550         }
5551         for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5552             ResolveInfo info = resolveInfos.get(i);
5553             if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5554                 resolveInfos.remove(i);
5555             }
5556         }
5557         return resolveInfos;
5558     }
5559
5560     /**
5561      * @param resolveInfos list of resolve infos in descending priority order
5562      * @return if the list contains a resolve info with non-negative priority
5563      */
5564     private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5565         return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5566     }
5567
5568     private static boolean hasWebURI(Intent intent) {
5569         if (intent.getData() == null) {
5570             return false;
5571         }
5572         final String scheme = intent.getScheme();
5573         if (TextUtils.isEmpty(scheme)) {
5574             return false;
5575         }
5576         return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5577     }
5578
5579     private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5580             int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5581             int userId) {
5582         final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5583
5584         if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5585             Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5586                     candidates.size());
5587         }
5588
5589         ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5590         ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5591         ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5592         ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5593         ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5594         ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5595
5596         synchronized (mPackages) {
5597             final int count = candidates.size();
5598             // First, try to use linked apps. Partition the candidates into four lists:
5599             // one for the final results, one for the "do not use ever", one for "undefined status"
5600             // and finally one for "browser app type".
5601             for (int n=0; n<count; n++) {
5602                 ResolveInfo info = candidates.get(n);
5603                 String packageName = info.activityInfo.packageName;
5604                 PackageSetting ps = mSettings.mPackages.get(packageName);
5605                 if (ps != null) {
5606                     // Add to the special match all list (Browser use case)
5607                     if (info.handleAllWebDataURI) {
5608                         matchAllList.add(info);
5609                         continue;
5610                     }
5611                     // Try to get the status from User settings first
5612                     long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5613                     int status = (int)(packedStatus >> 32);
5614                     int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5615                     if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5616                         if (DEBUG_DOMAIN_VERIFICATION) {
5617                             Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5618                                     + " : linkgen=" + linkGeneration);
5619                         }
5620                         // Use link-enabled generation as preferredOrder, i.e.
5621                         // prefer newly-enabled over earlier-enabled.
5622                         info.preferredOrder = linkGeneration;
5623                         alwaysList.add(info);
5624                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5625                         if (DEBUG_DOMAIN_VERIFICATION) {
5626                             Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5627                         }
5628                         neverList.add(info);
5629                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5630                         if (DEBUG_DOMAIN_VERIFICATION) {
5631                             Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5632                         }
5633                         alwaysAskList.add(info);
5634                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5635                             status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5636                         if (DEBUG_DOMAIN_VERIFICATION) {
5637                             Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5638                         }
5639                         undefinedList.add(info);
5640                     }
5641                 }
5642             }
5643
5644             // We'll want to include browser possibilities in a few cases
5645             boolean includeBrowser = false;
5646
5647             // First try to add the "always" resolution(s) for the current user, if any
5648             if (alwaysList.size() > 0) {
5649                 result.addAll(alwaysList);
5650             } else {
5651                 // Add all undefined apps as we want them to appear in the disambiguation dialog.
5652                 result.addAll(undefinedList);
5653                 // Maybe add one for the other profile.
5654                 if (xpDomainInfo != null && (
5655                         xpDomainInfo.bestDomainVerificationStatus
5656                         != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5657                     result.add(xpDomainInfo.resolveInfo);
5658                 }
5659                 includeBrowser = true;
5660             }
5661
5662             // The presence of any 'always ask' alternatives means we'll also offer browsers.
5663             // If there were 'always' entries their preferred order has been set, so we also
5664             // back that off to make the alternatives equivalent
5665             if (alwaysAskList.size() > 0) {
5666                 for (ResolveInfo i : result) {
5667                     i.preferredOrder = 0;
5668                 }
5669                 result.addAll(alwaysAskList);
5670                 includeBrowser = true;
5671             }
5672
5673             if (includeBrowser) {
5674                 // Also add browsers (all of them or only the default one)
5675                 if (DEBUG_DOMAIN_VERIFICATION) {
5676                     Slog.v(TAG, "   ...including browsers in candidate set");
5677                 }
5678                 if ((matchFlags & MATCH_ALL) != 0) {
5679                     result.addAll(matchAllList);
5680                 } else {
5681                     // Browser/generic handling case.  If there's a default browser, go straight
5682                     // to that (but only if there is no other higher-priority match).
5683                     final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5684                     int maxMatchPrio = 0;
5685                     ResolveInfo defaultBrowserMatch = null;
5686                     final int numCandidates = matchAllList.size();
5687                     for (int n = 0; n < numCandidates; n++) {
5688                         ResolveInfo info = matchAllList.get(n);
5689                         // track the highest overall match priority...
5690                         if (info.priority > maxMatchPrio) {
5691                             maxMatchPrio = info.priority;
5692                         }
5693                         // ...and the highest-priority default browser match
5694                         if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5695                             if (defaultBrowserMatch == null
5696                                     || (defaultBrowserMatch.priority < info.priority)) {
5697                                 if (debug) {
5698                                     Slog.v(TAG, "Considering default browser match " + info);
5699                                 }
5700                                 defaultBrowserMatch = info;
5701                             }
5702                         }
5703                     }
5704                     if (defaultBrowserMatch != null
5705                             && defaultBrowserMatch.priority >= maxMatchPrio
5706                             && !TextUtils.isEmpty(defaultBrowserPackageName))
5707                     {
5708                         if (debug) {
5709                             Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5710                         }
5711                         result.add(defaultBrowserMatch);
5712                     } else {
5713                         result.addAll(matchAllList);
5714                     }
5715                 }
5716
5717                 // If there is nothing selected, add all candidates and remove the ones that the user
5718                 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5719                 if (result.size() == 0) {
5720                     result.addAll(candidates);
5721                     result.removeAll(neverList);
5722                 }
5723             }
5724         }
5725         if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5726             Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5727                     result.size());
5728             for (ResolveInfo info : result) {
5729                 Slog.v(TAG, "  + " + info.activityInfo);
5730             }
5731         }
5732         return result;
5733     }
5734
5735     // Returns a packed value as a long:
5736     //
5737     // high 'int'-sized word: link status: undefined/ask/never/always.
5738     // low 'int'-sized word: relative priority among 'always' results.
5739     private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5740         long result = ps.getDomainVerificationStatusForUser(userId);
5741         // if none available, get the master status
5742         if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5743             if (ps.getIntentFilterVerificationInfo() != null) {
5744                 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5745             }
5746         }
5747         return result;
5748     }
5749
5750     private ResolveInfo querySkipCurrentProfileIntents(
5751             List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5752             int flags, int sourceUserId) {
5753         if (matchingFilters != null) {
5754             int size = matchingFilters.size();
5755             for (int i = 0; i < size; i ++) {
5756                 CrossProfileIntentFilter filter = matchingFilters.get(i);
5757                 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5758                     // Checking if there are activities in the target user that can handle the
5759                     // intent.
5760                     ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5761                             resolvedType, flags, sourceUserId);
5762                     if (resolveInfo != null) {
5763                         return resolveInfo;
5764                     }
5765                 }
5766             }
5767         }
5768         return null;
5769     }
5770
5771     // Return matching ResolveInfo in target user if any.
5772     private ResolveInfo queryCrossProfileIntents(
5773             List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5774             int flags, int sourceUserId, boolean matchInCurrentProfile) {
5775         if (matchingFilters != null) {
5776             // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5777             // match the same intent. For performance reasons, it is better not to
5778             // run queryIntent twice for the same userId
5779             SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5780             int size = matchingFilters.size();
5781             for (int i = 0; i < size; i++) {
5782                 CrossProfileIntentFilter filter = matchingFilters.get(i);
5783                 int targetUserId = filter.getTargetUserId();
5784                 boolean skipCurrentProfile =
5785                         (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5786                 boolean skipCurrentProfileIfNoMatchFound =
5787                         (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5788                 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5789                         && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5790                     // Checking if there are activities in the target user that can handle the
5791                     // intent.
5792                     ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5793                             resolvedType, flags, sourceUserId);
5794                     if (resolveInfo != null) return resolveInfo;
5795                     alreadyTriedUserIds.put(targetUserId, true);
5796                 }
5797             }
5798         }
5799         return null;
5800     }
5801
5802     /**
5803      * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5804      * will forward the intent to the filter's target user.
5805      * Otherwise, returns null.
5806      */
5807     private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5808             String resolvedType, int flags, int sourceUserId) {
5809         int targetUserId = filter.getTargetUserId();
5810         List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5811                 resolvedType, flags, targetUserId);
5812         if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5813             // If all the matches in the target profile are suspended, return null.
5814             for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5815                 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5816                         & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5817                     return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5818                             targetUserId);
5819                 }
5820             }
5821         }
5822         return null;
5823     }
5824
5825     private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5826             int sourceUserId, int targetUserId) {
5827         ResolveInfo forwardingResolveInfo = new ResolveInfo();
5828         long ident = Binder.clearCallingIdentity();
5829         boolean targetIsProfile;
5830         try {
5831             targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5832         } finally {
5833             Binder.restoreCallingIdentity(ident);
5834         }
5835         String className;
5836         if (targetIsProfile) {
5837             className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5838         } else {
5839             className = FORWARD_INTENT_TO_PARENT;
5840         }
5841         ComponentName forwardingActivityComponentName = new ComponentName(
5842                 mAndroidApplication.packageName, className);
5843         ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5844                 sourceUserId);
5845         if (!targetIsProfile) {
5846             forwardingActivityInfo.showUserIcon = targetUserId;
5847             forwardingResolveInfo.noResourceId = true;
5848         }
5849         forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5850         forwardingResolveInfo.priority = 0;
5851         forwardingResolveInfo.preferredOrder = 0;
5852         forwardingResolveInfo.match = 0;
5853         forwardingResolveInfo.isDefault = true;
5854         forwardingResolveInfo.filter = filter;
5855         forwardingResolveInfo.targetUserId = targetUserId;
5856         return forwardingResolveInfo;
5857     }
5858
5859     @Override
5860     public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5861             Intent[] specifics, String[] specificTypes, Intent intent,
5862             String resolvedType, int flags, int userId) {
5863         return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5864                 specificTypes, intent, resolvedType, flags, userId));
5865     }
5866
5867     private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5868             Intent[] specifics, String[] specificTypes, Intent intent,
5869             String resolvedType, int flags, int userId) {
5870         if (!sUserManager.exists(userId)) return Collections.emptyList();
5871         flags = updateFlagsForResolve(flags, userId, intent);
5872         enforceCrossUserPermission(Binder.getCallingUid(), userId,
5873                 false /* requireFullPermission */, false /* checkShell */,
5874                 "query intent activity options");
5875         final String resultsAction = intent.getAction();
5876
5877         final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5878                 | PackageManager.GET_RESOLVED_FILTER, userId);
5879
5880         if (DEBUG_INTENT_MATCHING) {
5881             Log.v(TAG, "Query " + intent + ": " + results);
5882         }
5883
5884         int specificsPos = 0;
5885         int N;
5886
5887         // todo: note that the algorithm used here is O(N^2).  This
5888         // isn't a problem in our current environment, but if we start running
5889         // into situations where we have more than 5 or 10 matches then this
5890         // should probably be changed to something smarter...
5891
5892         // First we go through and resolve each of the specific items
5893         // that were supplied, taking care of removing any corresponding
5894         // duplicate items in the generic resolve list.
5895         if (specifics != null) {
5896             for (int i=0; i<specifics.length; i++) {
5897                 final Intent sintent = specifics[i];
5898                 if (sintent == null) {
5899                     continue;
5900                 }
5901
5902                 if (DEBUG_INTENT_MATCHING) {
5903                     Log.v(TAG, "Specific #" + i + ": " + sintent);
5904                 }
5905
5906                 String action = sintent.getAction();
5907                 if (resultsAction != null && resultsAction.equals(action)) {
5908                     // If this action was explicitly requested, then don't
5909                     // remove things that have it.
5910                     action = null;
5911                 }
5912
5913                 ResolveInfo ri = null;
5914                 ActivityInfo ai = null;
5915
5916                 ComponentName comp = sintent.getComponent();
5917                 if (comp == null) {
5918                     ri = resolveIntent(
5919                         sintent,
5920                         specificTypes != null ? specificTypes[i] : null,
5921                             flags, userId);
5922                     if (ri == null) {
5923                         continue;
5924                     }
5925                     if (ri == mResolveInfo) {
5926                         // ACK!  Must do something better with this.
5927                     }
5928                     ai = ri.activityInfo;
5929                     comp = new ComponentName(ai.applicationInfo.packageName,
5930                             ai.name);
5931                 } else {
5932                     ai = getActivityInfo(comp, flags, userId);
5933                     if (ai == null) {
5934                         continue;
5935                     }
5936                 }
5937
5938                 // Look for any generic query activities that are duplicates
5939                 // of this specific one, and remove them from the results.
5940                 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5941                 N = results.size();
5942                 int j;
5943                 for (j=specificsPos; j<N; j++) {
5944                     ResolveInfo sri = results.get(j);
5945                     if ((sri.activityInfo.name.equals(comp.getClassName())
5946                             && sri.activityInfo.applicationInfo.packageName.equals(
5947                                     comp.getPackageName()))
5948                         || (action != null && sri.filter.matchAction(action))) {
5949                         results.remove(j);
5950                         if (DEBUG_INTENT_MATCHING) Log.v(
5951                             TAG, "Removing duplicate item from " + j
5952                             + " due to specific " + specificsPos);
5953                         if (ri == null) {
5954                             ri = sri;
5955                         }
5956                         j--;
5957                         N--;
5958                     }
5959                 }
5960
5961                 // Add this specific item to its proper place.
5962                 if (ri == null) {
5963                     ri = new ResolveInfo();
5964                     ri.activityInfo = ai;
5965                 }
5966                 results.add(specificsPos, ri);
5967                 ri.specificIndex = i;
5968                 specificsPos++;
5969             }
5970         }
5971
5972         // Now we go through the remaining generic results and remove any
5973         // duplicate actions that are found here.
5974         N = results.size();
5975         for (int i=specificsPos; i<N-1; i++) {
5976             final ResolveInfo rii = results.get(i);
5977             if (rii.filter == null) {
5978                 continue;
5979             }
5980
5981             // Iterate over all of the actions of this result's intent
5982             // filter...  typically this should be just one.
5983             final Iterator<String> it = rii.filter.actionsIterator();
5984             if (it == null) {
5985                 continue;
5986             }
5987             while (it.hasNext()) {
5988                 final String action = it.next();
5989                 if (resultsAction != null && resultsAction.equals(action)) {
5990                     // If this action was explicitly requested, then don't
5991                     // remove things that have it.
5992                     continue;
5993                 }
5994                 for (int j=i+1; j<N; j++) {
5995                     final ResolveInfo rij = results.get(j);
5996                     if (rij.filter != null && rij.filter.hasAction(action)) {
5997                         results.remove(j);
5998                         if (DEBUG_INTENT_MATCHING) Log.v(
5999                             TAG, "Removing duplicate item from " + j
6000                             + " due to action " + action + " at " + i);
6001                         j--;
6002                         N--;
6003                     }
6004                 }
6005             }
6006
6007             // If the caller didn't request filter information, drop it now
6008             // so we don't have to marshall/unmarshall it.
6009             if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6010                 rii.filter = null;
6011             }
6012         }
6013
6014         // Filter out the caller activity if so requested.
6015         if (caller != null) {
6016             N = results.size();
6017             for (int i=0; i<N; i++) {
6018                 ActivityInfo ainfo = results.get(i).activityInfo;
6019                 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6020                         && caller.getClassName().equals(ainfo.name)) {
6021                     results.remove(i);
6022                     break;
6023                 }
6024             }
6025         }
6026
6027         // If the caller didn't request filter information,
6028         // drop them now so we don't have to
6029         // marshall/unmarshall it.
6030         if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6031             N = results.size();
6032             for (int i=0; i<N; i++) {
6033                 results.get(i).filter = null;
6034             }
6035         }
6036
6037         if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6038         return results;
6039     }
6040
6041     @Override
6042     public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6043             String resolvedType, int flags, int userId) {
6044         return new ParceledListSlice<>(
6045                 queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6046     }
6047
6048     private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6049             String resolvedType, int flags, int userId) {
6050         if (!sUserManager.exists(userId)) return Collections.emptyList();
6051         flags = updateFlagsForResolve(flags, userId, intent);
6052         ComponentName comp = intent.getComponent();
6053         if (comp == null) {
6054             if (intent.getSelector() != null) {
6055                 intent = intent.getSelector();
6056                 comp = intent.getComponent();
6057             }
6058         }
6059         if (comp != null) {
6060             List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6061             ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6062             if (ai != null) {
6063                 ResolveInfo ri = new ResolveInfo();
6064                 ri.activityInfo = ai;
6065                 list.add(ri);
6066             }
6067             return list;
6068         }
6069
6070         // reader
6071         synchronized (mPackages) {
6072             String pkgName = intent.getPackage();
6073             if (pkgName == null) {
6074                 return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6075             }
6076             final PackageParser.Package pkg = mPackages.get(pkgName);
6077             if (pkg != null) {
6078                 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6079                         userId);
6080             }
6081             return Collections.emptyList();
6082         }
6083     }
6084
6085     @Override
6086     public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6087         if (!sUserManager.exists(userId)) return null;
6088         flags = updateFlagsForResolve(flags, userId, intent);
6089         List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6090         if (query != null) {
6091             if (query.size() >= 1) {
6092                 // If there is more than one service with the same priority,
6093                 // just arbitrarily pick the first one.
6094                 return query.get(0);
6095             }
6096         }
6097         return null;
6098     }
6099
6100     @Override
6101     public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6102             String resolvedType, int flags, int userId) {
6103         return new ParceledListSlice<>(
6104                 queryIntentServicesInternal(intent, resolvedType, flags, userId));
6105     }
6106
6107     private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6108             String resolvedType, int flags, int userId) {
6109         if (!sUserManager.exists(userId)) return Collections.emptyList();
6110         flags = updateFlagsForResolve(flags, userId, intent);
6111         ComponentName comp = intent.getComponent();
6112         if (comp == null) {
6113             if (intent.getSelector() != null) {
6114                 intent = intent.getSelector();
6115                 comp = intent.getComponent();
6116             }
6117         }
6118         if (comp != null) {
6119             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6120             final ServiceInfo si = getServiceInfo(comp, flags, userId);
6121             if (si != null) {
6122                 final ResolveInfo ri = new ResolveInfo();
6123                 ri.serviceInfo = si;
6124                 list.add(ri);
6125             }
6126             return list;
6127         }
6128
6129         // reader
6130         synchronized (mPackages) {
6131             String pkgName = intent.getPackage();
6132             if (pkgName == null) {
6133                 return mServices.queryIntent(intent, resolvedType, flags, userId);
6134             }
6135             final PackageParser.Package pkg = mPackages.get(pkgName);
6136             if (pkg != null) {
6137                 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6138                         userId);
6139             }
6140             return Collections.emptyList();
6141         }
6142     }
6143
6144     @Override
6145     public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6146             String resolvedType, int flags, int userId) {
6147         return new ParceledListSlice<>(
6148                 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6149     }
6150
6151     private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6152             Intent intent, String resolvedType, int flags, int userId) {
6153         if (!sUserManager.exists(userId)) return Collections.emptyList();
6154         flags = updateFlagsForResolve(flags, userId, intent);
6155         ComponentName comp = intent.getComponent();
6156         if (comp == null) {
6157             if (intent.getSelector() != null) {
6158                 intent = intent.getSelector();
6159                 comp = intent.getComponent();
6160             }
6161         }
6162         if (comp != null) {
6163             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6164             final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6165             if (pi != null) {
6166                 final ResolveInfo ri = new ResolveInfo();
6167                 ri.providerInfo = pi;
6168                 list.add(ri);
6169             }
6170             return list;
6171         }
6172
6173         // reader
6174         synchronized (mPackages) {
6175             String pkgName = intent.getPackage();
6176             if (pkgName == null) {
6177                 return mProviders.queryIntent(intent, resolvedType, flags, userId);
6178             }
6179             final PackageParser.Package pkg = mPackages.get(pkgName);
6180             if (pkg != null) {
6181                 return mProviders.queryIntentForPackage(
6182                         intent, resolvedType, flags, pkg.providers, userId);
6183             }
6184             return Collections.emptyList();
6185         }
6186     }
6187
6188     @Override
6189     public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6190         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6191         flags = updateFlagsForPackage(flags, userId, null);
6192         final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6193         enforceCrossUserPermission(Binder.getCallingUid(), userId,
6194                 true /* requireFullPermission */, false /* checkShell */,
6195                 "get installed packages");
6196
6197         // writer
6198         synchronized (mPackages) {
6199             ArrayList<PackageInfo> list;
6200             if (listUninstalled) {
6201                 list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6202                 for (PackageSetting ps : mSettings.mPackages.values()) {
6203                     final PackageInfo pi;
6204                     if (ps.pkg != null) {
6205                         pi = generatePackageInfo(ps, flags, userId);
6206                     } else {
6207                         pi = generatePackageInfo(ps, flags, userId);
6208                     }
6209                     if (pi != null) {
6210                         list.add(pi);
6211                     }
6212                 }
6213             } else {
6214                 list = new ArrayList<PackageInfo>(mPackages.size());
6215                 for (PackageParser.Package p : mPackages.values()) {
6216                     final PackageInfo pi =
6217                             generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6218                     if (pi != null) {
6219                         list.add(pi);
6220                     }
6221                 }
6222             }
6223
6224             return new ParceledListSlice<PackageInfo>(list);
6225         }
6226     }
6227
6228     private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6229             String[] permissions, boolean[] tmp, int flags, int userId) {
6230         int numMatch = 0;
6231         final PermissionsState permissionsState = ps.getPermissionsState();
6232         for (int i=0; i<permissions.length; i++) {
6233             final String permission = permissions[i];
6234             if (permissionsState.hasPermission(permission, userId)) {
6235                 tmp[i] = true;
6236                 numMatch++;
6237             } else {
6238                 tmp[i] = false;
6239             }
6240         }
6241         if (numMatch == 0) {
6242             return;
6243         }
6244         final PackageInfo pi;
6245         if (ps.pkg != null) {
6246             pi = generatePackageInfo(ps, flags, userId);
6247         } else {
6248             pi = generatePackageInfo(ps, flags, userId);
6249         }
6250         // The above might return null in cases of uninstalled apps or install-state
6251         // skew across users/profiles.
6252         if (pi != null) {
6253             if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6254                 if (numMatch == permissions.length) {
6255                     pi.requestedPermissions = permissions;
6256                 } else {
6257                     pi.requestedPermissions = new String[numMatch];
6258                     numMatch = 0;
6259                     for (int i=0; i<permissions.length; i++) {
6260                         if (tmp[i]) {
6261                             pi.requestedPermissions[numMatch] = permissions[i];
6262                             numMatch++;
6263                         }
6264                     }
6265                 }
6266             }
6267             list.add(pi);
6268         }
6269     }
6270
6271     @Override
6272     public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6273             String[] permissions, int flags, int userId) {
6274         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6275         flags = updateFlagsForPackage(flags, userId, permissions);
6276         final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6277
6278         // writer
6279         synchronized (mPackages) {
6280             ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6281             boolean[] tmpBools = new boolean[permissions.length];
6282             if (listUninstalled) {
6283                 for (PackageSetting ps : mSettings.mPackages.values()) {
6284                     addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6285                 }
6286             } else {
6287                 for (PackageParser.Package pkg : mPackages.values()) {
6288                     PackageSetting ps = (PackageSetting)pkg.mExtras;
6289                     if (ps != null) {
6290                         addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6291                                 userId);
6292                     }
6293                 }
6294             }
6295
6296             return new ParceledListSlice<PackageInfo>(list);
6297         }
6298     }
6299
6300     @Override
6301     public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6302         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6303         flags = updateFlagsForApplication(flags, userId, null);
6304         final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6305
6306         // writer
6307         synchronized (mPackages) {
6308             ArrayList<ApplicationInfo> list;
6309             if (listUninstalled) {
6310                 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6311                 for (PackageSetting ps : mSettings.mPackages.values()) {
6312                     ApplicationInfo ai;
6313                     if (ps.pkg != null) {
6314                         ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6315                                 ps.readUserState(userId), userId);
6316                     } else {
6317                         ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6318                     }
6319                     if (ai != null) {
6320                         list.add(ai);
6321                     }
6322                 }
6323             } else {
6324                 list = new ArrayList<ApplicationInfo>(mPackages.size());
6325                 for (PackageParser.Package p : mPackages.values()) {
6326                     if (p.mExtras != null) {
6327                         ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6328                                 ((PackageSetting)p.mExtras).readUserState(userId), userId);
6329                         if (ai != null) {
6330                             list.add(ai);
6331                         }
6332                     }
6333                 }
6334             }
6335
6336             return new ParceledListSlice<ApplicationInfo>(list);
6337         }
6338     }
6339
6340     @Override
6341     public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6342         if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6343             return null;
6344         }
6345
6346         mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6347                 "getEphemeralApplications");
6348         enforceCrossUserPermission(Binder.getCallingUid(), userId,
6349                 true /* requireFullPermission */, false /* checkShell */,
6350                 "getEphemeralApplications");
6351         synchronized (mPackages) {
6352             List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6353                     .getEphemeralApplicationsLPw(userId);
6354             if (ephemeralApps != null) {
6355                 return new ParceledListSlice<>(ephemeralApps);
6356             }
6357         }
6358         return null;
6359     }
6360
6361     @Override
6362     public boolean isEphemeralApplication(String packageName, int userId) {
6363         enforceCrossUserPermission(Binder.getCallingUid(), userId,
6364                 true /* requireFullPermission */, false /* checkShell */,
6365                 "isEphemeral");
6366         if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6367             return false;
6368         }
6369
6370         if (!isCallerSameApp(packageName)) {
6371             return false;
6372         }
6373         synchronized (mPackages) {
6374             PackageParser.Package pkg = mPackages.get(packageName);
6375             if (pkg != null) {
6376                 return pkg.applicationInfo.isEphemeralApp();
6377             }
6378         }
6379         return false;
6380     }
6381
6382     @Override
6383     public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6384         if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6385             return null;
6386         }
6387
6388         enforceCrossUserPermission(Binder.getCallingUid(), userId,
6389                 true /* requireFullPermission */, false /* checkShell */,
6390                 "getCookie");
6391         if (!isCallerSameApp(packageName)) {
6392             return null;
6393         }
6394         synchronized (mPackages) {
6395             return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6396                     packageName, userId);
6397         }
6398     }
6399
6400     @Override
6401     public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6402         if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6403             return true;
6404         }
6405
6406         enforceCrossUserPermission(Binder.getCallingUid(), userId,
6407                 true /* requireFullPermission */, true /* checkShell */,
6408                 "setCookie");
6409         if (!isCallerSameApp(packageName)) {
6410             return false;
6411         }
6412         synchronized (mPackages) {
6413             return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6414                     packageName, cookie, userId);
6415         }
6416     }
6417
6418     @Override
6419     public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6420         if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6421             return null;
6422         }
6423
6424         mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6425                 "getEphemeralApplicationIcon");
6426         enforceCrossUserPermission(Binder.getCallingUid(), userId,
6427                 true /* requireFullPermission */, false /* checkShell */,
6428                 "getEphemeralApplicationIcon");
6429         synchronized (mPackages) {
6430             return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6431                     packageName, userId);
6432         }
6433     }
6434
6435     private boolean isCallerSameApp(String packageName) {
6436         PackageParser.Package pkg = mPackages.get(packageName);
6437         return pkg != null
6438                 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6439     }
6440
6441     @Override
6442     public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6443         return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6444     }
6445
6446     private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6447         final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6448
6449         // reader
6450         synchronized (mPackages) {
6451             final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6452             final int userId = UserHandle.getCallingUserId();
6453             while (i.hasNext()) {
6454                 final PackageParser.Package p = i.next();
6455                 if (p.applicationInfo == null) continue;
6456
6457                 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6458                         && !p.applicationInfo.isDirectBootAware();
6459                 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6460                         && p.applicationInfo.isDirectBootAware();
6461
6462                 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6463                         && (!mSafeMode || isSystemApp(p))
6464                         && (matchesUnaware || matchesAware)) {
6465                     PackageSetting ps = mSettings.mPackages.get(p.packageName);
6466                     if (ps != null) {
6467                         ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6468                                 ps.readUserState(userId), userId);
6469                         if (ai != null) {
6470                             finalList.add(ai);
6471                         }
6472                     }
6473                 }
6474             }
6475         }
6476
6477         return finalList;
6478     }
6479
6480     @Override
6481     public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6482         if (!sUserManager.exists(userId)) return null;
6483         flags = updateFlagsForComponent(flags, userId, name);
6484         // reader
6485         synchronized (mPackages) {
6486             final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6487             PackageSetting ps = provider != null
6488                     ? mSettings.mPackages.get(provider.owner.packageName)
6489                     : null;
6490             return ps != null
6491                     && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6492                     ? PackageParser.generateProviderInfo(provider, flags,
6493                             ps.readUserState(userId), userId)
6494                     : null;
6495         }
6496     }
6497
6498     /**
6499      * @deprecated
6500      */
6501     @Deprecated
6502     public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6503         // reader
6504         synchronized (mPackages) {
6505             final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6506                     .entrySet().iterator();
6507             final int userId = UserHandle.getCallingUserId();
6508             while (i.hasNext()) {
6509                 Map.Entry<String, PackageParser.Provider> entry = i.next();
6510                 PackageParser.Provider p = entry.getValue();
6511                 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6512
6513                 if (ps != null && p.syncable
6514                         && (!mSafeMode || (p.info.applicationInfo.flags
6515                                 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6516                     ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6517                             ps.readUserState(userId), userId);
6518                     if (info != null) {
6519                         outNames.add(entry.getKey());
6520                         outInfo.add(info);
6521                     }
6522                 }
6523             }
6524         }
6525     }
6526
6527     @Override
6528     public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6529             int uid, int flags) {
6530         final int userId = processName != null ? UserHandle.getUserId(uid)
6531                 : UserHandle.getCallingUserId();
6532         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6533         flags = updateFlagsForComponent(flags, userId, processName);
6534
6535         ArrayList<ProviderInfo> finalList = null;
6536         // reader
6537         synchronized (mPackages) {
6538             final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6539             while (i.hasNext()) {
6540                 final PackageParser.Provider p = i.next();
6541                 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6542                 if (ps != null && p.info.authority != null
6543                         && (processName == null
6544                                 || (p.info.processName.equals(processName)
6545                                         && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6546                         && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6547                     if (finalList == null) {
6548                         finalList = new ArrayList<ProviderInfo>(3);
6549                     }
6550                     ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6551                             ps.readUserState(userId), userId);
6552                     if (info != null) {
6553                         finalList.add(info);
6554                     }
6555                 }
6556             }
6557         }
6558
6559         if (finalList != null) {
6560             Collections.sort(finalList, mProviderInitOrderSorter);
6561             return new ParceledListSlice<ProviderInfo>(finalList);
6562         }
6563
6564         return ParceledListSlice.emptyList();
6565     }
6566
6567     @Override
6568     public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6569         // reader
6570         synchronized (mPackages) {
6571             final PackageParser.Instrumentation i = mInstrumentation.get(name);
6572             return PackageParser.generateInstrumentationInfo(i, flags);
6573         }
6574     }
6575
6576     @Override
6577     public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6578             String targetPackage, int flags) {
6579         return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6580     }
6581
6582     private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6583             int flags) {
6584         ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6585
6586         // reader
6587         synchronized (mPackages) {
6588             final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6589             while (i.hasNext()) {
6590                 final PackageParser.Instrumentation p = i.next();
6591                 if (targetPackage == null
6592                         || targetPackage.equals(p.info.targetPackage)) {
6593                     InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6594                             flags);
6595                     if (ii != null) {
6596                         finalList.add(ii);
6597                     }
6598                 }
6599             }
6600         }
6601
6602         return finalList;
6603     }
6604
6605     private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6606         ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6607         if (overlays == null) {
6608             Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6609             return;
6610         }
6611         for (PackageParser.Package opkg : overlays.values()) {
6612             // Not much to do if idmap fails: we already logged the error
6613             // and we certainly don't want to abort installation of pkg simply
6614             // because an overlay didn't fit properly. For these reasons,
6615             // ignore the return value of createIdmapForPackagePairLI.
6616             createIdmapForPackagePairLI(pkg, opkg);
6617         }
6618     }
6619
6620     private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6621             PackageParser.Package opkg) {
6622         if (!opkg.mTrustedOverlay) {
6623             Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6624                     opkg.baseCodePath + ": overlay not trusted");
6625             return false;
6626         }
6627         ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6628         if (overlaySet == null) {
6629             Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6630                     opkg.baseCodePath + " but target package has no known overlays");
6631             return false;
6632         }
6633         final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6634         // TODO: generate idmap for split APKs
6635         try {
6636             mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6637         } catch (InstallerException e) {
6638             Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6639                     + opkg.baseCodePath);
6640             return false;
6641         }
6642         PackageParser.Package[] overlayArray =
6643             overlaySet.values().toArray(new PackageParser.Package[0]);
6644         Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6645             public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6646                 return p1.mOverlayPriority - p2.mOverlayPriority;
6647             }
6648         };
6649         Arrays.sort(overlayArray, cmp);
6650
6651         pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6652         int i = 0;
6653         for (PackageParser.Package p : overlayArray) {
6654             pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6655         }
6656         return true;
6657     }
6658
6659     private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6660         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6661         try {
6662             scanDirLI(dir, parseFlags, scanFlags, currentTime);
6663         } finally {
6664             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6665         }
6666     }
6667
6668     private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6669         final File[] files = dir.listFiles();
6670         if (ArrayUtils.isEmpty(files)) {
6671             Log.d(TAG, "No files in app dir " + dir);
6672             return;
6673         }
6674
6675         if (DEBUG_PACKAGE_SCANNING) {
6676             Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6677                     + " flags=0x" + Integer.toHexString(parseFlags));
6678         }
6679
6680         for (File file : files) {
6681             final boolean isPackage = (isApkFile(file) || file.isDirectory())
6682                     && !PackageInstallerService.isStageName(file.getName());
6683             if (!isPackage) {
6684                 // Ignore entries which are not packages
6685                 continue;
6686             }
6687             try {
6688                 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6689                         scanFlags, currentTime, null);
6690             } catch (PackageManagerException e) {
6691                 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6692
6693                 // Delete invalid userdata apps
6694                 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6695                         e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6696                     logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6697                     removeCodePathLI(file);
6698                 }
6699             }
6700         }
6701     }
6702
6703     private static File getSettingsProblemFile() {
6704         File dataDir = Environment.getDataDirectory();
6705         File systemDir = new File(dataDir, "system");
6706         File fname = new File(systemDir, "uiderrors.txt");
6707         return fname;
6708     }
6709
6710     static void reportSettingsProblem(int priority, String msg) {
6711         logCriticalInfo(priority, msg);
6712     }
6713
6714     static void logCriticalInfo(int priority, String msg) {
6715         Slog.println(priority, TAG, msg);
6716         EventLogTags.writePmCriticalInfo(msg);
6717         try {
6718             File fname = getSettingsProblemFile();
6719             FileOutputStream out = new FileOutputStream(fname, true);
6720             PrintWriter pw = new FastPrintWriter(out);
6721             SimpleDateFormat formatter = new SimpleDateFormat();
6722             String dateString = formatter.format(new Date(System.currentTimeMillis()));
6723             pw.println(dateString + ": " + msg);
6724             pw.close();
6725             FileUtils.setPermissions(
6726                     fname.toString(),
6727                     FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6728                     -1, -1);
6729         } catch (java.io.IOException e) {
6730         }
6731     }
6732
6733     private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6734         if (srcFile.isDirectory()) {
6735             final File baseFile = new File(pkg.baseCodePath);
6736             long maxModifiedTime = baseFile.lastModified();
6737             if (pkg.splitCodePaths != null) {
6738                 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6739                     final File splitFile = new File(pkg.splitCodePaths[i]);
6740                     maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6741                 }
6742             }
6743             return maxModifiedTime;
6744         }
6745         return srcFile.lastModified();
6746     }
6747
6748     private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6749             final int policyFlags) throws PackageManagerException {
6750         // When upgrading from pre-N MR1, verify the package time stamp using the package
6751         // directory and not the APK file.
6752         final long lastModifiedTime = mIsPreNMR1Upgrade
6753                 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6754         if (ps != null
6755                 && ps.codePath.equals(srcFile)
6756                 && ps.timeStamp == lastModifiedTime
6757                 && !isCompatSignatureUpdateNeeded(pkg)
6758                 && !isRecoverSignatureUpdateNeeded(pkg)) {
6759             long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6760             KeySetManagerService ksms = mSettings.mKeySetManagerService;
6761             ArraySet<PublicKey> signingKs;
6762             synchronized (mPackages) {
6763                 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6764             }
6765             if (ps.signatures.mSignatures != null
6766                     && ps.signatures.mSignatures.length != 0
6767                     && signingKs != null) {
6768                 // Optimization: reuse the existing cached certificates
6769                 // if the package appears to be unchanged.
6770                 pkg.mSignatures = ps.signatures.mSignatures;
6771                 pkg.mSigningKeys = signingKs;
6772                 return;
6773             }
6774
6775             Slog.w(TAG, "PackageSetting for " + ps.name
6776                     + " is missing signatures.  Collecting certs again to recover them.");
6777         } else {
6778             Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6779         }
6780
6781         try {
6782             PackageParser.collectCertificates(pkg, policyFlags);
6783         } catch (PackageParserException e) {
6784             throw PackageManagerException.from(e);
6785         }
6786     }
6787
6788     /**
6789      *  Traces a package scan.
6790      *  @see #scanPackageLI(File, int, int, long, UserHandle)
6791      */
6792     private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6793             int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6794         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6795         try {
6796             return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6797         } finally {
6798             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6799         }
6800     }
6801
6802     /**
6803      *  Scans a package and returns the newly parsed package.
6804      *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6805      */
6806     private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6807             long currentTime, UserHandle user) throws PackageManagerException {
6808         if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6809         PackageParser pp = new PackageParser();
6810         pp.setSeparateProcesses(mSeparateProcesses);
6811         pp.setOnlyCoreApps(mOnlyCore);
6812         pp.setDisplayMetrics(mMetrics);
6813
6814         if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6815             parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6816         }
6817
6818         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6819         final PackageParser.Package pkg;
6820         try {
6821             pkg = pp.parsePackage(scanFile, parseFlags);
6822         } catch (PackageParserException e) {
6823             throw PackageManagerException.from(e);
6824         } finally {
6825             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6826         }
6827
6828         return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6829     }
6830
6831     /**
6832      *  Scans a package and returns the newly parsed package.
6833      *  @throws PackageManagerException on a parse error.
6834      */
6835     private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6836             final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6837             throws PackageManagerException {
6838         // If the package has children and this is the first dive in the function
6839         // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6840         // packages (parent and children) would be successfully scanned before the
6841         // actual scan since scanning mutates internal state and we want to atomically
6842         // install the package and its children.
6843         if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6844             if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6845                 scanFlags |= SCAN_CHECK_ONLY;
6846             }
6847         } else {
6848             scanFlags &= ~SCAN_CHECK_ONLY;
6849         }
6850
6851         // Scan the parent
6852         PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6853                 scanFlags, currentTime, user);
6854
6855         // Scan the children
6856         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6857         for (int i = 0; i < childCount; i++) {
6858             PackageParser.Package childPackage = pkg.childPackages.get(i);
6859             scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6860                     currentTime, user);
6861         }
6862
6863
6864         if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6865             return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6866         }
6867
6868         return scannedPkg;
6869     }
6870
6871     /**
6872      *  Scans a package and returns the newly parsed package.
6873      *  @throws PackageManagerException on a parse error.
6874      */
6875     private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6876             int policyFlags, int scanFlags, long currentTime, UserHandle user)
6877             throws PackageManagerException {
6878         PackageSetting ps = null;
6879         PackageSetting updatedPkg;
6880         // reader
6881         synchronized (mPackages) {
6882             // Look to see if we already know about this package.
6883             String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6884             if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6885                 // This package has been renamed to its original name.  Let's
6886                 // use that.
6887                 ps = mSettings.peekPackageLPr(oldName);
6888             }
6889             // If there was no original package, see one for the real package name.
6890             if (ps == null) {
6891                 ps = mSettings.peekPackageLPr(pkg.packageName);
6892             }
6893             // Check to see if this package could be hiding/updating a system
6894             // package.  Must look for it either under the original or real
6895             // package name depending on our state.
6896             updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6897             if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6898
6899             // If this is a package we don't know about on the system partition, we
6900             // may need to remove disabled child packages on the system partition
6901             // or may need to not add child packages if the parent apk is updated
6902             // on the data partition and no longer defines this child package.
6903             if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6904                 // If this is a parent package for an updated system app and this system
6905                 // app got an OTA update which no longer defines some of the child packages
6906                 // we have to prune them from the disabled system packages.
6907                 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6908                 if (disabledPs != null) {
6909                     final int scannedChildCount = (pkg.childPackages != null)
6910                             ? pkg.childPackages.size() : 0;
6911                     final int disabledChildCount = disabledPs.childPackageNames != null
6912                             ? disabledPs.childPackageNames.size() : 0;
6913                     for (int i = 0; i < disabledChildCount; i++) {
6914                         String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6915                         boolean disabledPackageAvailable = false;
6916                         for (int j = 0; j < scannedChildCount; j++) {
6917                             PackageParser.Package childPkg = pkg.childPackages.get(j);
6918                             if (childPkg.packageName.equals(disabledChildPackageName)) {
6919                                 disabledPackageAvailable = true;
6920                                 break;
6921                             }
6922                          }
6923                          if (!disabledPackageAvailable) {
6924                              mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6925                          }
6926                     }
6927                 }
6928             }
6929         }
6930
6931         boolean updatedPkgBetter = false;
6932         // First check if this is a system package that may involve an update
6933         if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6934             // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6935             // it needs to drop FLAG_PRIVILEGED.
6936             if (locationIsPrivileged(scanFile)) {
6937                 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6938             } else {
6939                 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6940             }
6941
6942             if (ps != null && !ps.codePath.equals(scanFile)) {
6943                 // The path has changed from what was last scanned...  check the
6944                 // version of the new path against what we have stored to determine
6945                 // what to do.
6946                 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6947                 if (pkg.mVersionCode <= ps.versionCode) {
6948                     // The system package has been updated and the code path does not match
6949                     // Ignore entry. Skip it.
6950                     if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6951                             + " ignored: updated version " + ps.versionCode
6952                             + " better than this " + pkg.mVersionCode);
6953                     if (!updatedPkg.codePath.equals(scanFile)) {
6954                         Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6955                                 + ps.name + " changing from " + updatedPkg.codePathString
6956                                 + " to " + scanFile);
6957                         updatedPkg.codePath = scanFile;
6958                         updatedPkg.codePathString = scanFile.toString();
6959                         updatedPkg.resourcePath = scanFile;
6960                         updatedPkg.resourcePathString = scanFile.toString();
6961                     }
6962                     updatedPkg.pkg = pkg;
6963                     updatedPkg.versionCode = pkg.mVersionCode;
6964
6965                     // Update the disabled system child packages to point to the package too.
6966                     final int childCount = updatedPkg.childPackageNames != null
6967                             ? updatedPkg.childPackageNames.size() : 0;
6968                     for (int i = 0; i < childCount; i++) {
6969                         String childPackageName = updatedPkg.childPackageNames.get(i);
6970                         PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6971                                 childPackageName);
6972                         if (updatedChildPkg != null) {
6973                             updatedChildPkg.pkg = pkg;
6974                             updatedChildPkg.versionCode = pkg.mVersionCode;
6975                         }
6976                     }
6977
6978                     throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6979                             + scanFile + " ignored: updated version " + ps.versionCode
6980                             + " better than this " + pkg.mVersionCode);
6981                 } else {
6982                     // The current app on the system partition is better than
6983                     // what we have updated to on the data partition; switch
6984                     // back to the system partition version.
6985                     // At this point, its safely assumed that package installation for
6986                     // apps in system partition will go through. If not there won't be a working
6987                     // version of the app
6988                     // writer
6989                     synchronized (mPackages) {
6990                         // Just remove the loaded entries from package lists.
6991                         mPackages.remove(ps.name);
6992                     }
6993
6994                     logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6995                             + " reverting from " + ps.codePathString
6996                             + ": new version " + pkg.mVersionCode
6997                             + " better than installed " + ps.versionCode);
6998
6999                     InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7000                             ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7001                     synchronized (mInstallLock) {
7002                         args.cleanUpResourcesLI();
7003                     }
7004                     synchronized (mPackages) {
7005                         mSettings.enableSystemPackageLPw(ps.name);
7006                     }
7007                     updatedPkgBetter = true;
7008                 }
7009             }
7010         }
7011
7012         if (updatedPkg != null) {
7013             // An updated system app will not have the PARSE_IS_SYSTEM flag set
7014             // initially
7015             policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7016
7017             // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7018             // flag set initially
7019             if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7020                 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7021             }
7022         }
7023
7024         // Verify certificates against what was last scanned
7025         collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7026
7027         /*
7028          * A new system app appeared, but we already had a non-system one of the
7029          * same name installed earlier.
7030          */
7031         boolean shouldHideSystemApp = false;
7032         if (updatedPkg == null && ps != null
7033                 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7034             /*
7035              * Check to make sure the signatures match first. If they don't,
7036              * wipe the installed application and its data.
7037              */
7038             if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7039                     != PackageManager.SIGNATURE_MATCH) {
7040                 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7041                         + " signatures don't match existing userdata copy; removing");
7042                 try (PackageFreezer freezer = freezePackage(pkg.packageName,
7043                         "scanPackageInternalLI")) {
7044                     deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7045                 }
7046                 ps = null;
7047             } else {
7048                 /*
7049                  * If the newly-added system app is an older version than the
7050                  * already installed version, hide it. It will be scanned later
7051                  * and re-added like an update.
7052                  */
7053                 if (pkg.mVersionCode <= ps.versionCode) {
7054                     shouldHideSystemApp = true;
7055                     logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7056                             + " but new version " + pkg.mVersionCode + " better than installed "
7057                             + ps.versionCode + "; hiding system");
7058                 } else {
7059                     /*
7060                      * The newly found system app is a newer version that the
7061                      * one previously installed. Simply remove the
7062                      * already-installed application and replace it with our own
7063                      * while keeping the application data.
7064                      */
7065                     logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7066                             + " reverting from " + ps.codePathString + ": new version "
7067                             + pkg.mVersionCode + " better than installed " + ps.versionCode);
7068                     InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7069                             ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7070                     synchronized (mInstallLock) {
7071                         args.cleanUpResourcesLI();
7072                     }
7073                 }
7074             }
7075         }
7076
7077         // The apk is forward locked (not public) if its code and resources
7078         // are kept in different files. (except for app in either system or
7079         // vendor path).
7080         // TODO grab this value from PackageSettings
7081         if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7082             if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7083                 policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7084             }
7085         }
7086
7087         // TODO: extend to support forward-locked splits
7088         String resourcePath = null;
7089         String baseResourcePath = null;
7090         if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7091             if (ps != null && ps.resourcePathString != null) {
7092                 resourcePath = ps.resourcePathString;
7093                 baseResourcePath = ps.resourcePathString;
7094             } else {
7095                 // Should not happen at all. Just log an error.
7096                 Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7097             }
7098         } else {
7099             resourcePath = pkg.codePath;
7100             baseResourcePath = pkg.baseCodePath;
7101         }
7102
7103         // Set application objects path explicitly.
7104         pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7105         pkg.setApplicationInfoCodePath(pkg.codePath);
7106         pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7107         pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7108         pkg.setApplicationInfoResourcePath(resourcePath);
7109         pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7110         pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7111
7112         // Note that we invoke the following method only if we are about to unpack an application
7113         PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7114                 | SCAN_UPDATE_SIGNATURE, currentTime, user);
7115
7116         /*
7117          * If the system app should be overridden by a previously installed
7118          * data, hide the system app now and let the /data/app scan pick it up
7119          * again.
7120          */
7121         if (shouldHideSystemApp) {
7122             synchronized (mPackages) {
7123                 mSettings.disableSystemPackageLPw(pkg.packageName, true);
7124             }
7125         }
7126
7127         return scannedPkg;
7128     }
7129
7130     private static String fixProcessName(String defProcessName,
7131             String processName, int uid) {
7132         if (processName == null) {
7133             return defProcessName;
7134         }
7135         return processName;
7136     }
7137
7138     private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7139             throws PackageManagerException {
7140         if (pkgSetting.signatures.mSignatures != null) {
7141             // Already existing package. Make sure signatures match
7142             boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7143                     == PackageManager.SIGNATURE_MATCH;
7144             if (!match) {
7145                 match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7146                         == PackageManager.SIGNATURE_MATCH;
7147             }
7148             if (!match) {
7149                 match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7150                         == PackageManager.SIGNATURE_MATCH;
7151             }
7152             if (!match) {
7153                 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7154                         + pkg.packageName + " signatures do not match the "
7155                         + "previously installed version; ignoring!");
7156             }
7157         }
7158
7159         // Check for shared user signatures
7160         if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7161             // Already existing package. Make sure signatures match
7162             boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7163                     pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7164             if (!match) {
7165                 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7166                         == PackageManager.SIGNATURE_MATCH;
7167             }
7168             if (!match) {
7169                 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7170                         == PackageManager.SIGNATURE_MATCH;
7171             }
7172             if (!match) {
7173                 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7174                         "Package " + pkg.packageName
7175                         + " has no signatures that match those in shared user "
7176                         + pkgSetting.sharedUser.name + "; ignoring!");
7177             }
7178         }
7179     }
7180
7181     /**
7182      * Enforces that only the system UID or root's UID can call a method exposed
7183      * via Binder.
7184      *
7185      * @param message used as message if SecurityException is thrown
7186      * @throws SecurityException if the caller is not system or root
7187      */
7188     private static final void enforceSystemOrRoot(String message) {
7189         final int uid = Binder.getCallingUid();
7190         if (uid != Process.SYSTEM_UID && uid != 0) {
7191             throw new SecurityException(message);
7192         }
7193     }
7194
7195     @Override
7196     public void performFstrimIfNeeded() {
7197         enforceSystemOrRoot("Only the system can request fstrim");
7198
7199         // Before everything else, see whether we need to fstrim.
7200         try {
7201             IMountService ms = PackageHelper.getMountService();
7202             if (ms != null) {
7203                 boolean doTrim = false;
7204                 final long interval = android.provider.Settings.Global.getLong(
7205                         mContext.getContentResolver(),
7206                         android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7207                         DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7208                 if (interval > 0) {
7209                     final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7210                     if (timeSinceLast > interval) {
7211                         doTrim = true;
7212                         Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7213                                 + "; running immediately");
7214                     }
7215                 }
7216                 if (doTrim) {
7217                     final boolean dexOptDialogShown;
7218                     synchronized (mPackages) {
7219                         dexOptDialogShown = mDexOptDialogShown;
7220                     }
7221                     if (!isFirstBoot() && dexOptDialogShown) {
7222                         try {
7223                             ActivityManagerNative.getDefault().showBootMessage(
7224                                     mContext.getResources().getString(
7225                                             R.string.android_upgrading_fstrim), true);
7226                         } catch (RemoteException e) {
7227                         }
7228                     }
7229                     ms.runMaintenance();
7230                 }
7231             } else {
7232                 Slog.e(TAG, "Mount service unavailable!");
7233             }
7234         } catch (RemoteException e) {
7235             // Can't happen; MountService is local
7236         }
7237     }
7238
7239     @Override
7240     public void updatePackagesIfNeeded() {
7241         enforceSystemOrRoot("Only the system can request package update");
7242
7243         // We need to re-extract after an OTA.
7244         boolean causeUpgrade = isUpgrade();
7245
7246         // First boot or factory reset.
7247         // Note: we also handle devices that are upgrading to N right now as if it is their
7248         //       first boot, as they do not have profile data.
7249         boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7250
7251         // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7252         boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7253
7254         if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7255             return;
7256         }
7257
7258         List<PackageParser.Package> pkgs;
7259         synchronized (mPackages) {
7260             pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7261         }
7262
7263         final long startTime = System.nanoTime();
7264         final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7265                     getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7266
7267         final int elapsedTimeSeconds =
7268                 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7269
7270         MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7271         MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7272         MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7273         MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7274         MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7275     }
7276
7277     /**
7278      * Performs dexopt on the set of packages in {@code packages} and returns an int array
7279      * containing statistics about the invocation. The array consists of three elements,
7280      * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7281      * and {@code numberOfPackagesFailed}.
7282      */
7283     private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7284             String compilerFilter) {
7285
7286         int numberOfPackagesVisited = 0;
7287         int numberOfPackagesOptimized = 0;
7288         int numberOfPackagesSkipped = 0;
7289         int numberOfPackagesFailed = 0;
7290         final int numberOfPackagesToDexopt = pkgs.size();
7291
7292         for (PackageParser.Package pkg : pkgs) {
7293             numberOfPackagesVisited++;
7294
7295             if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7296                 if (DEBUG_DEXOPT) {
7297                     Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7298                 }
7299                 numberOfPackagesSkipped++;
7300                 continue;
7301             }
7302
7303             if (DEBUG_DEXOPT) {
7304                 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7305                         numberOfPackagesToDexopt + ": " + pkg.packageName);
7306             }
7307
7308             if (showDialog) {
7309                 try {
7310                     ActivityManagerNative.getDefault().showBootMessage(
7311                             mContext.getResources().getString(R.string.android_upgrading_apk,
7312                                     numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7313                 } catch (RemoteException e) {
7314                 }
7315                 synchronized (mPackages) {
7316                     mDexOptDialogShown = true;
7317                 }
7318             }
7319
7320             // If the OTA updates a system app which was previously preopted to a non-preopted state
7321             // the app might end up being verified at runtime. That's because by default the apps
7322             // are verify-profile but for preopted apps there's no profile.
7323             // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7324             // that before the OTA the app was preopted) the app gets compiled with a non-profile
7325             // filter (by default interpret-only).
7326             // Note that at this stage unused apps are already filtered.
7327             if (isSystemApp(pkg) &&
7328                     DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7329                     !Environment.getReferenceProfile(pkg.packageName).exists()) {
7330                 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7331             }
7332
7333             // checkProfiles is false to avoid merging profiles during boot which
7334             // might interfere with background compilation (b/28612421).
7335             // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7336             // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7337             // trade-off worth doing to save boot time work.
7338             int dexOptStatus = performDexOptTraced(pkg.packageName,
7339                     false /* checkProfiles */,
7340                     compilerFilter,
7341                     false /* force */);
7342             switch (dexOptStatus) {
7343                 case PackageDexOptimizer.DEX_OPT_PERFORMED:
7344                     numberOfPackagesOptimized++;
7345                     break;
7346                 case PackageDexOptimizer.DEX_OPT_SKIPPED:
7347                     numberOfPackagesSkipped++;
7348                     break;
7349                 case PackageDexOptimizer.DEX_OPT_FAILED:
7350                     numberOfPackagesFailed++;
7351                     break;
7352                 default:
7353                     Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7354                     break;
7355             }
7356         }
7357
7358         return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7359                 numberOfPackagesFailed };
7360     }
7361
7362     @Override
7363     public void notifyPackageUse(String packageName, int reason) {
7364         synchronized (mPackages) {
7365             PackageParser.Package p = mPackages.get(packageName);
7366             if (p == null) {
7367                 return;
7368             }
7369             p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7370         }
7371     }
7372
7373     // TODO: this is not used nor needed. Delete it.
7374     @Override
7375     public boolean performDexOptIfNeeded(String packageName) {
7376         int dexOptStatus = performDexOptTraced(packageName,
7377                 false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7378         return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7379     }
7380
7381     @Override
7382     public boolean performDexOpt(String packageName,
7383             boolean checkProfiles, int compileReason, boolean force) {
7384         int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7385                 getCompilerFilterForReason(compileReason), force);
7386         return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7387     }
7388
7389     @Override
7390     public boolean performDexOptMode(String packageName,
7391             boolean checkProfiles, String targetCompilerFilter, boolean force) {
7392         int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7393                 targetCompilerFilter, force);
7394         return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7395     }
7396
7397     private int performDexOptTraced(String packageName,
7398                 boolean checkProfiles, String targetCompilerFilter, boolean force) {
7399         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7400         try {
7401             return performDexOptInternal(packageName, checkProfiles,
7402                     targetCompilerFilter, force);
7403         } finally {
7404             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7405         }
7406     }
7407
7408     // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7409     // if the package can now be considered up to date for the given filter.
7410     private int performDexOptInternal(String packageName,
7411                 boolean checkProfiles, String targetCompilerFilter, boolean force) {
7412         PackageParser.Package p;
7413         synchronized (mPackages) {
7414             p = mPackages.get(packageName);
7415             if (p == null) {
7416                 // Package could not be found. Report failure.
7417                 return PackageDexOptimizer.DEX_OPT_FAILED;
7418             }
7419             mPackageUsage.maybeWriteAsync(mPackages);
7420             mCompilerStats.maybeWriteAsync();
7421         }
7422         long callingId = Binder.clearCallingIdentity();
7423         try {
7424             synchronized (mInstallLock) {
7425                 return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7426                         targetCompilerFilter, force);
7427             }
7428         } finally {
7429             Binder.restoreCallingIdentity(callingId);
7430         }
7431     }
7432
7433     public ArraySet<String> getOptimizablePackages() {
7434         ArraySet<String> pkgs = new ArraySet<String>();
7435         synchronized (mPackages) {
7436             for (PackageParser.Package p : mPackages.values()) {
7437                 if (PackageDexOptimizer.canOptimizePackage(p)) {
7438                     pkgs.add(p.packageName);
7439                 }
7440             }
7441         }
7442         return pkgs;
7443     }
7444
7445     private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7446             boolean checkProfiles, String targetCompilerFilter,
7447             boolean force) {
7448         // Select the dex optimizer based on the force parameter.
7449         // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7450         //       allocate an object here.
7451         PackageDexOptimizer pdo = force
7452                 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7453                 : mPackageDexOptimizer;
7454
7455         // Optimize all dependencies first. Note: we ignore the return value and march on
7456         // on errors.
7457         Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7458         final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7459         if (!deps.isEmpty()) {
7460             for (PackageParser.Package depPackage : deps) {
7461                 // TODO: Analyze and investigate if we (should) profile libraries.
7462                 // Currently this will do a full compilation of the library by default.
7463                 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7464                         false /* checkProfiles */,
7465                         getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7466                         getOrCreateCompilerPackageStats(depPackage));
7467             }
7468         }
7469         return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7470                 targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7471     }
7472
7473     Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7474         if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7475             ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7476             Set<String> collectedNames = new HashSet<>();
7477             findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7478
7479             retValue.remove(p);
7480
7481             return retValue;
7482         } else {
7483             return Collections.emptyList();
7484         }
7485     }
7486
7487     private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7488             Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7489         if (!collectedNames.contains(p.packageName)) {
7490             collectedNames.add(p.packageName);
7491             collected.add(p);
7492
7493             if (p.usesLibraries != null) {
7494                 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7495             }
7496             if (p.usesOptionalLibraries != null) {
7497                 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7498                         collectedNames);
7499             }
7500         }
7501     }
7502
7503     private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7504             Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7505         for (String libName : libs) {
7506             PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7507             if (libPkg != null) {
7508                 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7509             }
7510         }
7511     }
7512
7513     private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7514         synchronized (mPackages) {
7515             PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7516             if (lib != null && lib.apk != null) {
7517                 return mPackages.get(lib.apk);
7518             }
7519         }
7520         return null;
7521     }
7522
7523     public void shutdown() {
7524         mPackageUsage.writeNow(mPackages);
7525         mCompilerStats.writeNow();
7526     }
7527
7528     @Override
7529     public void dumpProfiles(String packageName) {
7530         PackageParser.Package pkg;
7531         synchronized (mPackages) {
7532             pkg = mPackages.get(packageName);
7533             if (pkg == null) {
7534                 throw new IllegalArgumentException("Unknown package: " + packageName);
7535             }
7536         }
7537         /* Only the shell, root, or the app user should be able to dump profiles. */
7538         int callingUid = Binder.getCallingUid();
7539         if (callingUid != Process.SHELL_UID &&
7540             callingUid != Process.ROOT_UID &&
7541             callingUid != pkg.applicationInfo.uid) {
7542             throw new SecurityException("dumpProfiles");
7543         }
7544
7545         synchronized (mInstallLock) {
7546             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7547             final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7548             try {
7549                 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7550                 String gid = Integer.toString(sharedGid);
7551                 String codePaths = TextUtils.join(";", allCodePaths);
7552                 mInstaller.dumpProfiles(gid, packageName, codePaths);
7553             } catch (InstallerException e) {
7554                 Slog.w(TAG, "Failed to dump profiles", e);
7555             }
7556             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7557         }
7558     }
7559
7560     @Override
7561     public void forceDexOpt(String packageName) {
7562         enforceSystemOrRoot("forceDexOpt");
7563
7564         PackageParser.Package pkg;
7565         synchronized (mPackages) {
7566             pkg = mPackages.get(packageName);
7567             if (pkg == null) {
7568                 throw new IllegalArgumentException("Unknown package: " + packageName);
7569             }
7570         }
7571
7572         synchronized (mInstallLock) {
7573             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7574
7575             // Whoever is calling forceDexOpt wants a fully compiled package.
7576             // Don't use profiles since that may cause compilation to be skipped.
7577             final int res = performDexOptInternalWithDependenciesLI(pkg,
7578                     false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7579                     true /* force */);
7580
7581             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7582             if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7583                 throw new IllegalStateException("Failed to dexopt: " + res);
7584             }
7585         }
7586     }
7587
7588     private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7589         if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7590             Slog.w(TAG, "Unable to update from " + oldPkg.name
7591                     + " to " + newPkg.packageName
7592                     + ": old package not in system partition");
7593             return false;
7594         } else if (mPackages.get(oldPkg.name) != null) {
7595             Slog.w(TAG, "Unable to update from " + oldPkg.name
7596                     + " to " + newPkg.packageName
7597                     + ": old package still exists");
7598             return false;
7599         }
7600         return true;
7601     }
7602
7603     void removeCodePathLI(File codePath) {
7604         if (codePath.isDirectory()) {
7605             try {
7606                 mInstaller.rmPackageDir(codePath.getAbsolutePath());
7607             } catch (InstallerException e) {
7608                 Slog.w(TAG, "Failed to remove code path", e);
7609             }
7610         } else {
7611             codePath.delete();
7612         }
7613     }
7614
7615     private int[] resolveUserIds(int userId) {
7616         return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7617     }
7618
7619     private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7620         if (pkg == null) {
7621             Slog.wtf(TAG, "Package was null!", new Throwable());
7622             return;
7623         }
7624         clearAppDataLeafLIF(pkg, userId, flags);
7625         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7626         for (int i = 0; i < childCount; i++) {
7627             clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7628         }
7629     }
7630
7631     private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7632         final PackageSetting ps;
7633         synchronized (mPackages) {
7634             ps = mSettings.mPackages.get(pkg.packageName);
7635         }
7636         for (int realUserId : resolveUserIds(userId)) {
7637             final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7638             try {
7639                 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7640                         ceDataInode);
7641             } catch (InstallerException e) {
7642                 Slog.w(TAG, String.valueOf(e));
7643             }
7644         }
7645     }
7646
7647     private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7648         if (pkg == null) {
7649             Slog.wtf(TAG, "Package was null!", new Throwable());
7650             return;
7651         }
7652         destroyAppDataLeafLIF(pkg, userId, flags);
7653         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7654         for (int i = 0; i < childCount; i++) {
7655             destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7656         }
7657     }
7658
7659     private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7660         final PackageSetting ps;
7661         synchronized (mPackages) {
7662             ps = mSettings.mPackages.get(pkg.packageName);
7663         }
7664         for (int realUserId : resolveUserIds(userId)) {
7665             final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7666             try {
7667                 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7668                         ceDataInode);
7669             } catch (InstallerException e) {
7670                 Slog.w(TAG, String.valueOf(e));
7671             }
7672         }
7673     }
7674
7675     private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7676         if (pkg == null) {
7677             Slog.wtf(TAG, "Package was null!", new Throwable());
7678             return;
7679         }
7680         destroyAppProfilesLeafLIF(pkg);
7681         destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7682         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7683         for (int i = 0; i < childCount; i++) {
7684             destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7685             destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7686                     true /* removeBaseMarker */);
7687         }
7688     }
7689
7690     private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7691             boolean removeBaseMarker) {
7692         if (pkg.isForwardLocked()) {
7693             return;
7694         }
7695
7696         for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7697             try {
7698                 path = PackageManagerServiceUtils.realpath(new File(path));
7699             } catch (IOException e) {
7700                 // TODO: Should we return early here ?
7701                 Slog.w(TAG, "Failed to get canonical path", e);
7702                 continue;
7703             }
7704
7705             final String useMarker = path.replace('/', '@');
7706             for (int realUserId : resolveUserIds(userId)) {
7707                 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7708                 if (removeBaseMarker) {
7709                     File foreignUseMark = new File(profileDir, useMarker);
7710                     if (foreignUseMark.exists()) {
7711                         if (!foreignUseMark.delete()) {
7712                             Slog.w(TAG, "Unable to delete foreign user mark for package: "
7713                                     + pkg.packageName);
7714                         }
7715                     }
7716                 }
7717
7718                 File[] markers = profileDir.listFiles();
7719                 if (markers != null) {
7720                     final String searchString = "@" + pkg.packageName + "@";
7721                     // We also delete all markers that contain the package name we're
7722                     // uninstalling. These are associated with secondary dex-files belonging
7723                     // to the package. Reconstructing the path of these dex files is messy
7724                     // in general.
7725                     for (File marker : markers) {
7726                         if (marker.getName().indexOf(searchString) > 0) {
7727                             if (!marker.delete()) {
7728                                 Slog.w(TAG, "Unable to delete foreign user mark for package: "
7729                                     + pkg.packageName);
7730                             }
7731                         }
7732                     }
7733                 }
7734             }
7735         }
7736     }
7737
7738     private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7739         try {
7740             mInstaller.destroyAppProfiles(pkg.packageName);
7741         } catch (InstallerException e) {
7742             Slog.w(TAG, String.valueOf(e));
7743         }
7744     }
7745
7746     private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7747         if (pkg == null) {
7748             Slog.wtf(TAG, "Package was null!", new Throwable());
7749             return;
7750         }
7751         clearAppProfilesLeafLIF(pkg);
7752         // We don't remove the base foreign use marker when clearing profiles because
7753         // we will rename it when the app is updated. Unlike the actual profile contents,
7754         // the foreign use marker is good across installs.
7755         destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7756         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7757         for (int i = 0; i < childCount; i++) {
7758             clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7759         }
7760     }
7761
7762     private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7763         try {
7764             mInstaller.clearAppProfiles(pkg.packageName);
7765         } catch (InstallerException e) {
7766             Slog.w(TAG, String.valueOf(e));
7767         }
7768     }
7769
7770     private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7771             long lastUpdateTime) {
7772         // Set parent install/update time
7773         PackageSetting ps = (PackageSetting) pkg.mExtras;
7774         if (ps != null) {
7775             ps.firstInstallTime = firstInstallTime;
7776             ps.lastUpdateTime = lastUpdateTime;
7777         }
7778         // Set children install/update time
7779         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7780         for (int i = 0; i < childCount; i++) {
7781             PackageParser.Package childPkg = pkg.childPackages.get(i);
7782             ps = (PackageSetting) childPkg.mExtras;
7783             if (ps != null) {
7784                 ps.firstInstallTime = firstInstallTime;
7785                 ps.lastUpdateTime = lastUpdateTime;
7786             }
7787         }
7788     }
7789
7790     private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7791             PackageParser.Package changingLib) {
7792         if (file.path != null) {
7793             usesLibraryFiles.add(file.path);
7794             return;
7795         }
7796         PackageParser.Package p = mPackages.get(file.apk);
7797         if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7798             // If we are doing this while in the middle of updating a library apk,
7799             // then we need to make sure to use that new apk for determining the
7800             // dependencies here.  (We haven't yet finished committing the new apk
7801             // to the package manager state.)
7802             if (p == null || p.packageName.equals(changingLib.packageName)) {
7803                 p = changingLib;
7804             }
7805         }
7806         if (p != null) {
7807             usesLibraryFiles.addAll(p.getAllCodePaths());
7808         }
7809     }
7810
7811     private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7812             PackageParser.Package changingLib) throws PackageManagerException {
7813         if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7814             final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7815             int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7816             for (int i=0; i<N; i++) {
7817                 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7818                 if (file == null) {
7819                     throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7820                             "Package " + pkg.packageName + " requires unavailable shared library "
7821                             + pkg.usesLibraries.get(i) + "; failing!");
7822                 }
7823                 addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7824             }
7825             N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7826             for (int i=0; i<N; i++) {
7827                 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7828                 if (file == null) {
7829                     Slog.w(TAG, "Package " + pkg.packageName
7830                             + " desires unavailable shared library "
7831                             + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7832                 } else {
7833                     addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7834                 }
7835             }
7836             N = usesLibraryFiles.size();
7837             if (N > 0) {
7838                 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7839             } else {
7840                 pkg.usesLibraryFiles = null;
7841             }
7842         }
7843     }
7844
7845     private static boolean hasString(List<String> list, List<String> which) {
7846         if (list == null) {
7847             return false;
7848         }
7849         for (int i=list.size()-1; i>=0; i--) {
7850             for (int j=which.size()-1; j>=0; j--) {
7851                 if (which.get(j).equals(list.get(i))) {
7852                     return true;
7853                 }
7854             }
7855         }
7856         return false;
7857     }
7858
7859     private void updateAllSharedLibrariesLPw() {
7860         for (PackageParser.Package pkg : mPackages.values()) {
7861             try {
7862                 updateSharedLibrariesLPw(pkg, null);
7863             } catch (PackageManagerException e) {
7864                 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7865             }
7866         }
7867     }
7868
7869     private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7870             PackageParser.Package changingPkg) {
7871         ArrayList<PackageParser.Package> res = null;
7872         for (PackageParser.Package pkg : mPackages.values()) {
7873             if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7874                     || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7875                 if (res == null) {
7876                     res = new ArrayList<PackageParser.Package>();
7877                 }
7878                 res.add(pkg);
7879                 try {
7880                     updateSharedLibrariesLPw(pkg, changingPkg);
7881                 } catch (PackageManagerException e) {
7882                     Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7883                 }
7884             }
7885         }
7886         return res;
7887     }
7888
7889     /**
7890      * Derive the value of the {@code cpuAbiOverride} based on the provided
7891      * value and an optional stored value from the package settings.
7892      */
7893     private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7894         String cpuAbiOverride = null;
7895
7896         if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7897             cpuAbiOverride = null;
7898         } else if (abiOverride != null) {
7899             cpuAbiOverride = abiOverride;
7900         } else if (settings != null) {
7901             cpuAbiOverride = settings.cpuAbiOverrideString;
7902         }
7903
7904         return cpuAbiOverride;
7905     }
7906
7907     private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7908             final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7909                     throws PackageManagerException {
7910         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7911         // If the package has children and this is the first dive in the function
7912         // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7913         // whether all packages (parent and children) would be successfully scanned
7914         // before the actual scan since scanning mutates internal state and we want
7915         // to atomically install the package and its children.
7916         if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7917             if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7918                 scanFlags |= SCAN_CHECK_ONLY;
7919             }
7920         } else {
7921             scanFlags &= ~SCAN_CHECK_ONLY;
7922         }
7923
7924         final PackageParser.Package scannedPkg;
7925         try {
7926             // Scan the parent
7927             scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7928             // Scan the children
7929             final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7930             for (int i = 0; i < childCount; i++) {
7931                 PackageParser.Package childPkg = pkg.childPackages.get(i);
7932                 scanPackageLI(childPkg, policyFlags,
7933                         scanFlags, currentTime, user);
7934             }
7935         } finally {
7936             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7937         }
7938
7939         if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7940             return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7941         }
7942
7943         return scannedPkg;
7944     }
7945
7946     private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7947             int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7948         boolean success = false;
7949         try {
7950             final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7951                     currentTime, user);
7952             success = true;
7953             return res;
7954         } finally {
7955             if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7956                 // DELETE_DATA_ON_FAILURES is only used by frozen paths
7957                 destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7958                         StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7959                 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7960             }
7961         }
7962     }
7963
7964     /**
7965      * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7966      */
7967     private static boolean apkHasCode(String fileName) {
7968         StrictJarFile jarFile = null;
7969         try {
7970             jarFile = new StrictJarFile(fileName,
7971                     false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7972             return jarFile.findEntry("classes.dex") != null;
7973         } catch (IOException ignore) {
7974         } finally {
7975             try {
7976                 if (jarFile != null) {
7977                     jarFile.close();
7978                 }
7979             } catch (IOException ignore) {}
7980         }
7981         return false;
7982     }
7983
7984     /**
7985      * Enforces code policy for the package. This ensures that if an APK has
7986      * declared hasCode="true" in its manifest that the APK actually contains
7987      * code.
7988      *
7989      * @throws PackageManagerException If bytecode could not be found when it should exist
7990      */
7991     private static void enforceCodePolicy(PackageParser.Package pkg)
7992             throws PackageManagerException {
7993         final boolean shouldHaveCode =
7994                 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7995         if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7996             throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7997                     "Package " + pkg.baseCodePath + " code is missing");
7998         }
7999
8000         if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8001             for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8002                 final boolean splitShouldHaveCode =
8003                         (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8004                 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8005                     throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8006                             "Package " + pkg.splitCodePaths[i] + " code is missing");
8007                 }
8008             }
8009         }
8010     }
8011
8012     private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8013             final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8014             throws PackageManagerException {
8015         final File scanFile = new File(pkg.codePath);
8016         if (pkg.applicationInfo.getCodePath() == null ||
8017                 pkg.applicationInfo.getResourcePath() == null) {
8018             // Bail out. The resource and code paths haven't been set.
8019             throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8020                     "Code and resource paths haven't been set correctly");
8021         }
8022
8023         // Apply policy
8024         if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8025             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8026             if (pkg.applicationInfo.isDirectBootAware()) {
8027                 // we're direct boot aware; set for all components
8028                 for (PackageParser.Service s : pkg.services) {
8029                     s.info.encryptionAware = s.info.directBootAware = true;
8030                 }
8031                 for (PackageParser.Provider p : pkg.providers) {
8032                     p.info.encryptionAware = p.info.directBootAware = true;
8033                 }
8034                 for (PackageParser.Activity a : pkg.activities) {
8035                     a.info.encryptionAware = a.info.directBootAware = true;
8036                 }
8037                 for (PackageParser.Activity r : pkg.receivers) {
8038                     r.info.encryptionAware = r.info.directBootAware = true;
8039                 }
8040             }
8041         } else {
8042             // Only allow system apps to be flagged as core apps.
8043             pkg.coreApp = false;
8044             // clear flags not applicable to regular apps
8045             pkg.applicationInfo.privateFlags &=
8046                     ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8047             pkg.applicationInfo.privateFlags &=
8048                     ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8049         }
8050         pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8051
8052         if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8053             pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8054         }
8055
8056         if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8057             enforceCodePolicy(pkg);
8058         }
8059
8060         if (mCustomResolverComponentName != null &&
8061                 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8062             setUpCustomResolverActivity(pkg);
8063         }
8064
8065         if (pkg.packageName.equals("android")) {
8066             synchronized (mPackages) {
8067                 if (mAndroidApplication != null) {
8068                     Slog.w(TAG, "*************************************************");
8069                     Slog.w(TAG, "Core android package being redefined.  Skipping.");
8070                     Slog.w(TAG, " file=" + scanFile);
8071                     Slog.w(TAG, "*************************************************");
8072                     throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8073                             "Core android package being redefined.  Skipping.");
8074                 }
8075
8076                 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8077                     // Set up information for our fall-back user intent resolution activity.
8078                     mPlatformPackage = pkg;
8079                     pkg.mVersionCode = mSdkVersion;
8080                     mAndroidApplication = pkg.applicationInfo;
8081
8082                     if (!mResolverReplaced) {
8083                         mResolveActivity.applicationInfo = mAndroidApplication;
8084                         mResolveActivity.name = ResolverActivity.class.getName();
8085                         mResolveActivity.packageName = mAndroidApplication.packageName;
8086                         mResolveActivity.processName = "system:ui";
8087                         mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8088                         mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8089                         mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8090                         mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8091                         mResolveActivity.exported = true;
8092                         mResolveActivity.enabled = true;
8093                         mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8094                         mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8095                                 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8096                                 | ActivityInfo.CONFIG_SCREEN_LAYOUT
8097                                 | ActivityInfo.CONFIG_ORIENTATION
8098                                 | ActivityInfo.CONFIG_KEYBOARD
8099                                 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8100                         mResolveInfo.activityInfo = mResolveActivity;
8101                         mResolveInfo.priority = 0;
8102                         mResolveInfo.preferredOrder = 0;
8103                         mResolveInfo.match = 0;
8104                         mResolveComponentName = new ComponentName(
8105                                 mAndroidApplication.packageName, mResolveActivity.name);
8106                     }
8107                 }
8108             }
8109         }
8110
8111         if (DEBUG_PACKAGE_SCANNING) {
8112             if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8113                 Log.d(TAG, "Scanning package " + pkg.packageName);
8114         }
8115
8116         synchronized (mPackages) {
8117             if (mPackages.containsKey(pkg.packageName)
8118                     || mSharedLibraries.containsKey(pkg.packageName)) {
8119                 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8120                         "Application package " + pkg.packageName
8121                                 + " already installed.  Skipping duplicate.");
8122             }
8123
8124             // If we're only installing presumed-existing packages, require that the
8125             // scanned APK is both already known and at the path previously established
8126             // for it.  Previously unknown packages we pick up normally, but if we have an
8127             // a priori expectation about this package's install presence, enforce it.
8128             // With a singular exception for new system packages. When an OTA contains
8129             // a new system package, we allow the codepath to change from a system location
8130             // to the user-installed location. If we don't allow this change, any newer,
8131             // user-installed version of the application will be ignored.
8132             if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8133                 if (mExpectingBetter.containsKey(pkg.packageName)) {
8134                     logCriticalInfo(Log.WARN,
8135                             "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8136                 } else {
8137                     PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8138                     if (known != null) {
8139                         if (DEBUG_PACKAGE_SCANNING) {
8140                             Log.d(TAG, "Examining " + pkg.codePath
8141                                     + " and requiring known paths " + known.codePathString
8142                                     + " & " + known.resourcePathString);
8143                         }
8144                         if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8145                                 || !pkg.applicationInfo.getResourcePath().equals(
8146                                 known.resourcePathString)) {
8147                             throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8148                                     "Application package " + pkg.packageName
8149                                             + " found at " + pkg.applicationInfo.getCodePath()
8150                                             + " but expected at " + known.codePathString
8151                                             + "; ignoring.");
8152                         }
8153                     }
8154                 }
8155             }
8156         }
8157
8158         // Initialize package source and resource directories
8159         File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8160         File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8161
8162         SharedUserSetting suid = null;
8163         PackageSetting pkgSetting = null;
8164
8165         if (!isSystemApp(pkg)) {
8166             // Only system apps can use these features.
8167             pkg.mOriginalPackages = null;
8168             pkg.mRealPackage = null;
8169             pkg.mAdoptPermissions = null;
8170         }
8171
8172         // Getting the package setting may have a side-effect, so if we
8173         // are only checking if scan would succeed, stash a copy of the
8174         // old setting to restore at the end.
8175         PackageSetting nonMutatedPs = null;
8176
8177         // writer
8178         synchronized (mPackages) {
8179             if (pkg.mSharedUserId != null) {
8180                 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8181                 if (suid == null) {
8182                     throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8183                             "Creating application package " + pkg.packageName
8184                             + " for shared user failed");
8185                 }
8186                 if (DEBUG_PACKAGE_SCANNING) {
8187                     if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8188                         Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8189                                 + "): packages=" + suid.packages);
8190                 }
8191             }
8192
8193             // Check if we are renaming from an original package name.
8194             PackageSetting origPackage = null;
8195             String realName = null;
8196             if (pkg.mOriginalPackages != null) {
8197                 // This package may need to be renamed to a previously
8198                 // installed name.  Let's check on that...
8199                 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8200                 if (pkg.mOriginalPackages.contains(renamed)) {
8201                     // This package had originally been installed as the
8202                     // original name, and we have already taken care of
8203                     // transitioning to the new one.  Just update the new
8204                     // one to continue using the old name.
8205                     realName = pkg.mRealPackage;
8206                     if (!pkg.packageName.equals(renamed)) {
8207                         // Callers into this function may have already taken
8208                         // care of renaming the package; only do it here if
8209                         // it is not already done.
8210                         pkg.setPackageName(renamed);
8211                     }
8212
8213                 } else {
8214                     for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8215                         if ((origPackage = mSettings.peekPackageLPr(
8216                                 pkg.mOriginalPackages.get(i))) != null) {
8217                             // We do have the package already installed under its
8218                             // original name...  should we use it?
8219                             if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8220                                 // New package is not compatible with original.
8221                                 origPackage = null;
8222                                 continue;
8223                             } else if (origPackage.sharedUser != null) {
8224                                 // Make sure uid is compatible between packages.
8225                                 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8226                                     Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8227                                             + " to " + pkg.packageName + ": old uid "
8228                                             + origPackage.sharedUser.name
8229                                             + " differs from " + pkg.mSharedUserId);
8230                                     origPackage = null;
8231                                     continue;
8232                                 }
8233                                 // TODO: Add case when shared user id is added [b/28144775]
8234                             } else {
8235                                 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8236                                         + pkg.packageName + " to old name " + origPackage.name);
8237                             }
8238                             break;
8239                         }
8240                     }
8241                 }
8242             }
8243
8244             if (mTransferedPackages.contains(pkg.packageName)) {
8245                 Slog.w(TAG, "Package " + pkg.packageName
8246                         + " was transferred to another, but its .apk remains");
8247             }
8248
8249             // See comments in nonMutatedPs declaration
8250             if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8251                 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8252                 if (foundPs != null) {
8253                     nonMutatedPs = new PackageSetting(foundPs);
8254                 }
8255             }
8256
8257             // Just create the setting, don't add it yet. For already existing packages
8258             // the PkgSetting exists already and doesn't have to be created.
8259             pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8260                     destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8261                     pkg.applicationInfo.primaryCpuAbi,
8262                     pkg.applicationInfo.secondaryCpuAbi,
8263                     pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8264                     user, false);
8265             if (pkgSetting == null) {
8266                 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8267                         "Creating application package " + pkg.packageName + " failed");
8268             }
8269
8270             if (pkgSetting.origPackage != null) {
8271                 // If we are first transitioning from an original package,
8272                 // fix up the new package's name now.  We need to do this after
8273                 // looking up the package under its new name, so getPackageLP
8274                 // can take care of fiddling things correctly.
8275                 pkg.setPackageName(origPackage.name);
8276
8277                 // File a report about this.
8278                 String msg = "New package " + pkgSetting.realName
8279                         + " renamed to replace old package " + pkgSetting.name;
8280                 reportSettingsProblem(Log.WARN, msg);
8281
8282                 // Make a note of it.
8283                 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8284                     mTransferedPackages.add(origPackage.name);
8285                 }
8286
8287                 // No longer need to retain this.
8288                 pkgSetting.origPackage = null;
8289             }
8290
8291             if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8292                 // Make a note of it.
8293                 mTransferedPackages.add(pkg.packageName);
8294             }
8295
8296             if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8297                 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8298             }
8299
8300             if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8301                 // Check all shared libraries and map to their actual file path.
8302                 // We only do this here for apps not on a system dir, because those
8303                 // are the only ones that can fail an install due to this.  We
8304                 // will take care of the system apps by updating all of their
8305                 // library paths after the scan is done.
8306                 updateSharedLibrariesLPw(pkg, null);
8307             }
8308
8309             if (mFoundPolicyFile) {
8310                 SELinuxMMAC.assignSeinfoValue(pkg);
8311             }
8312
8313             pkg.applicationInfo.uid = pkgSetting.appId;
8314             pkg.mExtras = pkgSetting;
8315             if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8316                 if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8317                     // We just determined the app is signed correctly, so bring
8318                     // over the latest parsed certs.
8319                     pkgSetting.signatures.mSignatures = pkg.mSignatures;
8320                 } else {
8321                     if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8322                         throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8323                                 "Package " + pkg.packageName + " upgrade keys do not match the "
8324                                 + "previously installed version");
8325                     } else {
8326                         pkgSetting.signatures.mSignatures = pkg.mSignatures;
8327                         String msg = "System package " + pkg.packageName
8328                             + " signature changed; retaining data.";
8329                         reportSettingsProblem(Log.WARN, msg);
8330                     }
8331                 }
8332             } else {
8333                 try {
8334                     verifySignaturesLP(pkgSetting, pkg);
8335                     // We just determined the app is signed correctly, so bring
8336                     // over the latest parsed certs.
8337                     pkgSetting.signatures.mSignatures = pkg.mSignatures;
8338                 } catch (PackageManagerException e) {
8339                     if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8340                         throw e;
8341                     }
8342                     // The signature has changed, but this package is in the system
8343                     // image...  let's recover!
8344                     pkgSetting.signatures.mSignatures = pkg.mSignatures;
8345                     // However...  if this package is part of a shared user, but it
8346                     // doesn't match the signature of the shared user, let's fail.
8347                     // What this means is that you can't change the signatures
8348                     // associated with an overall shared user, which doesn't seem all
8349                     // that unreasonable.
8350                     if (pkgSetting.sharedUser != null) {
8351                         if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8352                                               pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8353                             throw new PackageManagerException(
8354                                     INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8355                                             "Signature mismatch for shared user: "
8356                                             + pkgSetting.sharedUser);
8357                         }
8358                     }
8359                     // File a report about this.
8360                     String msg = "System package " + pkg.packageName
8361                         + " signature changed; retaining data.";
8362                     reportSettingsProblem(Log.WARN, msg);
8363                 }
8364             }
8365             // Verify that this new package doesn't have any content providers
8366             // that conflict with existing packages.  Only do this if the
8367             // package isn't already installed, since we don't want to break
8368             // things that are installed.
8369             if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8370                 final int N = pkg.providers.size();
8371                 int i;
8372                 for (i=0; i<N; i++) {
8373                     PackageParser.Provider p = pkg.providers.get(i);
8374                     if (p.info.authority != null) {
8375                         String names[] = p.info.authority.split(";");
8376                         for (int j = 0; j < names.length; j++) {
8377                             if (mProvidersByAuthority.containsKey(names[j])) {
8378                                 PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8379                                 final String otherPackageName =
8380                                         ((other != null && other.getComponentName() != null) ?
8381                                                 other.getComponentName().getPackageName() : "?");
8382                                 throw new PackageManagerException(
8383                                         INSTALL_FAILED_CONFLICTING_PROVIDER,
8384                                                 "Can't install because provider name " + names[j]
8385                                                 + " (in package " + pkg.applicationInfo.packageName
8386                                                 + ") is already used by " + otherPackageName);
8387                             }
8388                         }
8389                     }
8390                 }
8391             }
8392
8393             if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8394                 // This package wants to adopt ownership of permissions from
8395                 // another package.
8396                 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8397                     final String origName = pkg.mAdoptPermissions.get(i);
8398                     final PackageSetting orig = mSettings.peekPackageLPr(origName);
8399                     if (orig != null) {
8400                         if (verifyPackageUpdateLPr(orig, pkg)) {
8401                             Slog.i(TAG, "Adopting permissions from " + origName + " to "
8402                                     + pkg.packageName);
8403                             mSettings.transferPermissionsLPw(origName, pkg.packageName);
8404                         }
8405                     }
8406                 }
8407             }
8408         }
8409
8410         final String pkgName = pkg.packageName;
8411
8412         final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8413         final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8414         pkg.applicationInfo.processName = fixProcessName(
8415                 pkg.applicationInfo.packageName,
8416                 pkg.applicationInfo.processName,
8417                 pkg.applicationInfo.uid);
8418
8419         if (pkg != mPlatformPackage) {
8420             // Get all of our default paths setup
8421             pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8422         }
8423
8424         final String path = scanFile.getPath();
8425         final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8426
8427         if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8428             derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8429
8430             // Some system apps still use directory structure for native libraries
8431             // in which case we might end up not detecting abi solely based on apk
8432             // structure. Try to detect abi based on directory structure.
8433             if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8434                     pkg.applicationInfo.primaryCpuAbi == null) {
8435                 setBundledAppAbisAndRoots(pkg, pkgSetting);
8436                 setNativeLibraryPaths(pkg);
8437             }
8438
8439         } else {
8440             if ((scanFlags & SCAN_MOVE) != 0) {
8441                 // We haven't run dex-opt for this move (since we've moved the compiled output too)
8442                 // but we already have this packages package info in the PackageSetting. We just
8443                 // use that and derive the native library path based on the new codepath.
8444                 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8445                 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8446             }
8447
8448             // Set native library paths again. For moves, the path will be updated based on the
8449             // ABIs we've determined above. For non-moves, the path will be updated based on the
8450             // ABIs we determined during compilation, but the path will depend on the final
8451             // package path (after the rename away from the stage path).
8452             setNativeLibraryPaths(pkg);
8453         }
8454
8455         // This is a special case for the "system" package, where the ABI is
8456         // dictated by the zygote configuration (and init.rc). We should keep track
8457         // of this ABI so that we can deal with "normal" applications that run under
8458         // the same UID correctly.
8459         if (mPlatformPackage == pkg) {
8460             pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8461                     Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8462         }
8463
8464         // If there's a mismatch between the abi-override in the package setting
8465         // and the abiOverride specified for the install. Warn about this because we
8466         // would've already compiled the app without taking the package setting into
8467         // account.
8468         if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8469             if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8470                 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8471                         " for package " + pkg.packageName);
8472             }
8473         }
8474
8475         pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8476         pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8477         pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8478
8479         // Copy the derived override back to the parsed package, so that we can
8480         // update the package settings accordingly.
8481         pkg.cpuAbiOverride = cpuAbiOverride;
8482
8483         if (DEBUG_ABI_SELECTION) {
8484             Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8485                     + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8486                     + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8487         }
8488
8489         // Push the derived path down into PackageSettings so we know what to
8490         // clean up at uninstall time.
8491         pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8492
8493         if (DEBUG_ABI_SELECTION) {
8494             Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8495                     " primary=" + pkg.applicationInfo.primaryCpuAbi +
8496                     " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8497         }
8498
8499         if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8500             // We don't do this here during boot because we can do it all
8501             // at once after scanning all existing packages.
8502             //
8503             // We also do this *before* we perform dexopt on this package, so that
8504             // we can avoid redundant dexopts, and also to make sure we've got the
8505             // code and package path correct.
8506             adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8507                     pkg, true /* boot complete */);
8508         }
8509
8510         if (mFactoryTest && pkg.requestedPermissions.contains(
8511                 android.Manifest.permission.FACTORY_TEST)) {
8512             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8513         }
8514
8515         if (isSystemApp(pkg)) {
8516             pkgSetting.isOrphaned = true;
8517         }
8518
8519         ArrayList<PackageParser.Package> clientLibPkgs = null;
8520
8521         if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8522             if (nonMutatedPs != null) {
8523                 synchronized (mPackages) {
8524                     mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8525                 }
8526             }
8527             return pkg;
8528         }
8529
8530         // Only privileged apps and updated privileged apps can add child packages.
8531         if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8532             if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8533                 throw new PackageManagerException("Only privileged apps and updated "
8534                         + "privileged apps can add child packages. Ignoring package "
8535                         + pkg.packageName);
8536             }
8537             final int childCount = pkg.childPackages.size();
8538             for (int i = 0; i < childCount; i++) {
8539                 PackageParser.Package childPkg = pkg.childPackages.get(i);
8540                 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8541                         childPkg.packageName)) {
8542                     throw new PackageManagerException("Cannot override a child package of "
8543                             + "another disabled system app. Ignoring package " + pkg.packageName);
8544                 }
8545             }
8546         }
8547
8548         // writer
8549         synchronized (mPackages) {
8550             if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8551                 // Only system apps can add new shared libraries.
8552                 if (pkg.libraryNames != null) {
8553                     for (int i=0; i<pkg.libraryNames.size(); i++) {
8554                         String name = pkg.libraryNames.get(i);
8555                         boolean allowed = false;
8556                         if (pkg.isUpdatedSystemApp()) {
8557                             // New library entries can only be added through the
8558                             // system image.  This is important to get rid of a lot
8559                             // of nasty edge cases: for example if we allowed a non-
8560                             // system update of the app to add a library, then uninstalling
8561                             // the update would make the library go away, and assumptions
8562                             // we made such as through app install filtering would now
8563                             // have allowed apps on the device which aren't compatible
8564                             // with it.  Better to just have the restriction here, be
8565                             // conservative, and create many fewer cases that can negatively
8566                             // impact the user experience.
8567                             final PackageSetting sysPs = mSettings
8568                                     .getDisabledSystemPkgLPr(pkg.packageName);
8569                             if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8570                                 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8571                                     if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8572                                         allowed = true;
8573                                         break;
8574                                     }
8575                                 }
8576                             }
8577                         } else {
8578                             allowed = true;
8579                         }
8580                         if (allowed) {
8581                             if (!mSharedLibraries.containsKey(name)) {
8582                                 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8583                             } else if (!name.equals(pkg.packageName)) {
8584                                 Slog.w(TAG, "Package " + pkg.packageName + " library "
8585                                         + name + " already exists; skipping");
8586                             }
8587                         } else {
8588                             Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8589                                     + name + " that is not declared on system image; skipping");
8590                         }
8591                     }
8592                     if ((scanFlags & SCAN_BOOTING) == 0) {
8593                         // If we are not booting, we need to update any applications
8594                         // that are clients of our shared library.  If we are booting,
8595                         // this will all be done once the scan is complete.
8596                         clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8597                     }
8598                 }
8599             }
8600         }
8601
8602         if ((scanFlags & SCAN_BOOTING) != 0) {
8603             // No apps can run during boot scan, so they don't need to be frozen
8604         } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8605             // Caller asked to not kill app, so it's probably not frozen
8606         } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8607             // Caller asked us to ignore frozen check for some reason; they
8608             // probably didn't know the package name
8609         } else {
8610             // We're doing major surgery on this package, so it better be frozen
8611             // right now to keep it from launching
8612             checkPackageFrozen(pkgName);
8613         }
8614
8615         // Also need to kill any apps that are dependent on the library.
8616         if (clientLibPkgs != null) {
8617             for (int i=0; i<clientLibPkgs.size(); i++) {
8618                 PackageParser.Package clientPkg = clientLibPkgs.get(i);
8619                 killApplication(clientPkg.applicationInfo.packageName,
8620                         clientPkg.applicationInfo.uid, "update lib");
8621             }
8622         }
8623
8624         // Make sure we're not adding any bogus keyset info
8625         KeySetManagerService ksms = mSettings.mKeySetManagerService;
8626         ksms.assertScannedPackageValid(pkg);
8627
8628         // writer
8629         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8630
8631         boolean createIdmapFailed = false;
8632         synchronized (mPackages) {
8633             // We don't expect installation to fail beyond this point
8634
8635             if (pkgSetting.pkg != null) {
8636                 // Note that |user| might be null during the initial boot scan. If a codePath
8637                 // for an app has changed during a boot scan, it's due to an app update that's
8638                 // part of the system partition and marker changes must be applied to all users.
8639                 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8640                     (user != null) ? user : UserHandle.ALL);
8641             }
8642
8643             // Add the new setting to mSettings
8644             mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8645             // Add the new setting to mPackages
8646             mPackages.put(pkg.applicationInfo.packageName, pkg);
8647             // Make sure we don't accidentally delete its data.
8648             final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8649             while (iter.hasNext()) {
8650                 PackageCleanItem item = iter.next();
8651                 if (pkgName.equals(item.packageName)) {
8652                     iter.remove();
8653                 }
8654             }
8655
8656             // Take care of first install / last update times.
8657             if (currentTime != 0) {
8658                 if (pkgSetting.firstInstallTime == 0) {
8659                     pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8660                 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8661                     pkgSetting.lastUpdateTime = currentTime;
8662                 }
8663             } else if (pkgSetting.firstInstallTime == 0) {
8664                 // We need *something*.  Take time time stamp of the file.
8665                 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8666             } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8667                 if (scanFileTime != pkgSetting.timeStamp) {
8668                     // A package on the system image has changed; consider this
8669                     // to be an update.
8670                     pkgSetting.lastUpdateTime = scanFileTime;
8671                 }
8672             }
8673
8674             // Add the package's KeySets to the global KeySetManagerService
8675             ksms.addScannedPackageLPw(pkg);
8676
8677             int N = pkg.providers.size();
8678             StringBuilder r = null;
8679             int i;
8680             for (i=0; i<N; i++) {
8681                 PackageParser.Provider p = pkg.providers.get(i);
8682                 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8683                         p.info.processName, pkg.applicationInfo.uid);
8684                 mProviders.addProvider(p);
8685                 p.syncable = p.info.isSyncable;
8686                 if (p.info.authority != null) {
8687                     String names[] = p.info.authority.split(";");
8688                     p.info.authority = null;
8689                     for (int j = 0; j < names.length; j++) {
8690                         if (j == 1 && p.syncable) {
8691                             // We only want the first authority for a provider to possibly be
8692                             // syncable, so if we already added this provider using a different
8693                             // authority clear the syncable flag. We copy the provider before
8694                             // changing it because the mProviders object contains a reference
8695                             // to a provider that we don't want to change.
8696                             // Only do this for the second authority since the resulting provider
8697                             // object can be the same for all future authorities for this provider.
8698                             p = new PackageParser.Provider(p);
8699                             p.syncable = false;
8700                         }
8701                         if (!mProvidersByAuthority.containsKey(names[j])) {
8702                             mProvidersByAuthority.put(names[j], p);
8703                             if (p.info.authority == null) {
8704                                 p.info.authority = names[j];
8705                             } else {
8706                                 p.info.authority = p.info.authority + ";" + names[j];
8707                             }
8708                             if (DEBUG_PACKAGE_SCANNING) {
8709                                 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8710                                     Log.d(TAG, "Registered content provider: " + names[j]
8711                                             + ", className = " + p.info.name + ", isSyncable = "
8712                                             + p.info.isSyncable);
8713                             }
8714                         } else {
8715                             PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8716                             Slog.w(TAG, "Skipping provider name " + names[j] +
8717                                     " (in package " + pkg.applicationInfo.packageName +
8718                                     "): name already used by "
8719                                     + ((other != null && other.getComponentName() != null)
8720                                             ? other.getComponentName().getPackageName() : "?"));
8721                         }
8722                     }
8723                 }
8724                 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8725                     if (r == null) {
8726                         r = new StringBuilder(256);
8727                     } else {
8728                         r.append(' ');
8729                     }
8730                     r.append(p.info.name);
8731                 }
8732             }
8733             if (r != null) {
8734                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8735             }
8736
8737             N = pkg.services.size();
8738             r = null;
8739             for (i=0; i<N; i++) {
8740                 PackageParser.Service s = pkg.services.get(i);
8741                 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8742                         s.info.processName, pkg.applicationInfo.uid);
8743                 mServices.addService(s);
8744                 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8745                     if (r == null) {
8746                         r = new StringBuilder(256);
8747                     } else {
8748                         r.append(' ');
8749                     }
8750                     r.append(s.info.name);
8751                 }
8752             }
8753             if (r != null) {
8754                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8755             }
8756
8757             N = pkg.receivers.size();
8758             r = null;
8759             for (i=0; i<N; i++) {
8760                 PackageParser.Activity a = pkg.receivers.get(i);
8761                 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8762                         a.info.processName, pkg.applicationInfo.uid);
8763                 mReceivers.addActivity(a, "receiver");
8764                 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8765                     if (r == null) {
8766                         r = new StringBuilder(256);
8767                     } else {
8768                         r.append(' ');
8769                     }
8770                     r.append(a.info.name);
8771                 }
8772             }
8773             if (r != null) {
8774                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8775             }
8776
8777             N = pkg.activities.size();
8778             r = null;
8779             for (i=0; i<N; i++) {
8780                 PackageParser.Activity a = pkg.activities.get(i);
8781                 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8782                         a.info.processName, pkg.applicationInfo.uid);
8783                 mActivities.addActivity(a, "activity");
8784                 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8785                     if (r == null) {
8786                         r = new StringBuilder(256);
8787                     } else {
8788                         r.append(' ');
8789                     }
8790                     r.append(a.info.name);
8791                 }
8792             }
8793             if (r != null) {
8794                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8795             }
8796
8797             N = pkg.permissionGroups.size();
8798             r = null;
8799             for (i=0; i<N; i++) {
8800                 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8801                 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8802                 final String curPackageName = cur == null ? null : cur.info.packageName;
8803                 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8804                 if (cur == null || isPackageUpdate) {
8805                     mPermissionGroups.put(pg.info.name, pg);
8806                     if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8807                         if (r == null) {
8808                             r = new StringBuilder(256);
8809                         } else {
8810                             r.append(' ');
8811                         }
8812                         if (isPackageUpdate) {
8813                             r.append("UPD:");
8814                         }
8815                         r.append(pg.info.name);
8816                     }
8817                 } else {
8818                     Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8819                             + pg.info.packageName + " ignored: original from "
8820                             + cur.info.packageName);
8821                     if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8822                         if (r == null) {
8823                             r = new StringBuilder(256);
8824                         } else {
8825                             r.append(' ');
8826                         }
8827                         r.append("DUP:");
8828                         r.append(pg.info.name);
8829                     }
8830                 }
8831             }
8832             if (r != null) {
8833                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8834             }
8835
8836             N = pkg.permissions.size();
8837             r = null;
8838             for (i=0; i<N; i++) {
8839                 PackageParser.Permission p = pkg.permissions.get(i);
8840
8841                 // Assume by default that we did not install this permission into the system.
8842                 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8843
8844                 // Now that permission groups have a special meaning, we ignore permission
8845                 // groups for legacy apps to prevent unexpected behavior. In particular,
8846                 // permissions for one app being granted to someone just becase they happen
8847                 // to be in a group defined by another app (before this had no implications).
8848                 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8849                     p.group = mPermissionGroups.get(p.info.group);
8850                     // Warn for a permission in an unknown group.
8851                     if (p.info.group != null && p.group == null) {
8852                         Slog.w(TAG, "Permission " + p.info.name + " from package "
8853                                 + p.info.packageName + " in an unknown group " + p.info.group);
8854                     }
8855                 }
8856
8857                 ArrayMap<String, BasePermission> permissionMap =
8858                         p.tree ? mSettings.mPermissionTrees
8859                                 : mSettings.mPermissions;
8860                 BasePermission bp = permissionMap.get(p.info.name);
8861
8862                 // Allow system apps to redefine non-system permissions
8863                 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8864                     final boolean currentOwnerIsSystem = (bp.perm != null
8865                             && isSystemApp(bp.perm.owner));
8866                     if (isSystemApp(p.owner)) {
8867                         if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8868                             // It's a built-in permission and no owner, take ownership now
8869                             bp.packageSetting = pkgSetting;
8870                             bp.perm = p;
8871                             bp.uid = pkg.applicationInfo.uid;
8872                             bp.sourcePackage = p.info.packageName;
8873                             p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8874                         } else if (!currentOwnerIsSystem) {
8875                             String msg = "New decl " + p.owner + " of permission  "
8876                                     + p.info.name + " is system; overriding " + bp.sourcePackage;
8877                             reportSettingsProblem(Log.WARN, msg);
8878                             bp = null;
8879                         }
8880                     }
8881                 }
8882
8883                 if (bp == null) {
8884                     bp = new BasePermission(p.info.name, p.info.packageName,
8885                             BasePermission.TYPE_NORMAL);
8886                     permissionMap.put(p.info.name, bp);
8887                 }
8888
8889                 if (bp.perm == null) {
8890                     if (bp.sourcePackage == null
8891                             || bp.sourcePackage.equals(p.info.packageName)) {
8892                         BasePermission tree = findPermissionTreeLP(p.info.name);
8893                         if (tree == null
8894                                 || tree.sourcePackage.equals(p.info.packageName)) {
8895                             bp.packageSetting = pkgSetting;
8896                             bp.perm = p;
8897                             bp.uid = pkg.applicationInfo.uid;
8898                             bp.sourcePackage = p.info.packageName;
8899                             p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8900                             if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8901                                 if (r == null) {
8902                                     r = new StringBuilder(256);
8903                                 } else {
8904                                     r.append(' ');
8905                                 }
8906                                 r.append(p.info.name);
8907                             }
8908                         } else {
8909                             Slog.w(TAG, "Permission " + p.info.name + " from package "
8910                                     + p.info.packageName + " ignored: base tree "
8911                                     + tree.name + " is from package "
8912                                     + tree.sourcePackage);
8913                         }
8914                     } else {
8915                         Slog.w(TAG, "Permission " + p.info.name + " from package "
8916                                 + p.info.packageName + " ignored: original from "
8917                                 + bp.sourcePackage);
8918                     }
8919                 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8920                     if (r == null) {
8921                         r = new StringBuilder(256);
8922                     } else {
8923                         r.append(' ');
8924                     }
8925                     r.append("DUP:");
8926                     r.append(p.info.name);
8927                 }
8928                 if (bp.perm == p) {
8929                     bp.protectionLevel = p.info.protectionLevel;
8930                 }
8931             }
8932
8933             if (r != null) {
8934                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8935             }
8936
8937             N = pkg.instrumentation.size();
8938             r = null;
8939             for (i=0; i<N; i++) {
8940                 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8941                 a.info.packageName = pkg.applicationInfo.packageName;
8942                 a.info.sourceDir = pkg.applicationInfo.sourceDir;
8943                 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8944                 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8945                 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8946                 a.info.dataDir = pkg.applicationInfo.dataDir;
8947                 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8948                 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8949
8950                 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8951                 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8952                 mInstrumentation.put(a.getComponentName(), a);
8953                 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8954                     if (r == null) {
8955                         r = new StringBuilder(256);
8956                     } else {
8957                         r.append(' ');
8958                     }
8959                     r.append(a.info.name);
8960                 }
8961             }
8962             if (r != null) {
8963                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8964             }
8965
8966             if (pkg.protectedBroadcasts != null) {
8967                 N = pkg.protectedBroadcasts.size();
8968                 for (i=0; i<N; i++) {
8969                     mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8970                 }
8971             }
8972
8973             pkgSetting.setTimeStamp(scanFileTime);
8974
8975             // Create idmap files for pairs of (packages, overlay packages).
8976             // Note: "android", ie framework-res.apk, is handled by native layers.
8977             if (pkg.mOverlayTarget != null) {
8978                 // This is an overlay package.
8979                 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8980                     if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8981                         mOverlays.put(pkg.mOverlayTarget,
8982                                 new ArrayMap<String, PackageParser.Package>());
8983                     }
8984                     ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8985                     map.put(pkg.packageName, pkg);
8986                     PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8987                     if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8988                         createIdmapFailed = true;
8989                     }
8990                 }
8991             } else if (mOverlays.containsKey(pkg.packageName) &&
8992                     !pkg.packageName.equals("android")) {
8993                 // This is a regular package, with one or more known overlay packages.
8994                 createIdmapsForPackageLI(pkg);
8995             }
8996         }
8997
8998         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8999
9000         if (createIdmapFailed) {
9001             throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9002                     "scanPackageLI failed to createIdmap");
9003         }
9004         return pkg;
9005     }
9006
9007     private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9008             PackageParser.Package update, UserHandle user) {
9009         if (existing.applicationInfo == null || update.applicationInfo == null) {
9010             // This isn't due to an app installation.
9011             return;
9012         }
9013
9014         final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9015         final File newCodePath = new File(update.applicationInfo.getCodePath());
9016
9017         // The codePath hasn't changed, so there's nothing for us to do.
9018         if (Objects.equals(oldCodePath, newCodePath)) {
9019             return;
9020         }
9021
9022         File canonicalNewCodePath;
9023         try {
9024             canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9025         } catch (IOException e) {
9026             Slog.w(TAG, "Failed to get canonical path.", e);
9027             return;
9028         }
9029
9030         // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9031         // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9032         // that the last component of the path (i.e, the name) doesn't need canonicalization
9033         // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9034         // but may change in the future. Hopefully this function won't exist at that point.
9035         final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9036                 oldCodePath.getName());
9037
9038         // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9039         // with "@".
9040         String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9041         if (!oldMarkerPrefix.endsWith("@")) {
9042             oldMarkerPrefix += "@";
9043         }
9044         String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9045         if (!newMarkerPrefix.endsWith("@")) {
9046             newMarkerPrefix += "@";
9047         }
9048
9049         List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9050         List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9051         for (String updatedPath : updatedPaths) {
9052             String updatedPathName = new File(updatedPath).getName();
9053             markerSuffixes.add(updatedPathName.replace('/', '@'));
9054         }
9055
9056         for (int userId : resolveUserIds(user.getIdentifier())) {
9057             File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9058
9059             for (String markerSuffix : markerSuffixes) {
9060                 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9061                 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9062                 if (oldForeignUseMark.exists()) {
9063                     try {
9064                         Os.rename(oldForeignUseMark.getAbsolutePath(),
9065                                 newForeignUseMark.getAbsolutePath());
9066                     } catch (ErrnoException e) {
9067                         Slog.w(TAG, "Failed to rename foreign use marker", e);
9068                         oldForeignUseMark.delete();
9069                     }
9070                 }
9071             }
9072         }
9073     }
9074
9075     /**
9076      * Derive the ABI of a non-system package located at {@code scanFile}. This information
9077      * is derived purely on the basis of the contents of {@code scanFile} and
9078      * {@code cpuAbiOverride}.
9079      *
9080      * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9081      */
9082     private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9083                                  String cpuAbiOverride, boolean extractLibs)
9084             throws PackageManagerException {
9085         // TODO: We can probably be smarter about this stuff. For installed apps,
9086         // we can calculate this information at install time once and for all. For
9087         // system apps, we can probably assume that this information doesn't change
9088         // after the first boot scan. As things stand, we do lots of unnecessary work.
9089
9090         // Give ourselves some initial paths; we'll come back for another
9091         // pass once we've determined ABI below.
9092         setNativeLibraryPaths(pkg);
9093
9094         // We would never need to extract libs for forward-locked and external packages,
9095         // since the container service will do it for us. We shouldn't attempt to
9096         // extract libs from system app when it was not updated.
9097         if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9098                 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9099             extractLibs = false;
9100         }
9101
9102         final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9103         final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9104
9105         NativeLibraryHelper.Handle handle = null;
9106         try {
9107             handle = NativeLibraryHelper.Handle.create(pkg);
9108             // TODO(multiArch): This can be null for apps that didn't go through the
9109             // usual installation process. We can calculate it again, like we
9110             // do during install time.
9111             //
9112             // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9113             // unnecessary.
9114             final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9115
9116             // Null out the abis so that they can be recalculated.
9117             pkg.applicationInfo.primaryCpuAbi = null;
9118             pkg.applicationInfo.secondaryCpuAbi = null;
9119             if (isMultiArch(pkg.applicationInfo)) {
9120                 // Warn if we've set an abiOverride for multi-lib packages..
9121                 // By definition, we need to copy both 32 and 64 bit libraries for
9122                 // such packages.
9123                 if (pkg.cpuAbiOverride != null
9124                         && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9125                     Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9126                 }
9127
9128                 int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9129                 int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9130                 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9131                     if (extractLibs) {
9132                         abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9133                                 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9134                                 useIsaSpecificSubdirs);
9135                     } else {
9136                         abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9137                     }
9138                 }
9139
9140                 maybeThrowExceptionForMultiArchCopy(
9141                         "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9142
9143                 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9144                     if (extractLibs) {
9145                         abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9146                                 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9147                                 useIsaSpecificSubdirs);
9148                     } else {
9149                         abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9150                     }
9151                 }
9152
9153                 maybeThrowExceptionForMultiArchCopy(
9154                         "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9155
9156                 if (abi64 >= 0) {
9157                     pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9158                 }
9159
9160                 if (abi32 >= 0) {
9161                     final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9162                     if (abi64 >= 0) {
9163                         if (pkg.use32bitAbi) {
9164                             pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9165                             pkg.applicationInfo.primaryCpuAbi = abi;
9166                         } else {
9167                             pkg.applicationInfo.secondaryCpuAbi = abi;
9168                         }
9169                     } else {
9170                         pkg.applicationInfo.primaryCpuAbi = abi;
9171                     }
9172                 }
9173
9174             } else {
9175                 String[] abiList = (cpuAbiOverride != null) ?
9176                         new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9177
9178                 // Enable gross and lame hacks for apps that are built with old
9179                 // SDK tools. We must scan their APKs for renderscript bitcode and
9180                 // not launch them if it's present. Don't bother checking on devices
9181                 // that don't have 64 bit support.
9182                 boolean needsRenderScriptOverride = false;
9183                 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9184                         NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9185                     abiList = Build.SUPPORTED_32_BIT_ABIS;
9186                     needsRenderScriptOverride = true;
9187                 }
9188
9189                 final int copyRet;
9190                 if (extractLibs) {
9191                     copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9192                             nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9193                 } else {
9194                     copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9195                 }
9196
9197                 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9198                     throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9199                             "Error unpackaging native libs for app, errorCode=" + copyRet);
9200                 }
9201
9202                 if (copyRet >= 0) {
9203                     pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9204                 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9205                     pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9206                 } else if (needsRenderScriptOverride) {
9207                     pkg.applicationInfo.primaryCpuAbi = abiList[0];
9208                 }
9209             }
9210         } catch (IOException ioe) {
9211             Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9212         } finally {
9213             IoUtils.closeQuietly(handle);
9214         }
9215
9216         // Now that we've calculated the ABIs and determined if it's an internal app,
9217         // we will go ahead and populate the nativeLibraryPath.
9218         setNativeLibraryPaths(pkg);
9219     }
9220
9221     /**
9222      * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9223      * i.e, so that all packages can be run inside a single process if required.
9224      *
9225      * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9226      * this function will either try and make the ABI for all packages in {@code packagesForUser}
9227      * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9228      * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9229      * updating a package that belongs to a shared user.
9230      *
9231      * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9232      * adds unnecessary complexity.
9233      */
9234     private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9235             PackageParser.Package scannedPackage, boolean bootComplete) {
9236         String requiredInstructionSet = null;
9237         if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9238             requiredInstructionSet = VMRuntime.getInstructionSet(
9239                      scannedPackage.applicationInfo.primaryCpuAbi);
9240         }
9241
9242         PackageSetting requirer = null;
9243         for (PackageSetting ps : packagesForUser) {
9244             // If packagesForUser contains scannedPackage, we skip it. This will happen
9245             // when scannedPackage is an update of an existing package. Without this check,
9246             // we will never be able to change the ABI of any package belonging to a shared
9247             // user, even if it's compatible with other packages.
9248             if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9249                 if (ps.primaryCpuAbiString == null) {
9250                     continue;
9251                 }
9252
9253                 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9254                 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9255                     // We have a mismatch between instruction sets (say arm vs arm64) warn about
9256                     // this but there's not much we can do.
9257                     String errorMessage = "Instruction set mismatch, "
9258                             + ((requirer == null) ? "[caller]" : requirer)
9259                             + " requires " + requiredInstructionSet + " whereas " + ps
9260                             + " requires " + instructionSet;
9261                     Slog.w(TAG, errorMessage);
9262                 }
9263
9264                 if (requiredInstructionSet == null) {
9265                     requiredInstructionSet = instructionSet;
9266                     requirer = ps;
9267                 }
9268             }
9269         }
9270
9271         if (requiredInstructionSet != null) {
9272             String adjustedAbi;
9273             if (requirer != null) {
9274                 // requirer != null implies that either scannedPackage was null or that scannedPackage
9275                 // did not require an ABI, in which case we have to adjust scannedPackage to match
9276                 // the ABI of the set (which is the same as requirer's ABI)
9277                 adjustedAbi = requirer.primaryCpuAbiString;
9278                 if (scannedPackage != null) {
9279                     scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9280                 }
9281             } else {
9282                 // requirer == null implies that we're updating all ABIs in the set to
9283                 // match scannedPackage.
9284                 adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9285             }
9286
9287             for (PackageSetting ps : packagesForUser) {
9288                 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9289                     if (ps.primaryCpuAbiString != null) {
9290                         continue;
9291                     }
9292
9293                     ps.primaryCpuAbiString = adjustedAbi;
9294                     if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9295                             !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9296                         ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9297                         Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9298                                 + " (requirer="
9299                                 + (requirer == null ? "null" : requirer.pkg.packageName)
9300                                 + ", scannedPackage="
9301                                 + (scannedPackage != null ? scannedPackage.packageName : "null")
9302                                 + ")");
9303                         try {
9304                             mInstaller.rmdex(ps.codePathString,
9305                                     getDexCodeInstructionSet(getPreferredInstructionSet()));
9306                         } catch (InstallerException ignored) {
9307                         }
9308                     }
9309                 }
9310             }
9311         }
9312     }
9313
9314     private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9315         synchronized (mPackages) {
9316             mResolverReplaced = true;
9317             // Set up information for custom user intent resolution activity.
9318             mResolveActivity.applicationInfo = pkg.applicationInfo;
9319             mResolveActivity.name = mCustomResolverComponentName.getClassName();
9320             mResolveActivity.packageName = pkg.applicationInfo.packageName;
9321             mResolveActivity.processName = pkg.applicationInfo.packageName;
9322             mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9323             mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9324                     ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9325             mResolveActivity.theme = 0;
9326             mResolveActivity.exported = true;
9327             mResolveActivity.enabled = true;
9328             mResolveInfo.activityInfo = mResolveActivity;
9329             mResolveInfo.priority = 0;
9330             mResolveInfo.preferredOrder = 0;
9331             mResolveInfo.match = 0;
9332             mResolveComponentName = mCustomResolverComponentName;
9333             Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9334                     mResolveComponentName);
9335         }
9336     }
9337
9338     private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9339         final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9340
9341         // Set up information for ephemeral installer activity
9342         mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9343         mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9344         mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9345         mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9346         mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9347         mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9348                 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9349         mEphemeralInstallerActivity.theme = 0;
9350         mEphemeralInstallerActivity.exported = true;
9351         mEphemeralInstallerActivity.enabled = true;
9352         mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9353         mEphemeralInstallerInfo.priority = 0;
9354         mEphemeralInstallerInfo.preferredOrder = 1;
9355         mEphemeralInstallerInfo.isDefault = true;
9356         mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9357                 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9358
9359         if (DEBUG_EPHEMERAL) {
9360             Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9361         }
9362     }
9363
9364     private static String calculateBundledApkRoot(final String codePathString) {
9365         final File codePath = new File(codePathString);
9366         final File codeRoot;
9367         if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9368             codeRoot = Environment.getRootDirectory();
9369         } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9370             codeRoot = Environment.getOemDirectory();
9371         } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9372             codeRoot = Environment.getVendorDirectory();
9373         } else {
9374             // Unrecognized code path; take its top real segment as the apk root:
9375             // e.g. /something/app/blah.apk => /something
9376             try {
9377                 File f = codePath.getCanonicalFile();
9378                 File parent = f.getParentFile();    // non-null because codePath is a file
9379                 File tmp;
9380                 while ((tmp = parent.getParentFile()) != null) {
9381                     f = parent;
9382                     parent = tmp;
9383                 }
9384                 codeRoot = f;
9385                 Slog.w(TAG, "Unrecognized code path "
9386                         + codePath + " - using " + codeRoot);
9387             } catch (IOException e) {
9388                 // Can't canonicalize the code path -- shenanigans?
9389                 Slog.w(TAG, "Can't canonicalize code path " + codePath);
9390                 return Environment.getRootDirectory().getPath();
9391             }
9392         }
9393         return codeRoot.getPath();
9394     }
9395
9396     /**
9397      * Derive and set the location of native libraries for the given package,
9398      * which varies depending on where and how the package was installed.
9399      */
9400     private void setNativeLibraryPaths(PackageParser.Package pkg) {
9401         final ApplicationInfo info = pkg.applicationInfo;
9402         final String codePath = pkg.codePath;
9403         final File codeFile = new File(codePath);
9404         final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9405         final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9406
9407         info.nativeLibraryRootDir = null;
9408         info.nativeLibraryRootRequiresIsa = false;
9409         info.nativeLibraryDir = null;
9410         info.secondaryNativeLibraryDir = null;
9411
9412         if (isApkFile(codeFile)) {
9413             // Monolithic install
9414             if (bundledApp) {
9415                 // If "/system/lib64/apkname" exists, assume that is the per-package
9416                 // native library directory to use; otherwise use "/system/lib/apkname".
9417                 final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9418                 final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9419                         getPrimaryInstructionSet(info));
9420
9421                 // This is a bundled system app so choose the path based on the ABI.
9422                 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9423                 // is just the default path.
9424                 final String apkName = deriveCodePathName(codePath);
9425                 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9426                 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9427                         apkName).getAbsolutePath();
9428
9429                 if (info.secondaryCpuAbi != null) {
9430                     final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9431                     info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9432                             secondaryLibDir, apkName).getAbsolutePath();
9433                 }
9434             } else if (asecApp) {
9435                 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9436                         .getAbsolutePath();
9437             } else {
9438                 final String apkName = deriveCodePathName(codePath);
9439                 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9440                         .getAbsolutePath();
9441             }
9442
9443             info.nativeLibraryRootRequiresIsa = false;
9444             info.nativeLibraryDir = info.nativeLibraryRootDir;
9445         } else {
9446             // Cluster install
9447             info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9448             info.nativeLibraryRootRequiresIsa = true;
9449
9450             info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9451                     getPrimaryInstructionSet(info)).getAbsolutePath();
9452
9453             if (info.secondaryCpuAbi != null) {
9454                 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9455                         VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9456             }
9457         }
9458     }
9459
9460     /**
9461      * Calculate the abis and roots for a bundled app. These can uniquely
9462      * be determined from the contents of the system partition, i.e whether
9463      * it contains 64 or 32 bit shared libraries etc. We do not validate any
9464      * of this information, and instead assume that the system was built
9465      * sensibly.
9466      */
9467     private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9468                                            PackageSetting pkgSetting) {
9469         final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9470
9471         // If "/system/lib64/apkname" exists, assume that is the per-package
9472         // native library directory to use; otherwise use "/system/lib/apkname".
9473         final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9474         setBundledAppAbi(pkg, apkRoot, apkName);
9475         // pkgSetting might be null during rescan following uninstall of updates
9476         // to a bundled app, so accommodate that possibility.  The settings in
9477         // that case will be established later from the parsed package.
9478         //
9479         // If the settings aren't null, sync them up with what we've just derived.
9480         // note that apkRoot isn't stored in the package settings.
9481         if (pkgSetting != null) {
9482             pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9483             pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9484         }
9485     }
9486
9487     /**
9488      * Deduces the ABI of a bundled app and sets the relevant fields on the
9489      * parsed pkg object.
9490      *
9491      * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9492      *        under which system libraries are installed.
9493      * @param apkName the name of the installed package.
9494      */
9495     private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9496         final File codeFile = new File(pkg.codePath);
9497
9498         final boolean has64BitLibs;
9499         final boolean has32BitLibs;
9500         if (isApkFile(codeFile)) {
9501             // Monolithic install
9502             has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9503             has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9504         } else {
9505             // Cluster install
9506             final File rootDir = new File(codeFile, LIB_DIR_NAME);
9507             if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9508                     && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9509                 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9510                 has64BitLibs = (new File(rootDir, isa)).exists();
9511             } else {
9512                 has64BitLibs = false;
9513             }
9514             if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9515                     && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9516                 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9517                 has32BitLibs = (new File(rootDir, isa)).exists();
9518             } else {
9519                 has32BitLibs = false;
9520             }
9521         }
9522
9523         if (has64BitLibs && !has32BitLibs) {
9524             // The package has 64 bit libs, but not 32 bit libs. Its primary
9525             // ABI should be 64 bit. We can safely assume here that the bundled
9526             // native libraries correspond to the most preferred ABI in the list.
9527
9528             pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9529             pkg.applicationInfo.secondaryCpuAbi = null;
9530         } else if (has32BitLibs && !has64BitLibs) {
9531             // The package has 32 bit libs but not 64 bit libs. Its primary
9532             // ABI should be 32 bit.
9533
9534             pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9535             pkg.applicationInfo.secondaryCpuAbi = null;
9536         } else if (has32BitLibs && has64BitLibs) {
9537             // The application has both 64 and 32 bit bundled libraries. We check
9538             // here that the app declares multiArch support, and warn if it doesn't.
9539             //
9540             // We will be lenient here and record both ABIs. The primary will be the
9541             // ABI that's higher on the list, i.e, a device that's configured to prefer
9542             // 64 bit apps will see a 64 bit primary ABI,
9543
9544             if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9545                 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9546             }
9547
9548             if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9549                 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9550                 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9551             } else {
9552                 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9553                 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9554             }
9555         } else {
9556             pkg.applicationInfo.primaryCpuAbi = null;
9557             pkg.applicationInfo.secondaryCpuAbi = null;
9558         }
9559     }
9560
9561     private void killApplication(String pkgName, int appId, String reason) {
9562         killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9563     }
9564
9565     private void killApplication(String pkgName, int appId, int userId, String reason) {
9566         // Request the ActivityManager to kill the process(only for existing packages)
9567         // so that we do not end up in a confused state while the user is still using the older
9568         // version of the application while the new one gets installed.
9569         final long token = Binder.clearCallingIdentity();
9570         try {
9571             IActivityManager am = ActivityManagerNative.getDefault();
9572             if (am != null) {
9573                 try {
9574                     am.killApplication(pkgName, appId, userId, reason);
9575                 } catch (RemoteException e) {
9576                 }
9577             }
9578         } finally {
9579             Binder.restoreCallingIdentity(token);
9580         }
9581     }
9582
9583     private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9584         // Remove the parent package setting
9585         PackageSetting ps = (PackageSetting) pkg.mExtras;
9586         if (ps != null) {
9587             removePackageLI(ps, chatty);
9588         }
9589         // Remove the child package setting
9590         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9591         for (int i = 0; i < childCount; i++) {
9592             PackageParser.Package childPkg = pkg.childPackages.get(i);
9593             ps = (PackageSetting) childPkg.mExtras;
9594             if (ps != null) {
9595                 removePackageLI(ps, chatty);
9596             }
9597         }
9598     }
9599
9600     void removePackageLI(PackageSetting ps, boolean chatty) {
9601         if (DEBUG_INSTALL) {
9602             if (chatty)
9603                 Log.d(TAG, "Removing package " + ps.name);
9604         }
9605
9606         // writer
9607         synchronized (mPackages) {
9608             mPackages.remove(ps.name);
9609             final PackageParser.Package pkg = ps.pkg;
9610             if (pkg != null) {
9611                 cleanPackageDataStructuresLILPw(pkg, chatty);
9612             }
9613         }
9614     }
9615
9616     void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9617         if (DEBUG_INSTALL) {
9618             if (chatty)
9619                 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9620         }
9621
9622         // writer
9623         synchronized (mPackages) {
9624             // Remove the parent package
9625             mPackages.remove(pkg.applicationInfo.packageName);
9626             cleanPackageDataStructuresLILPw(pkg, chatty);
9627
9628             // Remove the child packages
9629             final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9630             for (int i = 0; i < childCount; i++) {
9631                 PackageParser.Package childPkg = pkg.childPackages.get(i);
9632                 mPackages.remove(childPkg.applicationInfo.packageName);
9633                 cleanPackageDataStructuresLILPw(childPkg, chatty);
9634             }
9635         }
9636     }
9637
9638     void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9639         int N = pkg.providers.size();
9640         StringBuilder r = null;
9641         int i;
9642         for (i=0; i<N; i++) {
9643             PackageParser.Provider p = pkg.providers.get(i);
9644             mProviders.removeProvider(p);
9645             if (p.info.authority == null) {
9646
9647                 /* There was another ContentProvider with this authority when
9648                  * this app was installed so this authority is null,
9649                  * Ignore it as we don't have to unregister the provider.
9650                  */
9651                 continue;
9652             }
9653             String names[] = p.info.authority.split(";");
9654             for (int j = 0; j < names.length; j++) {
9655                 if (mProvidersByAuthority.get(names[j]) == p) {
9656                     mProvidersByAuthority.remove(names[j]);
9657                     if (DEBUG_REMOVE) {
9658                         if (chatty)
9659                             Log.d(TAG, "Unregistered content provider: " + names[j]
9660                                     + ", className = " + p.info.name + ", isSyncable = "
9661                                     + p.info.isSyncable);
9662                     }
9663                 }
9664             }
9665             if (DEBUG_REMOVE && chatty) {
9666                 if (r == null) {
9667                     r = new StringBuilder(256);
9668                 } else {
9669                     r.append(' ');
9670                 }
9671                 r.append(p.info.name);
9672             }
9673         }
9674         if (r != null) {
9675             if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9676         }
9677
9678         N = pkg.services.size();
9679         r = null;
9680         for (i=0; i<N; i++) {
9681             PackageParser.Service s = pkg.services.get(i);
9682             mServices.removeService(s);
9683             if (chatty) {
9684                 if (r == null) {
9685                     r = new StringBuilder(256);
9686                 } else {
9687                     r.append(' ');
9688                 }
9689                 r.append(s.info.name);
9690             }
9691         }
9692         if (r != null) {
9693             if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9694         }
9695
9696         N = pkg.receivers.size();
9697         r = null;
9698         for (i=0; i<N; i++) {
9699             PackageParser.Activity a = pkg.receivers.get(i);
9700             mReceivers.removeActivity(a, "receiver");
9701             if (DEBUG_REMOVE && chatty) {
9702                 if (r == null) {
9703                     r = new StringBuilder(256);
9704                 } else {
9705                     r.append(' ');
9706                 }
9707                 r.append(a.info.name);
9708             }
9709         }
9710         if (r != null) {
9711             if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9712         }
9713
9714         N = pkg.activities.size();
9715         r = null;
9716         for (i=0; i<N; i++) {
9717             PackageParser.Activity a = pkg.activities.get(i);
9718             mActivities.removeActivity(a, "activity");
9719             if (DEBUG_REMOVE && chatty) {
9720                 if (r == null) {
9721                     r = new StringBuilder(256);
9722                 } else {
9723                     r.append(' ');
9724                 }
9725                 r.append(a.info.name);
9726             }
9727         }
9728         if (r != null) {
9729             if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9730         }
9731
9732         N = pkg.permissions.size();
9733         r = null;
9734         for (i=0; i<N; i++) {
9735             PackageParser.Permission p = pkg.permissions.get(i);
9736             BasePermission bp = mSettings.mPermissions.get(p.info.name);
9737             if (bp == null) {
9738                 bp = mSettings.mPermissionTrees.get(p.info.name);
9739             }
9740             if (bp != null && bp.perm == p) {
9741                 bp.perm = null;
9742                 if (DEBUG_REMOVE && chatty) {
9743                     if (r == null) {
9744                         r = new StringBuilder(256);
9745                     } else {
9746                         r.append(' ');
9747                     }
9748                     r.append(p.info.name);
9749                 }
9750             }
9751             if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9752                 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9753                 if (appOpPkgs != null) {
9754                     appOpPkgs.remove(pkg.packageName);
9755                 }
9756             }
9757         }
9758         if (r != null) {
9759             if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9760         }
9761
9762         N = pkg.requestedPermissions.size();
9763         r = null;
9764         for (i=0; i<N; i++) {
9765             String perm = pkg.requestedPermissions.get(i);
9766             BasePermission bp = mSettings.mPermissions.get(perm);
9767             if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9768                 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9769                 if (appOpPkgs != null) {
9770                     appOpPkgs.remove(pkg.packageName);
9771                     if (appOpPkgs.isEmpty()) {
9772                         mAppOpPermissionPackages.remove(perm);
9773                     }
9774                 }
9775             }
9776         }
9777         if (r != null) {
9778             if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9779         }
9780
9781         N = pkg.instrumentation.size();
9782         r = null;
9783         for (i=0; i<N; i++) {
9784             PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9785             mInstrumentation.remove(a.getComponentName());
9786             if (DEBUG_REMOVE && chatty) {
9787                 if (r == null) {
9788                     r = new StringBuilder(256);
9789                 } else {
9790                     r.append(' ');
9791                 }
9792                 r.append(a.info.name);
9793             }
9794         }
9795         if (r != null) {
9796             if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9797         }
9798
9799         r = null;
9800         if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9801             // Only system apps can hold shared libraries.
9802             if (pkg.libraryNames != null) {
9803                 for (i=0; i<pkg.libraryNames.size(); i++) {
9804                     String name = pkg.libraryNames.get(i);
9805                     SharedLibraryEntry cur = mSharedLibraries.get(name);
9806                     if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9807                         mSharedLibraries.remove(name);
9808                         if (DEBUG_REMOVE && chatty) {
9809                             if (r == null) {
9810                                 r = new StringBuilder(256);
9811                             } else {
9812                                 r.append(' ');
9813                             }
9814                             r.append(name);
9815                         }
9816                     }
9817                 }
9818             }
9819         }
9820         if (r != null) {
9821             if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9822         }
9823     }
9824
9825     private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9826         for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9827             if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9828                 return true;
9829             }
9830         }
9831         return false;
9832     }
9833
9834     static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9835     static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9836     static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9837
9838     private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9839         // Update the parent permissions
9840         updatePermissionsLPw(pkg.packageName, pkg, flags);
9841         // Update the child permissions
9842         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9843         for (int i = 0; i < childCount; i++) {
9844             PackageParser.Package childPkg = pkg.childPackages.get(i);
9845             updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9846         }
9847     }
9848
9849     private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9850             int flags) {
9851         final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9852         updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9853     }
9854
9855     private void updatePermissionsLPw(String changingPkg,
9856             PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9857         // Make sure there are no dangling permission trees.
9858         Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9859         while (it.hasNext()) {
9860             final BasePermission bp = it.next();
9861             if (bp.packageSetting == null) {
9862                 // We may not yet have parsed the package, so just see if
9863                 // we still know about its settings.
9864                 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9865             }
9866             if (bp.packageSetting == null) {
9867                 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9868                         + " from package " + bp.sourcePackage);
9869                 it.remove();
9870             } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9871                 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9872                     Slog.i(TAG, "Removing old permission tree: " + bp.name
9873                             + " from package " + bp.sourcePackage);
9874                     flags |= UPDATE_PERMISSIONS_ALL;
9875                     it.remove();
9876                 }
9877             }
9878         }
9879
9880         // Make sure all dynamic permissions have been assigned to a package,
9881         // and make sure there are no dangling permissions.
9882         it = mSettings.mPermissions.values().iterator();
9883         while (it.hasNext()) {
9884             final BasePermission bp = it.next();
9885             if (bp.type == BasePermission.TYPE_DYNAMIC) {
9886                 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9887                         + bp.name + " pkg=" + bp.sourcePackage
9888                         + " info=" + bp.pendingInfo);
9889                 if (bp.packageSetting == null && bp.pendingInfo != null) {
9890                     final BasePermission tree = findPermissionTreeLP(bp.name);
9891                     if (tree != null && tree.perm != null) {
9892                         bp.packageSetting = tree.packageSetting;
9893                         bp.perm = new PackageParser.Permission(tree.perm.owner,
9894                                 new PermissionInfo(bp.pendingInfo));
9895                         bp.perm.info.packageName = tree.perm.info.packageName;
9896                         bp.perm.info.name = bp.name;
9897                         bp.uid = tree.uid;
9898                     }
9899                 }
9900             }
9901             if (bp.packageSetting == null) {
9902                 // We may not yet have parsed the package, so just see if
9903                 // we still know about its settings.
9904                 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9905             }
9906             if (bp.packageSetting == null) {
9907                 Slog.w(TAG, "Removing dangling permission: " + bp.name
9908                         + " from package " + bp.sourcePackage);
9909                 it.remove();
9910             } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9911                 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9912                     Slog.i(TAG, "Removing old permission: " + bp.name
9913                             + " from package " + bp.sourcePackage);
9914                     flags |= UPDATE_PERMISSIONS_ALL;
9915                     it.remove();
9916                 }
9917             }
9918         }
9919
9920         // Now update the permissions for all packages, in particular
9921         // replace the granted permissions of the system packages.
9922         if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9923             for (PackageParser.Package pkg : mPackages.values()) {
9924                 if (pkg != pkgInfo) {
9925                     // Only replace for packages on requested volume
9926                     final String volumeUuid = getVolumeUuidForPackage(pkg);
9927                     final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9928                             && Objects.equals(replaceVolumeUuid, volumeUuid);
9929                     grantPermissionsLPw(pkg, replace, changingPkg);
9930                 }
9931             }
9932         }
9933
9934         if (pkgInfo != null) {
9935             // Only replace for packages on requested volume
9936             final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9937             final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9938                     && Objects.equals(replaceVolumeUuid, volumeUuid);
9939             grantPermissionsLPw(pkgInfo, replace, changingPkg);
9940         }
9941     }
9942
9943     private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9944             String packageOfInterest) {
9945         // IMPORTANT: There are two types of permissions: install and runtime.
9946         // Install time permissions are granted when the app is installed to
9947         // all device users and users added in the future. Runtime permissions
9948         // are granted at runtime explicitly to specific users. Normal and signature
9949         // protected permissions are install time permissions. Dangerous permissions
9950         // are install permissions if the app's target SDK is Lollipop MR1 or older,
9951         // otherwise they are runtime permissions. This function does not manage
9952         // runtime permissions except for the case an app targeting Lollipop MR1
9953         // being upgraded to target a newer SDK, in which case dangerous permissions
9954         // are transformed from install time to runtime ones.
9955
9956         final PackageSetting ps = (PackageSetting) pkg.mExtras;
9957         if (ps == null) {
9958             return;
9959         }
9960
9961         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9962
9963         PermissionsState permissionsState = ps.getPermissionsState();
9964         PermissionsState origPermissions = permissionsState;
9965
9966         final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9967
9968         boolean runtimePermissionsRevoked = false;
9969         int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9970
9971         boolean changedInstallPermission = false;
9972
9973         if (replace) {
9974             ps.installPermissionsFixed = false;
9975             if (!ps.isSharedUser()) {
9976                 origPermissions = new PermissionsState(permissionsState);
9977                 permissionsState.reset();
9978             } else {
9979                 // We need to know only about runtime permission changes since the
9980                 // calling code always writes the install permissions state but
9981                 // the runtime ones are written only if changed. The only cases of
9982                 // changed runtime permissions here are promotion of an install to
9983                 // runtime and revocation of a runtime from a shared user.
9984                 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9985                         ps.sharedUser, UserManagerService.getInstance().getUserIds());
9986                 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9987                     runtimePermissionsRevoked = true;
9988                 }
9989             }
9990         }
9991
9992         permissionsState.setGlobalGids(mGlobalGids);
9993
9994         final int N = pkg.requestedPermissions.size();
9995         for (int i=0; i<N; i++) {
9996             final String name = pkg.requestedPermissions.get(i);
9997             final BasePermission bp = mSettings.mPermissions.get(name);
9998
9999             if (DEBUG_INSTALL) {
10000                 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10001             }
10002
10003             if (bp == null || bp.packageSetting == null) {
10004                 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10005                     Slog.w(TAG, "Unknown permission " + name
10006                             + " in package " + pkg.packageName);
10007                 }
10008                 continue;
10009             }
10010
10011             final String perm = bp.name;
10012             boolean allowedSig = false;
10013             int grant = GRANT_DENIED;
10014
10015             // Keep track of app op permissions.
10016             if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10017                 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10018                 if (pkgs == null) {
10019                     pkgs = new ArraySet<>();
10020                     mAppOpPermissionPackages.put(bp.name, pkgs);
10021                 }
10022                 pkgs.add(pkg.packageName);
10023             }
10024
10025             final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10026             final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10027                     >= Build.VERSION_CODES.M;
10028             switch (level) {
10029                 case PermissionInfo.PROTECTION_NORMAL: {
10030                     // For all apps normal permissions are install time ones.
10031                     grant = GRANT_INSTALL;
10032                 } break;
10033
10034                 case PermissionInfo.PROTECTION_DANGEROUS: {
10035                     // If a permission review is required for legacy apps we represent
10036                     // their permissions as always granted runtime ones since we need
10037                     // to keep the review required permission flag per user while an
10038                     // install permission's state is shared across all users.
10039                     if (!appSupportsRuntimePermissions && !mPermissionReviewRequired
10040                             && !Build.PERMISSIONS_REVIEW_REQUIRED) {
10041                         // For legacy apps dangerous permissions are install time ones.
10042                         grant = GRANT_INSTALL;
10043                     } else if (origPermissions.hasInstallPermission(bp.name)) {
10044                         // For legacy apps that became modern, install becomes runtime.
10045                         grant = GRANT_UPGRADE;
10046                     } else if (mPromoteSystemApps
10047                             && isSystemApp(ps)
10048                             && mExistingSystemPackages.contains(ps.name)) {
10049                         // For legacy system apps, install becomes runtime.
10050                         // We cannot check hasInstallPermission() for system apps since those
10051                         // permissions were granted implicitly and not persisted pre-M.
10052                         grant = GRANT_UPGRADE;
10053                     } else {
10054                         // For modern apps keep runtime permissions unchanged.
10055                         grant = GRANT_RUNTIME;
10056                     }
10057                 } break;
10058
10059                 case PermissionInfo.PROTECTION_SIGNATURE: {
10060                     // For all apps signature permissions are install time ones.
10061                     allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10062                     if (allowedSig) {
10063                         grant = GRANT_INSTALL;
10064                     }
10065                 } break;
10066             }
10067
10068             if (DEBUG_INSTALL) {
10069                 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10070             }
10071
10072             if (grant != GRANT_DENIED) {
10073                 if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10074                     // If this is an existing, non-system package, then
10075                     // we can't add any new permissions to it.
10076                     if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10077                         // Except...  if this is a permission that was added
10078                         // to the platform (note: need to only do this when
10079                         // updating the platform).
10080                         if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10081                             grant = GRANT_DENIED;
10082                         }
10083                     }
10084                 }
10085
10086                 switch (grant) {
10087                     case GRANT_INSTALL: {
10088                         // Revoke this as runtime permission to handle the case of
10089                         // a runtime permission being downgraded to an install one.
10090                         // Also in permission review mode we keep dangerous permissions
10091                         // for legacy apps
10092                         for (int userId : UserManagerService.getInstance().getUserIds()) {
10093                             if (origPermissions.getRuntimePermissionState(
10094                                     bp.name, userId) != null) {
10095                                 // Revoke the runtime permission and clear the flags.
10096                                 origPermissions.revokeRuntimePermission(bp, userId);
10097                                 origPermissions.updatePermissionFlags(bp, userId,
10098                                       PackageManager.MASK_PERMISSION_FLAGS, 0);
10099                                 // If we revoked a permission permission, we have to write.
10100                                 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10101                                         changedRuntimePermissionUserIds, userId);
10102                             }
10103                         }
10104                         // Grant an install permission.
10105                         if (permissionsState.grantInstallPermission(bp) !=
10106                                 PermissionsState.PERMISSION_OPERATION_FAILURE) {
10107                             changedInstallPermission = true;
10108                         }
10109                     } break;
10110
10111                     case GRANT_RUNTIME: {
10112                         // Grant previously granted runtime permissions.
10113                         for (int userId : UserManagerService.getInstance().getUserIds()) {
10114                             PermissionState permissionState = origPermissions
10115                                     .getRuntimePermissionState(bp.name, userId);
10116                             int flags = permissionState != null
10117                                     ? permissionState.getFlags() : 0;
10118                             if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10119                                 // Don't propagate the permission in a permission review mode if
10120                                 // the former was revoked, i.e. marked to not propagate on upgrade.
10121                                 // Note that in a permission review mode install permissions are
10122                                 // represented as constantly granted runtime ones since we need to
10123                                 // keep a per user state associated with the permission. Also the
10124                                 // revoke on upgrade flag is no longer applicable and is reset.
10125                                 final boolean revokeOnUpgrade = (flags & PackageManager
10126                                         .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
10127                                 if (revokeOnUpgrade) {
10128                                     flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
10129                                     // Since we changed the flags, we have to write.
10130                                     changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10131                                             changedRuntimePermissionUserIds, userId);
10132                                 }
10133                                 if (!mPermissionReviewRequired || !revokeOnUpgrade) {
10134                                     if (permissionsState.grantRuntimePermission(bp, userId) ==
10135                                             PermissionsState.PERMISSION_OPERATION_FAILURE) {
10136                                         // If we cannot put the permission as it was,
10137                                         // we have to write.
10138                                         changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10139                                                 changedRuntimePermissionUserIds, userId);
10140                                     }
10141                                 }
10142
10143                                 // If the app supports runtime permissions no need for a review.
10144                                 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
10145                                         && appSupportsRuntimePermissions
10146                                         && (flags & PackageManager
10147                                                 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10148                                     flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10149                                     // Since we changed the flags, we have to write.
10150                                     changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10151                                             changedRuntimePermissionUserIds, userId);
10152                                 }
10153                             } else if ((mPermissionReviewRequired
10154                                         || Build.PERMISSIONS_REVIEW_REQUIRED)
10155                                     && !appSupportsRuntimePermissions) {
10156                                 // For legacy apps that need a permission review, every new
10157                                 // runtime permission is granted but it is pending a review.
10158                                 // We also need to review only platform defined runtime
10159                                 // permissions as these are the only ones the platform knows
10160                                 // how to disable the API to simulate revocation as legacy
10161                                 // apps don't expect to run with revoked permissions.
10162                                 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10163                                     if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10164                                         flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10165                                         // We changed the flags, hence have to write.
10166                                         changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10167                                                 changedRuntimePermissionUserIds, userId);
10168                                     }
10169                                 }
10170                                 if (permissionsState.grantRuntimePermission(bp, userId)
10171                                         != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10172                                     // We changed the permission, hence have to write.
10173                                     changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10174                                             changedRuntimePermissionUserIds, userId);
10175                                 }
10176                             }
10177                             // Propagate the permission flags.
10178                             permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10179                         }
10180                     } break;
10181
10182                     case GRANT_UPGRADE: {
10183                         // Grant runtime permissions for a previously held install permission.
10184                         PermissionState permissionState = origPermissions
10185                                 .getInstallPermissionState(bp.name);
10186                         final int flags = permissionState != null ? permissionState.getFlags() : 0;
10187
10188                         if (origPermissions.revokeInstallPermission(bp)
10189                                 != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10190                             // We will be transferring the permission flags, so clear them.
10191                             origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10192                                     PackageManager.MASK_PERMISSION_FLAGS, 0);
10193                             changedInstallPermission = true;
10194                         }
10195
10196                         // If the permission is not to be promoted to runtime we ignore it and
10197                         // also its other flags as they are not applicable to install permissions.
10198                         if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10199                             for (int userId : currentUserIds) {
10200                                 if (permissionsState.grantRuntimePermission(bp, userId) !=
10201                                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
10202                                     // Transfer the permission flags.
10203                                     permissionsState.updatePermissionFlags(bp, userId,
10204                                             flags, flags);
10205                                     // If we granted the permission, we have to write.
10206                                     changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10207                                             changedRuntimePermissionUserIds, userId);
10208                                 }
10209                             }
10210                         }
10211                     } break;
10212
10213                     default: {
10214                         if (packageOfInterest == null
10215                                 || packageOfInterest.equals(pkg.packageName)) {
10216                             Slog.w(TAG, "Not granting permission " + perm
10217                                     + " to package " + pkg.packageName
10218                                     + " because it was previously installed without");
10219                         }
10220                     } break;
10221                 }
10222             } else {
10223                 if (permissionsState.revokeInstallPermission(bp) !=
10224                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
10225                     // Also drop the permission flags.
10226                     permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10227                             PackageManager.MASK_PERMISSION_FLAGS, 0);
10228                     changedInstallPermission = true;
10229                     Slog.i(TAG, "Un-granting permission " + perm
10230                             + " from package " + pkg.packageName
10231                             + " (protectionLevel=" + bp.protectionLevel
10232                             + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10233                             + ")");
10234                 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10235                     // Don't print warning for app op permissions, since it is fine for them
10236                     // not to be granted, there is a UI for the user to decide.
10237                     if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10238                         Slog.w(TAG, "Not granting permission " + perm
10239                                 + " to package " + pkg.packageName
10240                                 + " (protectionLevel=" + bp.protectionLevel
10241                                 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10242                                 + ")");
10243                     }
10244                 }
10245             }
10246         }
10247
10248         if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10249                 !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10250             // This is the first that we have heard about this package, so the
10251             // permissions we have now selected are fixed until explicitly
10252             // changed.
10253             ps.installPermissionsFixed = true;
10254         }
10255
10256         // Persist the runtime permissions state for users with changes. If permissions
10257         // were revoked because no app in the shared user declares them we have to
10258         // write synchronously to avoid losing runtime permissions state.
10259         for (int userId : changedRuntimePermissionUserIds) {
10260             mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10261         }
10262
10263         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10264     }
10265
10266     private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10267         boolean allowed = false;
10268         final int NP = PackageParser.NEW_PERMISSIONS.length;
10269         for (int ip=0; ip<NP; ip++) {
10270             final PackageParser.NewPermissionInfo npi
10271                     = PackageParser.NEW_PERMISSIONS[ip];
10272             if (npi.name.equals(perm)
10273                     && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10274                 allowed = true;
10275                 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10276                         + pkg.packageName);
10277                 break;
10278             }
10279         }
10280         return allowed;
10281     }
10282
10283     private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10284             BasePermission bp, PermissionsState origPermissions) {
10285         boolean allowed;
10286         allowed = (compareSignatures(
10287                 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10288                         == PackageManager.SIGNATURE_MATCH)
10289                 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10290                         == PackageManager.SIGNATURE_MATCH);
10291         if (!allowed && (bp.protectionLevel
10292                 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10293             if (isSystemApp(pkg)) {
10294                 // For updated system applications, a system permission
10295                 // is granted only if it had been defined by the original application.
10296                 if (pkg.isUpdatedSystemApp()) {
10297                     final PackageSetting sysPs = mSettings
10298                             .getDisabledSystemPkgLPr(pkg.packageName);
10299                     if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10300                         // If the original was granted this permission, we take
10301                         // that grant decision as read and propagate it to the
10302                         // update.
10303                         if (sysPs.isPrivileged()) {
10304                             allowed = true;
10305                         }
10306                     } else {
10307                         // The system apk may have been updated with an older
10308                         // version of the one on the data partition, but which
10309                         // granted a new system permission that it didn't have
10310                         // before.  In this case we do want to allow the app to
10311                         // now get the new permission if the ancestral apk is
10312                         // privileged to get it.
10313                         if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10314                             for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10315                                 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10316                                     allowed = true;
10317                                     break;
10318                                 }
10319                             }
10320                         }
10321                         // Also if a privileged parent package on the system image or any of
10322                         // its children requested a privileged permission, the updated child
10323                         // packages can also get the permission.
10324                         if (pkg.parentPackage != null) {
10325                             final PackageSetting disabledSysParentPs = mSettings
10326                                     .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10327                             if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10328                                     && disabledSysParentPs.isPrivileged()) {
10329                                 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10330                                     allowed = true;
10331                                 } else if (disabledSysParentPs.pkg.childPackages != null) {
10332                                     final int count = disabledSysParentPs.pkg.childPackages.size();
10333                                     for (int i = 0; i < count; i++) {
10334                                         PackageParser.Package disabledSysChildPkg =
10335                                                 disabledSysParentPs.pkg.childPackages.get(i);
10336                                         if (isPackageRequestingPermission(disabledSysChildPkg,
10337                                                 perm)) {
10338                                             allowed = true;
10339                                             break;
10340                                         }
10341                                     }
10342                                 }
10343                             }
10344                         }
10345                     }
10346                 } else {
10347                     allowed = isPrivilegedApp(pkg);
10348                 }
10349             }
10350         }
10351         if (!allowed) {
10352             if (!allowed && (bp.protectionLevel
10353                     & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10354                     && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10355                 // If this was a previously normal/dangerous permission that got moved
10356                 // to a system permission as part of the runtime permission redesign, then
10357                 // we still want to blindly grant it to old apps.
10358                 allowed = true;
10359             }
10360             if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10361                     && pkg.packageName.equals(mRequiredInstallerPackage)) {
10362                 // If this permission is to be granted to the system installer and
10363                 // this app is an installer, then it gets the permission.
10364                 allowed = true;
10365             }
10366             if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10367                     && pkg.packageName.equals(mRequiredVerifierPackage)) {
10368                 // If this permission is to be granted to the system verifier and
10369                 // this app is a verifier, then it gets the permission.
10370                 allowed = true;
10371             }
10372             if (!allowed && (bp.protectionLevel
10373                     & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10374                     && isSystemApp(pkg)) {
10375                 // Any pre-installed system app is allowed to get this permission.
10376                 allowed = true;
10377             }
10378             if (!allowed && (bp.protectionLevel
10379                     & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10380                 // For development permissions, a development permission
10381                 // is granted only if it was already granted.
10382                 allowed = origPermissions.hasInstallPermission(perm);
10383             }
10384             if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10385                     && pkg.packageName.equals(mSetupWizardPackage)) {
10386                 // If this permission is to be granted to the system setup wizard and
10387                 // this app is a setup wizard, then it gets the permission.
10388                 allowed = true;
10389             }
10390         }
10391         return allowed;
10392     }
10393
10394     private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10395         final int permCount = pkg.requestedPermissions.size();
10396         for (int j = 0; j < permCount; j++) {
10397             String requestedPermission = pkg.requestedPermissions.get(j);
10398             if (permission.equals(requestedPermission)) {
10399                 return true;
10400             }
10401         }
10402         return false;
10403     }
10404
10405     final class ActivityIntentResolver
10406             extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10407         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10408                 boolean defaultOnly, int userId) {
10409             if (!sUserManager.exists(userId)) return null;
10410             mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10411             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10412         }
10413
10414         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10415                 int userId) {
10416             if (!sUserManager.exists(userId)) return null;
10417             mFlags = flags;
10418             return super.queryIntent(intent, resolvedType,
10419                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10420         }
10421
10422         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10423                 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10424             if (!sUserManager.exists(userId)) return null;
10425             if (packageActivities == null) {
10426                 return null;
10427             }
10428             mFlags = flags;
10429             final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10430             final int N = packageActivities.size();
10431             ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10432                 new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10433
10434             ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10435             for (int i = 0; i < N; ++i) {
10436                 intentFilters = packageActivities.get(i).intents;
10437                 if (intentFilters != null && intentFilters.size() > 0) {
10438                     PackageParser.ActivityIntentInfo[] array =
10439                             new PackageParser.ActivityIntentInfo[intentFilters.size()];
10440                     intentFilters.toArray(array);
10441                     listCut.add(array);
10442                 }
10443             }
10444             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10445         }
10446
10447         /**
10448          * Finds a privileged activity that matches the specified activity names.
10449          */
10450         private PackageParser.Activity findMatchingActivity(
10451                 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10452             for (PackageParser.Activity sysActivity : activityList) {
10453                 if (sysActivity.info.name.equals(activityInfo.name)) {
10454                     return sysActivity;
10455                 }
10456                 if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10457                     return sysActivity;
10458                 }
10459                 if (sysActivity.info.targetActivity != null) {
10460                     if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10461                         return sysActivity;
10462                     }
10463                     if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10464                         return sysActivity;
10465                     }
10466                 }
10467             }
10468             return null;
10469         }
10470
10471         public class IterGenerator<E> {
10472             public Iterator<E> generate(ActivityIntentInfo info) {
10473                 return null;
10474             }
10475         }
10476
10477         public class ActionIterGenerator extends IterGenerator<String> {
10478             @Override
10479             public Iterator<String> generate(ActivityIntentInfo info) {
10480                 return info.actionsIterator();
10481             }
10482         }
10483
10484         public class CategoriesIterGenerator extends IterGenerator<String> {
10485             @Override
10486             public Iterator<String> generate(ActivityIntentInfo info) {
10487                 return info.categoriesIterator();
10488             }
10489         }
10490
10491         public class SchemesIterGenerator extends IterGenerator<String> {
10492             @Override
10493             public Iterator<String> generate(ActivityIntentInfo info) {
10494                 return info.schemesIterator();
10495             }
10496         }
10497
10498         public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10499             @Override
10500             public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10501                 return info.authoritiesIterator();
10502             }
10503         }
10504
10505         /**
10506          * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10507          * MODIFIED. Do not pass in a list that should not be changed.
10508          */
10509         private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10510                 IterGenerator<T> generator, Iterator<T> searchIterator) {
10511             // loop through the set of actions; every one must be found in the intent filter
10512             while (searchIterator.hasNext()) {
10513                 // we must have at least one filter in the list to consider a match
10514                 if (intentList.size() == 0) {
10515                     break;
10516                 }
10517
10518                 final T searchAction = searchIterator.next();
10519
10520                 // loop through the set of intent filters
10521                 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10522                 while (intentIter.hasNext()) {
10523                     final ActivityIntentInfo intentInfo = intentIter.next();
10524                     boolean selectionFound = false;
10525
10526                     // loop through the intent filter's selection criteria; at least one
10527                     // of them must match the searched criteria
10528                     final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10529                     while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10530                         final T intentSelection = intentSelectionIter.next();
10531                         if (intentSelection != null && intentSelection.equals(searchAction)) {
10532                             selectionFound = true;
10533                             break;
10534                         }
10535                     }
10536
10537                     // the selection criteria wasn't found in this filter's set; this filter
10538                     // is not a potential match
10539                     if (!selectionFound) {
10540                         intentIter.remove();
10541                     }
10542                 }
10543             }
10544         }
10545
10546         private boolean isProtectedAction(ActivityIntentInfo filter) {
10547             final Iterator<String> actionsIter = filter.actionsIterator();
10548             while (actionsIter != null && actionsIter.hasNext()) {
10549                 final String filterAction = actionsIter.next();
10550                 if (PROTECTED_ACTIONS.contains(filterAction)) {
10551                     return true;
10552                 }
10553             }
10554             return false;
10555         }
10556
10557         /**
10558          * Adjusts the priority of the given intent filter according to policy.
10559          * <p>
10560          * <ul>
10561          * <li>The priority for non privileged applications is capped to '0'</li>
10562          * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10563          * <li>The priority for unbundled updates to privileged applications is capped to the
10564          *      priority defined on the system partition</li>
10565          * </ul>
10566          * <p>
10567          * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10568          * allowed to obtain any priority on any action.
10569          */
10570         private void adjustPriority(
10571                 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10572             // nothing to do; priority is fine as-is
10573             if (intent.getPriority() <= 0) {
10574                 return;
10575             }
10576
10577             final ActivityInfo activityInfo = intent.activity.info;
10578             final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10579
10580             final boolean privilegedApp =
10581                     ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10582             if (!privilegedApp) {
10583                 // non-privileged applications can never define a priority >0
10584                 Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10585                         + " package: " + applicationInfo.packageName
10586                         + " activity: " + intent.activity.className
10587                         + " origPrio: " + intent.getPriority());
10588                 intent.setPriority(0);
10589                 return;
10590             }
10591
10592             if (systemActivities == null) {
10593                 // the system package is not disabled; we're parsing the system partition
10594                 if (isProtectedAction(intent)) {
10595                     if (mDeferProtectedFilters) {
10596                         // We can't deal with these just yet. No component should ever obtain a
10597                         // >0 priority for a protected actions, with ONE exception -- the setup
10598                         // wizard. The setup wizard, however, cannot be known until we're able to
10599                         // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10600                         // until all intent filters have been processed. Chicken, meet egg.
10601                         // Let the filter temporarily have a high priority and rectify the
10602                         // priorities after all system packages have been scanned.
10603                         mProtectedFilters.add(intent);
10604                         if (DEBUG_FILTERS) {
10605                             Slog.i(TAG, "Protected action; save for later;"
10606                                     + " package: " + applicationInfo.packageName
10607                                     + " activity: " + intent.activity.className
10608                                     + " origPrio: " + intent.getPriority());
10609                         }
10610                         return;
10611                     } else {
10612                         if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10613                             Slog.i(TAG, "No setup wizard;"
10614                                 + " All protected intents capped to priority 0");
10615                         }
10616                         if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10617                             if (DEBUG_FILTERS) {
10618                                 Slog.i(TAG, "Found setup wizard;"
10619                                     + " allow priority " + intent.getPriority() + ";"
10620                                     + " package: " + intent.activity.info.packageName
10621                                     + " activity: " + intent.activity.className
10622                                     + " priority: " + intent.getPriority());
10623                             }
10624                             // setup wizard gets whatever it wants
10625                             return;
10626                         }
10627                         Slog.w(TAG, "Protected action; cap priority to 0;"
10628                                 + " package: " + intent.activity.info.packageName
10629                                 + " activity: " + intent.activity.className
10630                                 + " origPrio: " + intent.getPriority());
10631                         intent.setPriority(0);
10632                         return;
10633                     }
10634                 }
10635                 // privileged apps on the system image get whatever priority they request
10636                 return;
10637             }
10638
10639             // privileged app unbundled update ... try to find the same activity
10640             final PackageParser.Activity foundActivity =
10641                     findMatchingActivity(systemActivities, activityInfo);
10642             if (foundActivity == null) {
10643                 // this is a new activity; it cannot obtain >0 priority
10644                 if (DEBUG_FILTERS) {
10645                     Slog.i(TAG, "New activity; cap priority to 0;"
10646                             + " package: " + applicationInfo.packageName
10647                             + " activity: " + intent.activity.className
10648                             + " origPrio: " + intent.getPriority());
10649                 }
10650                 intent.setPriority(0);
10651                 return;
10652             }
10653
10654             // found activity, now check for filter equivalence
10655
10656             // a shallow copy is enough; we modify the list, not its contents
10657             final List<ActivityIntentInfo> intentListCopy =
10658                     new ArrayList<>(foundActivity.intents);
10659             final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10660
10661             // find matching action subsets
10662             final Iterator<String> actionsIterator = intent.actionsIterator();
10663             if (actionsIterator != null) {
10664                 getIntentListSubset(
10665                         intentListCopy, new ActionIterGenerator(), actionsIterator);
10666                 if (intentListCopy.size() == 0) {
10667                     // no more intents to match; we're not equivalent
10668                     if (DEBUG_FILTERS) {
10669                         Slog.i(TAG, "Mismatched action; cap priority to 0;"
10670                                 + " package: " + applicationInfo.packageName
10671                                 + " activity: " + intent.activity.className
10672                                 + " origPrio: " + intent.getPriority());
10673                     }
10674                     intent.setPriority(0);
10675                     return;
10676                 }
10677             }
10678
10679             // find matching category subsets
10680             final Iterator<String> categoriesIterator = intent.categoriesIterator();
10681             if (categoriesIterator != null) {
10682                 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10683                         categoriesIterator);
10684                 if (intentListCopy.size() == 0) {
10685                     // no more intents to match; we're not equivalent
10686                     if (DEBUG_FILTERS) {
10687                         Slog.i(TAG, "Mismatched category; cap priority to 0;"
10688                                 + " package: " + applicationInfo.packageName
10689                                 + " activity: " + intent.activity.className
10690                                 + " origPrio: " + intent.getPriority());
10691                     }
10692                     intent.setPriority(0);
10693                     return;
10694                 }
10695             }
10696
10697             // find matching schemes subsets
10698             final Iterator<String> schemesIterator = intent.schemesIterator();
10699             if (schemesIterator != null) {
10700                 getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10701                         schemesIterator);
10702                 if (intentListCopy.size() == 0) {
10703                     // no more intents to match; we're not equivalent
10704                     if (DEBUG_FILTERS) {
10705                         Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10706                                 + " package: " + applicationInfo.packageName
10707                                 + " activity: " + intent.activity.className
10708                                 + " origPrio: " + intent.getPriority());
10709                     }
10710                     intent.setPriority(0);
10711                     return;
10712                 }
10713             }
10714
10715             // find matching authorities subsets
10716             final Iterator<IntentFilter.AuthorityEntry>
10717                     authoritiesIterator = intent.authoritiesIterator();
10718             if (authoritiesIterator != null) {
10719                 getIntentListSubset(intentListCopy,
10720                         new AuthoritiesIterGenerator(),
10721                         authoritiesIterator);
10722                 if (intentListCopy.size() == 0) {
10723                     // no more intents to match; we're not equivalent
10724                     if (DEBUG_FILTERS) {
10725                         Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10726                                 + " package: " + applicationInfo.packageName
10727                                 + " activity: " + intent.activity.className
10728                                 + " origPrio: " + intent.getPriority());
10729                     }
10730                     intent.setPriority(0);
10731                     return;
10732                 }
10733             }
10734
10735             // we found matching filter(s); app gets the max priority of all intents
10736             int cappedPriority = 0;
10737             for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10738                 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10739             }
10740             if (intent.getPriority() > cappedPriority) {
10741                 if (DEBUG_FILTERS) {
10742                     Slog.i(TAG, "Found matching filter(s);"
10743                             + " cap priority to " + cappedPriority + ";"
10744                             + " package: " + applicationInfo.packageName
10745                             + " activity: " + intent.activity.className
10746                             + " origPrio: " + intent.getPriority());
10747                 }
10748                 intent.setPriority(cappedPriority);
10749                 return;
10750             }
10751             // all this for nothing; the requested priority was <= what was on the system
10752         }
10753
10754         public final void addActivity(PackageParser.Activity a, String type) {
10755             mActivities.put(a.getComponentName(), a);
10756             if (DEBUG_SHOW_INFO)
10757                 Log.v(
10758                 TAG, "  " + type + " " +
10759                 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10760             if (DEBUG_SHOW_INFO)
10761                 Log.v(TAG, "    Class=" + a.info.name);
10762             final int NI = a.intents.size();
10763             for (int j=0; j<NI; j++) {
10764                 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10765                 if ("activity".equals(type)) {
10766                     final PackageSetting ps =
10767                             mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10768                     final List<PackageParser.Activity> systemActivities =
10769                             ps != null && ps.pkg != null ? ps.pkg.activities : null;
10770                     adjustPriority(systemActivities, intent);
10771                 }
10772                 if (DEBUG_SHOW_INFO) {
10773                     Log.v(TAG, "    IntentFilter:");
10774                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10775                 }
10776                 if (!intent.debugCheck()) {
10777                     Log.w(TAG, "==> For Activity " + a.info.name);
10778                 }
10779                 addFilter(intent);
10780             }
10781         }
10782
10783         public final void removeActivity(PackageParser.Activity a, String type) {
10784             mActivities.remove(a.getComponentName());
10785             if (DEBUG_SHOW_INFO) {
10786                 Log.v(TAG, "  " + type + " "
10787                         + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10788                                 : a.info.name) + ":");
10789                 Log.v(TAG, "    Class=" + a.info.name);
10790             }
10791             final int NI = a.intents.size();
10792             for (int j=0; j<NI; j++) {
10793                 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10794                 if (DEBUG_SHOW_INFO) {
10795                     Log.v(TAG, "    IntentFilter:");
10796                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10797                 }
10798                 removeFilter(intent);
10799             }
10800         }
10801
10802         @Override
10803         protected boolean allowFilterResult(
10804                 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10805             ActivityInfo filterAi = filter.activity.info;
10806             for (int i=dest.size()-1; i>=0; i--) {
10807                 ActivityInfo destAi = dest.get(i).activityInfo;
10808                 if (destAi.name == filterAi.name
10809                         && destAi.packageName == filterAi.packageName) {
10810                     return false;
10811                 }
10812             }
10813             return true;
10814         }
10815
10816         @Override
10817         protected ActivityIntentInfo[] newArray(int size) {
10818             return new ActivityIntentInfo[size];
10819         }
10820
10821         @Override
10822         protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10823             if (!sUserManager.exists(userId)) return true;
10824             PackageParser.Package p = filter.activity.owner;
10825             if (p != null) {
10826                 PackageSetting ps = (PackageSetting)p.mExtras;
10827                 if (ps != null) {
10828                     // System apps are never considered stopped for purposes of
10829                     // filtering, because there may be no way for the user to
10830                     // actually re-launch them.
10831                     return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10832                             && ps.getStopped(userId);
10833                 }
10834             }
10835             return false;
10836         }
10837
10838         @Override
10839         protected boolean isPackageForFilter(String packageName,
10840                 PackageParser.ActivityIntentInfo info) {
10841             return packageName.equals(info.activity.owner.packageName);
10842         }
10843
10844         @Override
10845         protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10846                 int match, int userId) {
10847             if (!sUserManager.exists(userId)) return null;
10848             if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10849                 return null;
10850             }
10851             final PackageParser.Activity activity = info.activity;
10852             PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10853             if (ps == null) {
10854                 return null;
10855             }
10856             ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10857                     ps.readUserState(userId), userId);
10858             if (ai == null) {
10859                 return null;
10860             }
10861             final ResolveInfo res = new ResolveInfo();
10862             res.activityInfo = ai;
10863             if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10864                 res.filter = info;
10865             }
10866             if (info != null) {
10867                 res.handleAllWebDataURI = info.handleAllWebDataURI();
10868             }
10869             res.priority = info.getPriority();
10870             res.preferredOrder = activity.owner.mPreferredOrder;
10871             //System.out.println("Result: " + res.activityInfo.className +
10872             //                   " = " + res.priority);
10873             res.match = match;
10874             res.isDefault = info.hasDefault;
10875             res.labelRes = info.labelRes;
10876             res.nonLocalizedLabel = info.nonLocalizedLabel;
10877             if (userNeedsBadging(userId)) {
10878                 res.noResourceId = true;
10879             } else {
10880                 res.icon = info.icon;
10881             }
10882             res.iconResourceId = info.icon;
10883             res.system = res.activityInfo.applicationInfo.isSystemApp();
10884             return res;
10885         }
10886
10887         @Override
10888         protected void sortResults(List<ResolveInfo> results) {
10889             Collections.sort(results, mResolvePrioritySorter);
10890         }
10891
10892         @Override
10893         protected void dumpFilter(PrintWriter out, String prefix,
10894                 PackageParser.ActivityIntentInfo filter) {
10895             out.print(prefix); out.print(
10896                     Integer.toHexString(System.identityHashCode(filter.activity)));
10897                     out.print(' ');
10898                     filter.activity.printComponentShortName(out);
10899                     out.print(" filter ");
10900                     out.println(Integer.toHexString(System.identityHashCode(filter)));
10901         }
10902
10903         @Override
10904         protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10905             return filter.activity;
10906         }
10907
10908         protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10909             PackageParser.Activity activity = (PackageParser.Activity)label;
10910             out.print(prefix); out.print(
10911                     Integer.toHexString(System.identityHashCode(activity)));
10912                     out.print(' ');
10913                     activity.printComponentShortName(out);
10914             if (count > 1) {
10915                 out.print(" ("); out.print(count); out.print(" filters)");
10916             }
10917             out.println();
10918         }
10919
10920         // Keys are String (activity class name), values are Activity.
10921         private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10922                 = new ArrayMap<ComponentName, PackageParser.Activity>();
10923         private int mFlags;
10924     }
10925
10926     private final class ServiceIntentResolver
10927             extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10928         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10929                 boolean defaultOnly, int userId) {
10930             mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10931             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10932         }
10933
10934         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10935                 int userId) {
10936             if (!sUserManager.exists(userId)) return null;
10937             mFlags = flags;
10938             return super.queryIntent(intent, resolvedType,
10939                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10940         }
10941
10942         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10943                 int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10944             if (!sUserManager.exists(userId)) return null;
10945             if (packageServices == null) {
10946                 return null;
10947             }
10948             mFlags = flags;
10949             final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10950             final int N = packageServices.size();
10951             ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10952                 new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10953
10954             ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10955             for (int i = 0; i < N; ++i) {
10956                 intentFilters = packageServices.get(i).intents;
10957                 if (intentFilters != null && intentFilters.size() > 0) {
10958                     PackageParser.ServiceIntentInfo[] array =
10959                             new PackageParser.ServiceIntentInfo[intentFilters.size()];
10960                     intentFilters.toArray(array);
10961                     listCut.add(array);
10962                 }
10963             }
10964             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10965         }
10966
10967         public final void addService(PackageParser.Service s) {
10968             mServices.put(s.getComponentName(), s);
10969             if (DEBUG_SHOW_INFO) {
10970                 Log.v(TAG, "  "
10971                         + (s.info.nonLocalizedLabel != null
10972                         ? s.info.nonLocalizedLabel : s.info.name) + ":");
10973                 Log.v(TAG, "    Class=" + s.info.name);
10974             }
10975             final int NI = s.intents.size();
10976             int j;
10977             for (j=0; j<NI; j++) {
10978                 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10979                 if (DEBUG_SHOW_INFO) {
10980                     Log.v(TAG, "    IntentFilter:");
10981                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10982                 }
10983                 if (!intent.debugCheck()) {
10984                     Log.w(TAG, "==> For Service " + s.info.name);
10985                 }
10986                 addFilter(intent);
10987             }
10988         }
10989
10990         public final void removeService(PackageParser.Service s) {
10991             mServices.remove(s.getComponentName());
10992             if (DEBUG_SHOW_INFO) {
10993                 Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10994                         ? s.info.nonLocalizedLabel : s.info.name) + ":");
10995                 Log.v(TAG, "    Class=" + s.info.name);
10996             }
10997             final int NI = s.intents.size();
10998             int j;
10999             for (j=0; j<NI; j++) {
11000                 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11001                 if (DEBUG_SHOW_INFO) {
11002                     Log.v(TAG, "    IntentFilter:");
11003                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11004                 }
11005                 removeFilter(intent);
11006             }
11007         }
11008
11009         @Override
11010         protected boolean allowFilterResult(
11011                 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11012             ServiceInfo filterSi = filter.service.info;
11013             for (int i=dest.size()-1; i>=0; i--) {
11014                 ServiceInfo destAi = dest.get(i).serviceInfo;
11015                 if (destAi.name == filterSi.name
11016                         && destAi.packageName == filterSi.packageName) {
11017                     return false;
11018                 }
11019             }
11020             return true;
11021         }
11022
11023         @Override
11024         protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11025             return new PackageParser.ServiceIntentInfo[size];
11026         }
11027
11028         @Override
11029         protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11030             if (!sUserManager.exists(userId)) return true;
11031             PackageParser.Package p = filter.service.owner;
11032             if (p != null) {
11033                 PackageSetting ps = (PackageSetting)p.mExtras;
11034                 if (ps != null) {
11035                     // System apps are never considered stopped for purposes of
11036                     // filtering, because there may be no way for the user to
11037                     // actually re-launch them.
11038                     return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11039                             && ps.getStopped(userId);
11040                 }
11041             }
11042             return false;
11043         }
11044
11045         @Override
11046         protected boolean isPackageForFilter(String packageName,
11047                 PackageParser.ServiceIntentInfo info) {
11048             return packageName.equals(info.service.owner.packageName);
11049         }
11050
11051         @Override
11052         protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11053                 int match, int userId) {
11054             if (!sUserManager.exists(userId)) return null;
11055             final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11056             if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11057                 return null;
11058             }
11059             final PackageParser.Service service = info.service;
11060             PackageSetting ps = (PackageSetting) service.owner.mExtras;
11061             if (ps == null) {
11062                 return null;
11063             }
11064             ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11065                     ps.readUserState(userId), userId);
11066             if (si == null) {
11067                 return null;
11068             }
11069             final ResolveInfo res = new ResolveInfo();
11070             res.serviceInfo = si;
11071             if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11072                 res.filter = filter;
11073             }
11074             res.priority = info.getPriority();
11075             res.preferredOrder = service.owner.mPreferredOrder;
11076             res.match = match;
11077             res.isDefault = info.hasDefault;
11078             res.labelRes = info.labelRes;
11079             res.nonLocalizedLabel = info.nonLocalizedLabel;
11080             res.icon = info.icon;
11081             res.system = res.serviceInfo.applicationInfo.isSystemApp();
11082             return res;
11083         }
11084
11085         @Override
11086         protected void sortResults(List<ResolveInfo> results) {
11087             Collections.sort(results, mResolvePrioritySorter);
11088         }
11089
11090         @Override
11091         protected void dumpFilter(PrintWriter out, String prefix,
11092                 PackageParser.ServiceIntentInfo filter) {
11093             out.print(prefix); out.print(
11094                     Integer.toHexString(System.identityHashCode(filter.service)));
11095                     out.print(' ');
11096                     filter.service.printComponentShortName(out);
11097                     out.print(" filter ");
11098                     out.println(Integer.toHexString(System.identityHashCode(filter)));
11099         }
11100
11101         @Override
11102         protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11103             return filter.service;
11104         }
11105
11106         protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11107             PackageParser.Service service = (PackageParser.Service)label;
11108             out.print(prefix); out.print(
11109                     Integer.toHexString(System.identityHashCode(service)));
11110                     out.print(' ');
11111                     service.printComponentShortName(out);
11112             if (count > 1) {
11113                 out.print(" ("); out.print(count); out.print(" filters)");
11114             }
11115             out.println();
11116         }
11117
11118 //        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11119 //            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11120 //            final List<ResolveInfo> retList = Lists.newArrayList();
11121 //            while (i.hasNext()) {
11122 //                final ResolveInfo resolveInfo = (ResolveInfo) i;
11123 //                if (isEnabledLP(resolveInfo.serviceInfo)) {
11124 //                    retList.add(resolveInfo);
11125 //                }
11126 //            }
11127 //            return retList;
11128 //        }
11129
11130         // Keys are String (activity class name), values are Activity.
11131         private final ArrayMap<ComponentName, PackageParser.Service> mServices
11132                 = new ArrayMap<ComponentName, PackageParser.Service>();
11133         private int mFlags;
11134     };
11135
11136     private final class ProviderIntentResolver
11137             extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11138         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11139                 boolean defaultOnly, int userId) {
11140             mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11141             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11142         }
11143
11144         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11145                 int userId) {
11146             if (!sUserManager.exists(userId))
11147                 return null;
11148             mFlags = flags;
11149             return super.queryIntent(intent, resolvedType,
11150                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11151         }
11152
11153         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11154                 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11155             if (!sUserManager.exists(userId))
11156                 return null;
11157             if (packageProviders == null) {
11158                 return null;
11159             }
11160             mFlags = flags;
11161             final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11162             final int N = packageProviders.size();
11163             ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11164                     new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11165
11166             ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11167             for (int i = 0; i < N; ++i) {
11168                 intentFilters = packageProviders.get(i).intents;
11169                 if (intentFilters != null && intentFilters.size() > 0) {
11170                     PackageParser.ProviderIntentInfo[] array =
11171                             new PackageParser.ProviderIntentInfo[intentFilters.size()];
11172                     intentFilters.toArray(array);
11173                     listCut.add(array);
11174                 }
11175             }
11176             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11177         }
11178
11179         public final void addProvider(PackageParser.Provider p) {
11180             if (mProviders.containsKey(p.getComponentName())) {
11181                 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11182                 return;
11183             }
11184
11185             mProviders.put(p.getComponentName(), p);
11186             if (DEBUG_SHOW_INFO) {
11187                 Log.v(TAG, "  "
11188                         + (p.info.nonLocalizedLabel != null
11189                                 ? p.info.nonLocalizedLabel : p.info.name) + ":");
11190                 Log.v(TAG, "    Class=" + p.info.name);
11191             }
11192             final int NI = p.intents.size();
11193             int j;
11194             for (j = 0; j < NI; j++) {
11195                 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11196                 if (DEBUG_SHOW_INFO) {
11197                     Log.v(TAG, "    IntentFilter:");
11198                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11199                 }
11200                 if (!intent.debugCheck()) {
11201                     Log.w(TAG, "==> For Provider " + p.info.name);
11202                 }
11203                 addFilter(intent);
11204             }
11205         }
11206
11207         public final void removeProvider(PackageParser.Provider p) {
11208             mProviders.remove(p.getComponentName());
11209             if (DEBUG_SHOW_INFO) {
11210                 Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11211                         ? p.info.nonLocalizedLabel : p.info.name) + ":");
11212                 Log.v(TAG, "    Class=" + p.info.name);
11213             }
11214             final int NI = p.intents.size();
11215             int j;
11216             for (j = 0; j < NI; j++) {
11217                 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11218                 if (DEBUG_SHOW_INFO) {
11219                     Log.v(TAG, "    IntentFilter:");
11220                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11221                 }
11222                 removeFilter(intent);
11223             }
11224         }
11225
11226         @Override
11227         protected boolean allowFilterResult(
11228                 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11229             ProviderInfo filterPi = filter.provider.info;
11230             for (int i = dest.size() - 1; i >= 0; i--) {
11231                 ProviderInfo destPi = dest.get(i).providerInfo;
11232                 if (destPi.name == filterPi.name
11233                         && destPi.packageName == filterPi.packageName) {
11234                     return false;
11235                 }
11236             }
11237             return true;
11238         }
11239
11240         @Override
11241         protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11242             return new PackageParser.ProviderIntentInfo[size];
11243         }
11244
11245         @Override
11246         protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11247             if (!sUserManager.exists(userId))
11248                 return true;
11249             PackageParser.Package p = filter.provider.owner;
11250             if (p != null) {
11251                 PackageSetting ps = (PackageSetting) p.mExtras;
11252                 if (ps != null) {
11253                     // System apps are never considered stopped for purposes of
11254                     // filtering, because there may be no way for the user to
11255                     // actually re-launch them.
11256                     return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11257                             && ps.getStopped(userId);
11258                 }
11259             }
11260             return false;
11261         }
11262
11263         @Override
11264         protected boolean isPackageForFilter(String packageName,
11265                 PackageParser.ProviderIntentInfo info) {
11266             return packageName.equals(info.provider.owner.packageName);
11267         }
11268
11269         @Override
11270         protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11271                 int match, int userId) {
11272             if (!sUserManager.exists(userId))
11273                 return null;
11274             final PackageParser.ProviderIntentInfo info = filter;
11275             if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11276                 return null;
11277             }
11278             final PackageParser.Provider provider = info.provider;
11279             PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11280             if (ps == null) {
11281                 return null;
11282             }
11283             ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11284                     ps.readUserState(userId), userId);
11285             if (pi == null) {
11286                 return null;
11287             }
11288             final ResolveInfo res = new ResolveInfo();
11289             res.providerInfo = pi;
11290             if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11291                 res.filter = filter;
11292             }
11293             res.priority = info.getPriority();
11294             res.preferredOrder = provider.owner.mPreferredOrder;
11295             res.match = match;
11296             res.isDefault = info.hasDefault;
11297             res.labelRes = info.labelRes;
11298             res.nonLocalizedLabel = info.nonLocalizedLabel;
11299             res.icon = info.icon;
11300             res.system = res.providerInfo.applicationInfo.isSystemApp();
11301             return res;
11302         }
11303
11304         @Override
11305         protected void sortResults(List<ResolveInfo> results) {
11306             Collections.sort(results, mResolvePrioritySorter);
11307         }
11308
11309         @Override
11310         protected void dumpFilter(PrintWriter out, String prefix,
11311                 PackageParser.ProviderIntentInfo filter) {
11312             out.print(prefix);
11313             out.print(
11314                     Integer.toHexString(System.identityHashCode(filter.provider)));
11315             out.print(' ');
11316             filter.provider.printComponentShortName(out);
11317             out.print(" filter ");
11318             out.println(Integer.toHexString(System.identityHashCode(filter)));
11319         }
11320
11321         @Override
11322         protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11323             return filter.provider;
11324         }
11325
11326         protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11327             PackageParser.Provider provider = (PackageParser.Provider)label;
11328             out.print(prefix); out.print(
11329                     Integer.toHexString(System.identityHashCode(provider)));
11330                     out.print(' ');
11331                     provider.printComponentShortName(out);
11332             if (count > 1) {
11333                 out.print(" ("); out.print(count); out.print(" filters)");
11334             }
11335             out.println();
11336         }
11337
11338         private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11339                 = new ArrayMap<ComponentName, PackageParser.Provider>();
11340         private int mFlags;
11341     }
11342
11343     private static final class EphemeralIntentResolver
11344             extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11345         /**
11346          * The result that has the highest defined order. Ordering applies on a
11347          * per-package basis. Mapping is from package name to Pair of order and
11348          * EphemeralResolveInfo.
11349          * <p>
11350          * NOTE: This is implemented as a field variable for convenience and efficiency.
11351          * By having a field variable, we're able to track filter ordering as soon as
11352          * a non-zero order is defined. Otherwise, multiple loops across the result set
11353          * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11354          * this needs to be contained entirely within {@link #filterResults()}.
11355          */
11356         final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11357
11358         @Override
11359         protected EphemeralResolveIntentInfo[] newArray(int size) {
11360             return new EphemeralResolveIntentInfo[size];
11361         }
11362
11363         @Override
11364         protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11365             return true;
11366         }
11367
11368         @Override
11369         protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11370                 int userId) {
11371             if (!sUserManager.exists(userId)) {
11372                 return null;
11373             }
11374             final String packageName = info.getEphemeralResolveInfo().getPackageName();
11375             final Integer order = info.getOrder();
11376             final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11377                     mOrderResult.get(packageName);
11378             // ordering is enabled and this item's order isn't high enough
11379             if (lastOrderResult != null && lastOrderResult.first >= order) {
11380                 return null;
11381             }
11382             final EphemeralResolveInfo res = info.getEphemeralResolveInfo();
11383             if (order > 0) {
11384                 // non-zero order, enable ordering
11385                 mOrderResult.put(packageName, new Pair<>(order, res));
11386             }
11387             return res;
11388         }
11389
11390         @Override
11391         protected void filterResults(List<EphemeralResolveInfo> results) {
11392             // only do work if ordering is enabled [most of the time it won't be]
11393             if (mOrderResult.size() == 0) {
11394                 return;
11395             }
11396             int resultSize = results.size();
11397             for (int i = 0; i < resultSize; i++) {
11398                 final EphemeralResolveInfo info = results.get(i);
11399                 final String packageName = info.getPackageName();
11400                 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11401                 if (savedInfo == null) {
11402                     // package doesn't having ordering
11403                     continue;
11404                 }
11405                 if (savedInfo.second == info) {
11406                     // circled back to the highest ordered item; remove from order list
11407                     mOrderResult.remove(savedInfo);
11408                     if (mOrderResult.size() == 0) {
11409                         // no more ordered items
11410                         break;
11411                     }
11412                     continue;
11413                 }
11414                 // item has a worse order, remove it from the result list
11415                 results.remove(i);
11416                 resultSize--;
11417                 i--;
11418             }
11419         }
11420     }
11421
11422     private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11423             new Comparator<ResolveInfo>() {
11424         public int compare(ResolveInfo r1, ResolveInfo r2) {
11425             int v1 = r1.priority;
11426             int v2 = r2.priority;
11427             //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11428             if (v1 != v2) {
11429                 return (v1 > v2) ? -1 : 1;
11430             }
11431             v1 = r1.preferredOrder;
11432             v2 = r2.preferredOrder;
11433             if (v1 != v2) {
11434                 return (v1 > v2) ? -1 : 1;
11435             }
11436             if (r1.isDefault != r2.isDefault) {
11437                 return r1.isDefault ? -1 : 1;
11438             }
11439             v1 = r1.match;
11440             v2 = r2.match;
11441             //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11442             if (v1 != v2) {
11443                 return (v1 > v2) ? -1 : 1;
11444             }
11445             if (r1.system != r2.system) {
11446                 return r1.system ? -1 : 1;
11447             }
11448             if (r1.activityInfo != null) {
11449                 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11450             }
11451             if (r1.serviceInfo != null) {
11452                 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11453             }
11454             if (r1.providerInfo != null) {
11455                 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11456             }
11457             return 0;
11458         }
11459     };
11460
11461     private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11462             new Comparator<ProviderInfo>() {
11463         public int compare(ProviderInfo p1, ProviderInfo p2) {
11464             final int v1 = p1.initOrder;
11465             final int v2 = p2.initOrder;
11466             return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11467         }
11468     };
11469
11470     final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11471             final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11472             final int[] userIds) {
11473         mHandler.post(new Runnable() {
11474             @Override
11475             public void run() {
11476                 try {
11477                     final IActivityManager am = ActivityManagerNative.getDefault();
11478                     if (am == null) return;
11479                     final int[] resolvedUserIds;
11480                     if (userIds == null) {
11481                         resolvedUserIds = am.getRunningUserIds();
11482                     } else {
11483                         resolvedUserIds = userIds;
11484                     }
11485                     for (int id : resolvedUserIds) {
11486                         final Intent intent = new Intent(action,
11487                                 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11488                         if (extras != null) {
11489                             intent.putExtras(extras);
11490                         }
11491                         if (targetPkg != null) {
11492                             intent.setPackage(targetPkg);
11493                         }
11494                         // Modify the UID when posting to other users
11495                         int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11496                         if (uid > 0 && UserHandle.getUserId(uid) != id) {
11497                             uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11498                             intent.putExtra(Intent.EXTRA_UID, uid);
11499                         }
11500                         intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11501                         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11502                         if (DEBUG_BROADCASTS) {
11503                             RuntimeException here = new RuntimeException("here");
11504                             here.fillInStackTrace();
11505                             Slog.d(TAG, "Sending to user " + id + ": "
11506                                     + intent.toShortString(false, true, false, false)
11507                                     + " " + intent.getExtras(), here);
11508                         }
11509                         am.broadcastIntent(null, intent, null, finishedReceiver,
11510                                 0, null, null, null, android.app.AppOpsManager.OP_NONE,
11511                                 null, finishedReceiver != null, false, id);
11512                     }
11513                 } catch (RemoteException ex) {
11514                 }
11515             }
11516         });
11517     }
11518
11519     /**
11520      * Check if the external storage media is available. This is true if there
11521      * is a mounted external storage medium or if the external storage is
11522      * emulated.
11523      */
11524     private boolean isExternalMediaAvailable() {
11525         return mMediaMounted || Environment.isExternalStorageEmulated();
11526     }
11527
11528     @Override
11529     public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11530         // writer
11531         synchronized (mPackages) {
11532             if (!isExternalMediaAvailable()) {
11533                 // If the external storage is no longer mounted at this point,
11534                 // the caller may not have been able to delete all of this
11535                 // packages files and can not delete any more.  Bail.
11536                 return null;
11537             }
11538             final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11539             if (lastPackage != null) {
11540                 pkgs.remove(lastPackage);
11541             }
11542             if (pkgs.size() > 0) {
11543                 return pkgs.get(0);
11544             }
11545         }
11546         return null;
11547     }
11548
11549     void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11550         final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11551                 userId, andCode ? 1 : 0, packageName);
11552         if (mSystemReady) {
11553             msg.sendToTarget();
11554         } else {
11555             if (mPostSystemReadyMessages == null) {
11556                 mPostSystemReadyMessages = new ArrayList<>();
11557             }
11558             mPostSystemReadyMessages.add(msg);
11559         }
11560     }
11561
11562     void startCleaningPackages() {
11563         // reader
11564         if (!isExternalMediaAvailable()) {
11565             return;
11566         }
11567         synchronized (mPackages) {
11568             if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11569                 return;
11570             }
11571         }
11572         Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11573         intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11574         IActivityManager am = ActivityManagerNative.getDefault();
11575         if (am != null) {
11576             try {
11577                 am.startService(null, intent, null, mContext.getOpPackageName(),
11578                         UserHandle.USER_SYSTEM);
11579             } catch (RemoteException e) {
11580             }
11581         }
11582     }
11583
11584     @Override
11585     public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11586             int installFlags, String installerPackageName, int userId) {
11587         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11588
11589         final int callingUid = Binder.getCallingUid();
11590         enforceCrossUserPermission(callingUid, userId,
11591                 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11592
11593         if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11594             try {
11595                 if (observer != null) {
11596                     observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11597                 }
11598             } catch (RemoteException re) {
11599             }
11600             return;
11601         }
11602
11603         if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11604             installFlags |= PackageManager.INSTALL_FROM_ADB;
11605
11606         } else {
11607             // Caller holds INSTALL_PACKAGES permission, so we're less strict
11608             // about installerPackageName.
11609
11610             installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11611             installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11612         }
11613
11614         UserHandle user;
11615         if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11616             user = UserHandle.ALL;
11617         } else {
11618             user = new UserHandle(userId);
11619         }
11620
11621         // Only system components can circumvent runtime permissions when installing.
11622         if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11623                 && mContext.checkCallingOrSelfPermission(Manifest.permission
11624                 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11625             throw new SecurityException("You need the "
11626                     + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11627                     + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11628         }
11629
11630         final File originFile = new File(originPath);
11631         final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11632
11633         final Message msg = mHandler.obtainMessage(INIT_COPY);
11634         final VerificationInfo verificationInfo = new VerificationInfo(
11635                 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11636         final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11637                 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11638                 null /*packageAbiOverride*/, null /*grantedPermissions*/,
11639                 null /*certificates*/);
11640         params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11641         msg.obj = params;
11642
11643         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11644                 System.identityHashCode(msg.obj));
11645         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11646                 System.identityHashCode(msg.obj));
11647
11648         mHandler.sendMessage(msg);
11649     }
11650
11651     void installStage(String packageName, File stagedDir, String stagedCid,
11652             IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11653             String installerPackageName, int installerUid, UserHandle user,
11654             Certificate[][] certificates) {
11655         if (DEBUG_EPHEMERAL) {
11656             if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11657                 Slog.d(TAG, "Ephemeral install of " + packageName);
11658             }
11659         }
11660         final VerificationInfo verificationInfo = new VerificationInfo(
11661                 sessionParams.originatingUri, sessionParams.referrerUri,
11662                 sessionParams.originatingUid, installerUid);
11663
11664         final OriginInfo origin;
11665         if (stagedDir != null) {
11666             origin = OriginInfo.fromStagedFile(stagedDir);
11667         } else {
11668             origin = OriginInfo.fromStagedContainer(stagedCid);
11669         }
11670
11671         final Message msg = mHandler.obtainMessage(INIT_COPY);
11672         final InstallParams params = new InstallParams(origin, null, observer,
11673                 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11674                 verificationInfo, user, sessionParams.abiOverride,
11675                 sessionParams.grantedRuntimePermissions, certificates);
11676         params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11677         msg.obj = params;
11678
11679         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11680                 System.identityHashCode(msg.obj));
11681         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11682                 System.identityHashCode(msg.obj));
11683
11684         mHandler.sendMessage(msg);
11685     }
11686
11687     private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11688             int userId) {
11689         final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11690         sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11691     }
11692
11693     private void sendPackageAddedForUser(String packageName, boolean isSystem,
11694             int appId, int userId) {
11695         Bundle extras = new Bundle(1);
11696         extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11697
11698         sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11699                 packageName, extras, 0, null, null, new int[] {userId});
11700         try {
11701             IActivityManager am = ActivityManagerNative.getDefault();
11702             if (isSystem && am.isUserRunning(userId, 0)) {
11703                 // The just-installed/enabled app is bundled on the system, so presumed
11704                 // to be able to run automatically without needing an explicit launch.
11705                 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11706                 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11707                         .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11708                         .setPackage(packageName);
11709                 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11710                         android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11711             }
11712         } catch (RemoteException e) {
11713             // shouldn't happen
11714             Slog.w(TAG, "Unable to bootstrap installed package", e);
11715         }
11716     }
11717
11718     @Override
11719     public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11720             int userId) {
11721         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11722         PackageSetting pkgSetting;
11723         final int uid = Binder.getCallingUid();
11724         enforceCrossUserPermission(uid, userId,
11725                 true /* requireFullPermission */, true /* checkShell */,
11726                 "setApplicationHiddenSetting for user " + userId);
11727
11728         if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11729             Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11730             return false;
11731         }
11732
11733         long callingId = Binder.clearCallingIdentity();
11734         try {
11735             boolean sendAdded = false;
11736             boolean sendRemoved = false;
11737             // writer
11738             synchronized (mPackages) {
11739                 pkgSetting = mSettings.mPackages.get(packageName);
11740                 if (pkgSetting == null) {
11741                     return false;
11742                 }
11743                 // Do not allow "android" is being disabled
11744                 if ("android".equals(packageName)) {
11745                     Slog.w(TAG, "Cannot hide package: android");
11746                     return false;
11747                 }
11748                 // Only allow protected packages to hide themselves.
11749                 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11750                         && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11751                     Slog.w(TAG, "Not hiding protected package: " + packageName);
11752                     return false;
11753                 }
11754
11755                 if (pkgSetting.getHidden(userId) != hidden) {
11756                     pkgSetting.setHidden(hidden, userId);
11757                     mSettings.writePackageRestrictionsLPr(userId);
11758                     if (hidden) {
11759                         sendRemoved = true;
11760                     } else {
11761                         sendAdded = true;
11762                     }
11763                 }
11764             }
11765             if (sendAdded) {
11766                 sendPackageAddedForUser(packageName, pkgSetting, userId);
11767                 return true;
11768             }
11769             if (sendRemoved) {
11770                 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11771                         "hiding pkg");
11772                 sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11773                 return true;
11774             }
11775         } finally {
11776             Binder.restoreCallingIdentity(callingId);
11777         }
11778         return false;
11779     }
11780
11781     private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11782             int userId) {
11783         final PackageRemovedInfo info = new PackageRemovedInfo();
11784         info.removedPackage = packageName;
11785         info.removedUsers = new int[] {userId};
11786         info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11787         info.sendPackageRemovedBroadcasts(true /*killApp*/);
11788     }
11789
11790     private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11791         if (pkgList.length > 0) {
11792             Bundle extras = new Bundle(1);
11793             extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11794
11795             sendPackageBroadcast(
11796                     suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11797                             : Intent.ACTION_PACKAGES_UNSUSPENDED,
11798                     null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11799                     new int[] {userId});
11800         }
11801     }
11802
11803     /**
11804      * Returns true if application is not found or there was an error. Otherwise it returns
11805      * the hidden state of the package for the given user.
11806      */
11807     @Override
11808     public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11809         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11810         enforceCrossUserPermission(Binder.getCallingUid(), userId,
11811                 true /* requireFullPermission */, false /* checkShell */,
11812                 "getApplicationHidden for user " + userId);
11813         PackageSetting pkgSetting;
11814         long callingId = Binder.clearCallingIdentity();
11815         try {
11816             // writer
11817             synchronized (mPackages) {
11818                 pkgSetting = mSettings.mPackages.get(packageName);
11819                 if (pkgSetting == null) {
11820                     return true;
11821                 }
11822                 return pkgSetting.getHidden(userId);
11823             }
11824         } finally {
11825             Binder.restoreCallingIdentity(callingId);
11826         }
11827     }
11828
11829     /**
11830      * @hide
11831      */
11832     @Override
11833     public int installExistingPackageAsUser(String packageName, int userId) {
11834         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11835                 null);
11836         PackageSetting pkgSetting;
11837         final int uid = Binder.getCallingUid();
11838         enforceCrossUserPermission(uid, userId,
11839                 true /* requireFullPermission */, true /* checkShell */,
11840                 "installExistingPackage for user " + userId);
11841         if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11842             return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11843         }
11844
11845         long callingId = Binder.clearCallingIdentity();
11846         try {
11847             boolean installed = false;
11848
11849             // writer
11850             synchronized (mPackages) {
11851                 pkgSetting = mSettings.mPackages.get(packageName);
11852                 if (pkgSetting == null) {
11853                     return PackageManager.INSTALL_FAILED_INVALID_URI;
11854                 }
11855                 if (!pkgSetting.getInstalled(userId)) {
11856                     pkgSetting.setInstalled(true, userId);
11857                     pkgSetting.setHidden(false, userId);
11858                     mSettings.writePackageRestrictionsLPr(userId);
11859                     installed = true;
11860                 }
11861             }
11862
11863             if (installed) {
11864                 if (pkgSetting.pkg != null) {
11865                     synchronized (mInstallLock) {
11866                         // We don't need to freeze for a brand new install
11867                         prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11868                     }
11869                 }
11870                 sendPackageAddedForUser(packageName, pkgSetting, userId);
11871             }
11872         } finally {
11873             Binder.restoreCallingIdentity(callingId);
11874         }
11875
11876         return PackageManager.INSTALL_SUCCEEDED;
11877     }
11878
11879     boolean isUserRestricted(int userId, String restrictionKey) {
11880         Bundle restrictions = sUserManager.getUserRestrictions(userId);
11881         if (restrictions.getBoolean(restrictionKey, false)) {
11882             Log.w(TAG, "User is restricted: " + restrictionKey);
11883             return true;
11884         }
11885         return false;
11886     }
11887
11888     @Override
11889     public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11890             int userId) {
11891         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11892         enforceCrossUserPermission(Binder.getCallingUid(), userId,
11893                 true /* requireFullPermission */, true /* checkShell */,
11894                 "setPackagesSuspended for user " + userId);
11895
11896         if (ArrayUtils.isEmpty(packageNames)) {
11897             return packageNames;
11898         }
11899
11900         // List of package names for whom the suspended state has changed.
11901         List<String> changedPackages = new ArrayList<>(packageNames.length);
11902         // List of package names for whom the suspended state is not set as requested in this
11903         // method.
11904         List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11905         long callingId = Binder.clearCallingIdentity();
11906         try {
11907             for (int i = 0; i < packageNames.length; i++) {
11908                 String packageName = packageNames[i];
11909                 boolean changed = false;
11910                 final int appId;
11911                 synchronized (mPackages) {
11912                     final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11913                     if (pkgSetting == null) {
11914                         Slog.w(TAG, "Could not find package setting for package \"" + packageName
11915                                 + "\". Skipping suspending/un-suspending.");
11916                         unactionedPackages.add(packageName);
11917                         continue;
11918                     }
11919                     appId = pkgSetting.appId;
11920                     if (pkgSetting.getSuspended(userId) != suspended) {
11921                         if (!canSuspendPackageForUserLocked(packageName, userId)) {
11922                             unactionedPackages.add(packageName);
11923                             continue;
11924                         }
11925                         pkgSetting.setSuspended(suspended, userId);
11926                         mSettings.writePackageRestrictionsLPr(userId);
11927                         changed = true;
11928                         changedPackages.add(packageName);
11929                     }
11930                 }
11931
11932                 if (changed && suspended) {
11933                     killApplication(packageName, UserHandle.getUid(userId, appId),
11934                             "suspending package");
11935                 }
11936             }
11937         } finally {
11938             Binder.restoreCallingIdentity(callingId);
11939         }
11940
11941         if (!changedPackages.isEmpty()) {
11942             sendPackagesSuspendedForUser(changedPackages.toArray(
11943                     new String[changedPackages.size()]), userId, suspended);
11944         }
11945
11946         return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11947     }
11948
11949     @Override
11950     public boolean isPackageSuspendedForUser(String packageName, int userId) {
11951         enforceCrossUserPermission(Binder.getCallingUid(), userId,
11952                 true /* requireFullPermission */, false /* checkShell */,
11953                 "isPackageSuspendedForUser for user " + userId);
11954         synchronized (mPackages) {
11955             final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11956             if (pkgSetting == null) {
11957                 throw new IllegalArgumentException("Unknown target package: " + packageName);
11958             }
11959             return pkgSetting.getSuspended(userId);
11960         }
11961     }
11962
11963     private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11964         if (isPackageDeviceAdmin(packageName, userId)) {
11965             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11966                     + "\": has an active device admin");
11967             return false;
11968         }
11969
11970         String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11971         if (packageName.equals(activeLauncherPackageName)) {
11972             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11973                     + "\": contains the active launcher");
11974             return false;
11975         }
11976
11977         if (packageName.equals(mRequiredInstallerPackage)) {
11978             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11979                     + "\": required for package installation");
11980             return false;
11981         }
11982
11983         if (packageName.equals(mRequiredUninstallerPackage)) {
11984             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11985                     + "\": required for package uninstallation");
11986             return false;
11987         }
11988
11989         if (packageName.equals(mRequiredVerifierPackage)) {
11990             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11991                     + "\": required for package verification");
11992             return false;
11993         }
11994
11995         if (packageName.equals(getDefaultDialerPackageName(userId))) {
11996             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11997                     + "\": is the default dialer");
11998             return false;
11999         }
12000
12001         if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12002             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12003                     + "\": protected package");
12004             return false;
12005         }
12006
12007         return true;
12008     }
12009
12010     private String getActiveLauncherPackageName(int userId) {
12011         Intent intent = new Intent(Intent.ACTION_MAIN);
12012         intent.addCategory(Intent.CATEGORY_HOME);
12013         ResolveInfo resolveInfo = resolveIntent(
12014                 intent,
12015                 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12016                 PackageManager.MATCH_DEFAULT_ONLY,
12017                 userId);
12018
12019         return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12020     }
12021
12022     private String getDefaultDialerPackageName(int userId) {
12023         synchronized (mPackages) {
12024             return mSettings.getDefaultDialerPackageNameLPw(userId);
12025         }
12026     }
12027
12028     @Override
12029     public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12030         mContext.enforceCallingOrSelfPermission(
12031                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12032                 "Only package verification agents can verify applications");
12033
12034         final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12035         final PackageVerificationResponse response = new PackageVerificationResponse(
12036                 verificationCode, Binder.getCallingUid());
12037         msg.arg1 = id;
12038         msg.obj = response;
12039         mHandler.sendMessage(msg);
12040     }
12041
12042     @Override
12043     public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12044             long millisecondsToDelay) {
12045         mContext.enforceCallingOrSelfPermission(
12046                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12047                 "Only package verification agents can extend verification timeouts");
12048
12049         final PackageVerificationState state = mPendingVerification.get(id);
12050         final PackageVerificationResponse response = new PackageVerificationResponse(
12051                 verificationCodeAtTimeout, Binder.getCallingUid());
12052
12053         if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12054             millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12055         }
12056         if (millisecondsToDelay < 0) {
12057             millisecondsToDelay = 0;
12058         }
12059         if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12060                 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12061             verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12062         }
12063
12064         if ((state != null) && !state.timeoutExtended()) {
12065             state.extendTimeout();
12066
12067             final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12068             msg.arg1 = id;
12069             msg.obj = response;
12070             mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12071         }
12072     }
12073
12074     private void broadcastPackageVerified(int verificationId, Uri packageUri,
12075             int verificationCode, UserHandle user) {
12076         final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12077         intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12078         intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12079         intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12080         intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12081
12082         mContext.sendBroadcastAsUser(intent, user,
12083                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12084     }
12085
12086     private ComponentName matchComponentForVerifier(String packageName,
12087             List<ResolveInfo> receivers) {
12088         ActivityInfo targetReceiver = null;
12089
12090         final int NR = receivers.size();
12091         for (int i = 0; i < NR; i++) {
12092             final ResolveInfo info = receivers.get(i);
12093             if (info.activityInfo == null) {
12094                 continue;
12095             }
12096
12097             if (packageName.equals(info.activityInfo.packageName)) {
12098                 targetReceiver = info.activityInfo;
12099                 break;
12100             }
12101         }
12102
12103         if (targetReceiver == null) {
12104             return null;
12105         }
12106
12107         return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12108     }
12109
12110     private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12111             List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12112         if (pkgInfo.verifiers.length == 0) {
12113             return null;
12114         }
12115
12116         final int N = pkgInfo.verifiers.length;
12117         final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12118         for (int i = 0; i < N; i++) {
12119             final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12120
12121             final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12122                     receivers);
12123             if (comp == null) {
12124                 continue;
12125             }
12126
12127             final int verifierUid = getUidForVerifier(verifierInfo);
12128             if (verifierUid == -1) {
12129                 continue;
12130             }
12131
12132             if (DEBUG_VERIFY) {
12133                 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12134                         + " with the correct signature");
12135             }
12136             sufficientVerifiers.add(comp);
12137             verificationState.addSufficientVerifier(verifierUid);
12138         }
12139
12140         return sufficientVerifiers;
12141     }
12142
12143     private int getUidForVerifier(VerifierInfo verifierInfo) {
12144         synchronized (mPackages) {
12145             final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12146             if (pkg == null) {
12147                 return -1;
12148             } else if (pkg.mSignatures.length != 1) {
12149                 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12150                         + " has more than one signature; ignoring");
12151                 return -1;
12152             }
12153
12154             /*
12155              * If the public key of the package's signature does not match
12156              * our expected public key, then this is a different package and
12157              * we should skip.
12158              */
12159
12160             final byte[] expectedPublicKey;
12161             try {
12162                 final Signature verifierSig = pkg.mSignatures[0];
12163                 final PublicKey publicKey = verifierSig.getPublicKey();
12164                 expectedPublicKey = publicKey.getEncoded();
12165             } catch (CertificateException e) {
12166                 return -1;
12167             }
12168
12169             final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12170
12171             if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12172                 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12173                         + " does not have the expected public key; ignoring");
12174                 return -1;
12175             }
12176
12177             return pkg.applicationInfo.uid;
12178         }
12179     }
12180
12181     @Override
12182     public void finishPackageInstall(int token, boolean didLaunch) {
12183         enforceSystemOrRoot("Only the system is allowed to finish installs");
12184
12185         if (DEBUG_INSTALL) {
12186             Slog.v(TAG, "BM finishing package install for " + token);
12187         }
12188         Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12189
12190         final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12191         mHandler.sendMessage(msg);
12192     }
12193
12194     /**
12195      * Get the verification agent timeout.
12196      *
12197      * @return verification timeout in milliseconds
12198      */
12199     private long getVerificationTimeout() {
12200         return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12201                 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12202                 DEFAULT_VERIFICATION_TIMEOUT);
12203     }
12204
12205     /**
12206      * Get the default verification agent response code.
12207      *
12208      * @return default verification response code
12209      */
12210     private int getDefaultVerificationResponse() {
12211         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12212                 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12213                 DEFAULT_VERIFICATION_RESPONSE);
12214     }
12215
12216     /**
12217      * Check whether or not package verification has been enabled.
12218      *
12219      * @return true if verification should be performed
12220      */
12221     private boolean isVerificationEnabled(int userId, int installFlags) {
12222         if (!DEFAULT_VERIFY_ENABLE) {
12223             return false;
12224         }
12225         // Ephemeral apps don't get the full verification treatment
12226         if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12227             if (DEBUG_EPHEMERAL) {
12228                 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12229             }
12230             return false;
12231         }
12232
12233         boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12234
12235         // Check if installing from ADB
12236         if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12237             // Do not run verification in a test harness environment
12238             if (ActivityManager.isRunningInTestHarness()) {
12239                 return false;
12240             }
12241             if (ensureVerifyAppsEnabled) {
12242                 return true;
12243             }
12244             // Check if the developer does not want package verification for ADB installs
12245             if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12246                     android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12247                 return false;
12248             }
12249         }
12250
12251         if (ensureVerifyAppsEnabled) {
12252             return true;
12253         }
12254
12255         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12256                 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12257     }
12258
12259     @Override
12260     public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12261             throws RemoteException {
12262         mContext.enforceCallingOrSelfPermission(
12263                 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12264                 "Only intentfilter verification agents can verify applications");
12265
12266         final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12267         final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12268                 Binder.getCallingUid(), verificationCode, failedDomains);
12269         msg.arg1 = id;
12270         msg.obj = response;
12271         mHandler.sendMessage(msg);
12272     }
12273
12274     @Override
12275     public int getIntentVerificationStatus(String packageName, int userId) {
12276         synchronized (mPackages) {
12277             return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12278         }
12279     }
12280
12281     @Override
12282     public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12283         mContext.enforceCallingOrSelfPermission(
12284                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12285
12286         boolean result = false;
12287         synchronized (mPackages) {
12288             result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12289         }
12290         if (result) {
12291             scheduleWritePackageRestrictionsLocked(userId);
12292         }
12293         return result;
12294     }
12295
12296     @Override
12297     public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12298             String packageName) {
12299         synchronized (mPackages) {
12300             return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12301         }
12302     }
12303
12304     @Override
12305     public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12306         if (TextUtils.isEmpty(packageName)) {
12307             return ParceledListSlice.emptyList();
12308         }
12309         synchronized (mPackages) {
12310             PackageParser.Package pkg = mPackages.get(packageName);
12311             if (pkg == null || pkg.activities == null) {
12312                 return ParceledListSlice.emptyList();
12313             }
12314             final int count = pkg.activities.size();
12315             ArrayList<IntentFilter> result = new ArrayList<>();
12316             for (int n=0; n<count; n++) {
12317                 PackageParser.Activity activity = pkg.activities.get(n);
12318                 if (activity.intents != null && activity.intents.size() > 0) {
12319                     result.addAll(activity.intents);
12320                 }
12321             }
12322             return new ParceledListSlice<>(result);
12323         }
12324     }
12325
12326     @Override
12327     public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12328         mContext.enforceCallingOrSelfPermission(
12329                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12330
12331         synchronized (mPackages) {
12332             boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12333             if (packageName != null) {
12334                 result |= updateIntentVerificationStatus(packageName,
12335                         PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12336                         userId);
12337                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12338                         packageName, userId);
12339             }
12340             return result;
12341         }
12342     }
12343
12344     @Override
12345     public String getDefaultBrowserPackageName(int userId) {
12346         synchronized (mPackages) {
12347             return mSettings.getDefaultBrowserPackageNameLPw(userId);
12348         }
12349     }
12350
12351     /**
12352      * Get the "allow unknown sources" setting.
12353      *
12354      * @return the current "allow unknown sources" setting
12355      */
12356     private int getUnknownSourcesSettings() {
12357         return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12358                 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12359                 -1);
12360     }
12361
12362     @Override
12363     public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12364         final int uid = Binder.getCallingUid();
12365         // writer
12366         synchronized (mPackages) {
12367             PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12368             if (targetPackageSetting == null) {
12369                 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12370             }
12371
12372             PackageSetting installerPackageSetting;
12373             if (installerPackageName != null) {
12374                 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12375                 if (installerPackageSetting == null) {
12376                     throw new IllegalArgumentException("Unknown installer package: "
12377                             + installerPackageName);
12378                 }
12379             } else {
12380                 installerPackageSetting = null;
12381             }
12382
12383             Signature[] callerSignature;
12384             Object obj = mSettings.getUserIdLPr(uid);
12385             if (obj != null) {
12386                 if (obj instanceof SharedUserSetting) {
12387                     callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12388                 } else if (obj instanceof PackageSetting) {
12389                     callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12390                 } else {
12391                     throw new SecurityException("Bad object " + obj + " for uid " + uid);
12392                 }
12393             } else {
12394                 throw new SecurityException("Unknown calling UID: " + uid);
12395             }
12396
12397             // Verify: can't set installerPackageName to a package that is
12398             // not signed with the same cert as the caller.
12399             if (installerPackageSetting != null) {
12400                 if (compareSignatures(callerSignature,
12401                         installerPackageSetting.signatures.mSignatures)
12402                         != PackageManager.SIGNATURE_MATCH) {
12403                     throw new SecurityException(
12404                             "Caller does not have same cert as new installer package "
12405                             + installerPackageName);
12406                 }
12407             }
12408
12409             // Verify: if target already has an installer package, it must
12410             // be signed with the same cert as the caller.
12411             if (targetPackageSetting.installerPackageName != null) {
12412                 PackageSetting setting = mSettings.mPackages.get(
12413                         targetPackageSetting.installerPackageName);
12414                 // If the currently set package isn't valid, then it's always
12415                 // okay to change it.
12416                 if (setting != null) {
12417                     if (compareSignatures(callerSignature,
12418                             setting.signatures.mSignatures)
12419                             != PackageManager.SIGNATURE_MATCH) {
12420                         throw new SecurityException(
12421                                 "Caller does not have same cert as old installer package "
12422                                 + targetPackageSetting.installerPackageName);
12423                     }
12424                 }
12425             }
12426
12427             // Okay!
12428             targetPackageSetting.installerPackageName = installerPackageName;
12429             if (installerPackageName != null) {
12430                 mSettings.mInstallerPackages.add(installerPackageName);
12431             }
12432             scheduleWriteSettingsLocked();
12433         }
12434     }
12435
12436     private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12437         // Queue up an async operation since the package installation may take a little while.
12438         mHandler.post(new Runnable() {
12439             public void run() {
12440                 mHandler.removeCallbacks(this);
12441                  // Result object to be returned
12442                 PackageInstalledInfo res = new PackageInstalledInfo();
12443                 res.setReturnCode(currentStatus);
12444                 res.uid = -1;
12445                 res.pkg = null;
12446                 res.removedInfo = null;
12447                 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12448                     args.doPreInstall(res.returnCode);
12449                     synchronized (mInstallLock) {
12450                         installPackageTracedLI(args, res);
12451                     }
12452                     args.doPostInstall(res.returnCode, res.uid);
12453                 }
12454
12455                 // A restore should be performed at this point if (a) the install
12456                 // succeeded, (b) the operation is not an update, and (c) the new
12457                 // package has not opted out of backup participation.
12458                 final boolean update = res.removedInfo != null
12459                         && res.removedInfo.removedPackage != null;
12460                 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12461                 boolean doRestore = !update
12462                         && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12463
12464                 // Set up the post-install work request bookkeeping.  This will be used
12465                 // and cleaned up by the post-install event handling regardless of whether
12466                 // there's a restore pass performed.  Token values are >= 1.
12467                 int token;
12468                 if (mNextInstallToken < 0) mNextInstallToken = 1;
12469                 token = mNextInstallToken++;
12470
12471                 PostInstallData data = new PostInstallData(args, res);
12472                 mRunningInstalls.put(token, data);
12473                 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12474
12475                 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12476                     // Pass responsibility to the Backup Manager.  It will perform a
12477                     // restore if appropriate, then pass responsibility back to the
12478                     // Package Manager to run the post-install observer callbacks
12479                     // and broadcasts.
12480                     IBackupManager bm = IBackupManager.Stub.asInterface(
12481                             ServiceManager.getService(Context.BACKUP_SERVICE));
12482                     if (bm != null) {
12483                         if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12484                                 + " to BM for possible restore");
12485                         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12486                         try {
12487                             // TODO: http://b/22388012
12488                             if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12489                                 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12490                             } else {
12491                                 doRestore = false;
12492                             }
12493                         } catch (RemoteException e) {
12494                             // can't happen; the backup manager is local
12495                         } catch (Exception e) {
12496                             Slog.e(TAG, "Exception trying to enqueue restore", e);
12497                             doRestore = false;
12498                         }
12499                     } else {
12500                         Slog.e(TAG, "Backup Manager not found!");
12501                         doRestore = false;
12502                     }
12503                 }
12504
12505                 if (!doRestore) {
12506                     // No restore possible, or the Backup Manager was mysteriously not
12507                     // available -- just fire the post-install work request directly.
12508                     if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12509
12510                     Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12511
12512                     Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12513                     mHandler.sendMessage(msg);
12514                 }
12515             }
12516         });
12517     }
12518
12519     /**
12520      * Callback from PackageSettings whenever an app is first transitioned out of the
12521      * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12522      * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12523      * here whether the app is the target of an ongoing install, and only send the
12524      * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12525      * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12526      * handling.
12527      */
12528     void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12529         // Serialize this with the rest of the install-process message chain.  In the
12530         // restore-at-install case, this Runnable will necessarily run before the
12531         // POST_INSTALL message is processed, so the contents of mRunningInstalls
12532         // are coherent.  In the non-restore case, the app has already completed install
12533         // and been launched through some other means, so it is not in a problematic
12534         // state for observers to see the FIRST_LAUNCH signal.
12535         mHandler.post(new Runnable() {
12536             @Override
12537             public void run() {
12538                 for (int i = 0; i < mRunningInstalls.size(); i++) {
12539                     final PostInstallData data = mRunningInstalls.valueAt(i);
12540                     if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12541                         continue;
12542                     }
12543                     if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12544                         // right package; but is it for the right user?
12545                         for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12546                             if (userId == data.res.newUsers[uIndex]) {
12547                                 if (DEBUG_BACKUP) {
12548                                     Slog.i(TAG, "Package " + pkgName
12549                                             + " being restored so deferring FIRST_LAUNCH");
12550                                 }
12551                                 return;
12552                             }
12553                         }
12554                     }
12555                 }
12556                 // didn't find it, so not being restored
12557                 if (DEBUG_BACKUP) {
12558                     Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12559                 }
12560                 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12561             }
12562         });
12563     }
12564
12565     private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12566         sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12567                 installerPkg, null, userIds);
12568     }
12569
12570     private abstract class HandlerParams {
12571         private static final int MAX_RETRIES = 4;
12572
12573         /**
12574          * Number of times startCopy() has been attempted and had a non-fatal
12575          * error.
12576          */
12577         private int mRetries = 0;
12578
12579         /** User handle for the user requesting the information or installation. */
12580         private final UserHandle mUser;
12581         String traceMethod;
12582         int traceCookie;
12583
12584         HandlerParams(UserHandle user) {
12585             mUser = user;
12586         }
12587
12588         UserHandle getUser() {
12589             return mUser;
12590         }
12591
12592         HandlerParams setTraceMethod(String traceMethod) {
12593             this.traceMethod = traceMethod;
12594             return this;
12595         }
12596
12597         HandlerParams setTraceCookie(int traceCookie) {
12598             this.traceCookie = traceCookie;
12599             return this;
12600         }
12601
12602         final boolean startCopy() {
12603             boolean res;
12604             try {
12605                 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12606
12607                 if (++mRetries > MAX_RETRIES) {
12608                     Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12609                     mHandler.sendEmptyMessage(MCS_GIVE_UP);
12610                     handleServiceError();
12611                     return false;
12612                 } else {
12613                     handleStartCopy();
12614                     res = true;
12615                 }
12616             } catch (RemoteException e) {
12617                 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12618                 mHandler.sendEmptyMessage(MCS_RECONNECT);
12619                 res = false;
12620             }
12621             handleReturnCode();
12622             return res;
12623         }
12624
12625         final void serviceError() {
12626             if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12627             handleServiceError();
12628             handleReturnCode();
12629         }
12630
12631         abstract void handleStartCopy() throws RemoteException;
12632         abstract void handleServiceError();
12633         abstract void handleReturnCode();
12634     }
12635
12636     class MeasureParams extends HandlerParams {
12637         private final PackageStats mStats;
12638         private boolean mSuccess;
12639
12640         private final IPackageStatsObserver mObserver;
12641
12642         public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12643             super(new UserHandle(stats.userHandle));
12644             mObserver = observer;
12645             mStats = stats;
12646         }
12647
12648         @Override
12649         public String toString() {
12650             return "MeasureParams{"
12651                 + Integer.toHexString(System.identityHashCode(this))
12652                 + " " + mStats.packageName + "}";
12653         }
12654
12655         @Override
12656         void handleStartCopy() throws RemoteException {
12657             synchronized (mInstallLock) {
12658                 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12659             }
12660
12661             if (mSuccess) {
12662                 boolean mounted = false;
12663                 try {
12664                     final String status = Environment.getExternalStorageState();
12665                     mounted = (Environment.MEDIA_MOUNTED.equals(status)
12666                             || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12667                 } catch (Exception e) {
12668                 }
12669
12670                 if (mounted) {
12671                     final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12672
12673                     mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12674                             userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12675
12676                     mStats.externalDataSize = calculateDirectorySize(mContainerService,
12677                             userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12678
12679                     // Always subtract cache size, since it's a subdirectory
12680                     mStats.externalDataSize -= mStats.externalCacheSize;
12681
12682                     mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12683                             userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12684
12685                     mStats.externalObbSize = calculateDirectorySize(mContainerService,
12686                             userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12687                 }
12688             }
12689         }
12690
12691         @Override
12692         void handleReturnCode() {
12693             if (mObserver != null) {
12694                 try {
12695                     mObserver.onGetStatsCompleted(mStats, mSuccess);
12696                 } catch (RemoteException e) {
12697                     Slog.i(TAG, "Observer no longer exists.");
12698                 }
12699             }
12700         }
12701
12702         @Override
12703         void handleServiceError() {
12704             Slog.e(TAG, "Could not measure application " + mStats.packageName
12705                             + " external storage");
12706         }
12707     }
12708
12709     private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12710             throws RemoteException {
12711         long result = 0;
12712         for (File path : paths) {
12713             result += mcs.calculateDirectorySize(path.getAbsolutePath());
12714         }
12715         return result;
12716     }
12717
12718     private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12719         for (File path : paths) {
12720             try {
12721                 mcs.clearDirectory(path.getAbsolutePath());
12722             } catch (RemoteException e) {
12723             }
12724         }
12725     }
12726
12727     static class OriginInfo {
12728         /**
12729          * Location where install is coming from, before it has been
12730          * copied/renamed into place. This could be a single monolithic APK
12731          * file, or a cluster directory. This location may be untrusted.
12732          */
12733         final File file;
12734         final String cid;
12735
12736         /**
12737          * Flag indicating that {@link #file} or {@link #cid} has already been
12738          * staged, meaning downstream users don't need to defensively copy the
12739          * contents.
12740          */
12741         final boolean staged;
12742
12743         /**
12744          * Flag indicating that {@link #file} or {@link #cid} is an already
12745          * installed app that is being moved.
12746          */
12747         final boolean existing;
12748
12749         final String resolvedPath;
12750         final File resolvedFile;
12751
12752         static OriginInfo fromNothing() {
12753             return new OriginInfo(null, null, false, false);
12754         }
12755
12756         static OriginInfo fromUntrustedFile(File file) {
12757             return new OriginInfo(file, null, false, false);
12758         }
12759
12760         static OriginInfo fromExistingFile(File file) {
12761             return new OriginInfo(file, null, false, true);
12762         }
12763
12764         static OriginInfo fromStagedFile(File file) {
12765             return new OriginInfo(file, null, true, false);
12766         }
12767
12768         static OriginInfo fromStagedContainer(String cid) {
12769             return new OriginInfo(null, cid, true, false);
12770         }
12771
12772         private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12773             this.file = file;
12774             this.cid = cid;
12775             this.staged = staged;
12776             this.existing = existing;
12777
12778             if (cid != null) {
12779                 resolvedPath = PackageHelper.getSdDir(cid);
12780                 resolvedFile = new File(resolvedPath);
12781             } else if (file != null) {
12782                 resolvedPath = file.getAbsolutePath();
12783                 resolvedFile = file;
12784             } else {
12785                 resolvedPath = null;
12786                 resolvedFile = null;
12787             }
12788         }
12789     }
12790
12791     static class MoveInfo {
12792         final int moveId;
12793         final String fromUuid;
12794         final String toUuid;
12795         final String packageName;
12796         final String dataAppName;
12797         final int appId;
12798         final String seinfo;
12799         final int targetSdkVersion;
12800
12801         public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12802                 String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12803             this.moveId = moveId;
12804             this.fromUuid = fromUuid;
12805             this.toUuid = toUuid;
12806             this.packageName = packageName;
12807             this.dataAppName = dataAppName;
12808             this.appId = appId;
12809             this.seinfo = seinfo;
12810             this.targetSdkVersion = targetSdkVersion;
12811         }
12812     }
12813
12814     static class VerificationInfo {
12815         /** A constant used to indicate that a uid value is not present. */
12816         public static final int NO_UID = -1;
12817
12818         /** URI referencing where the package was downloaded from. */
12819         final Uri originatingUri;
12820
12821         /** HTTP referrer URI associated with the originatingURI. */
12822         final Uri referrer;
12823
12824         /** UID of the application that the install request originated from. */
12825         final int originatingUid;
12826
12827         /** UID of application requesting the install */
12828         final int installerUid;
12829
12830         VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12831             this.originatingUri = originatingUri;
12832             this.referrer = referrer;
12833             this.originatingUid = originatingUid;
12834             this.installerUid = installerUid;
12835         }
12836     }
12837
12838     class InstallParams extends HandlerParams {
12839         final OriginInfo origin;
12840         final MoveInfo move;
12841         final IPackageInstallObserver2 observer;
12842         int installFlags;
12843         final String installerPackageName;
12844         final String volumeUuid;
12845         private InstallArgs mArgs;
12846         private int mRet;
12847         final String packageAbiOverride;
12848         final String[] grantedRuntimePermissions;
12849         final VerificationInfo verificationInfo;
12850         final Certificate[][] certificates;
12851
12852         InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12853                 int installFlags, String installerPackageName, String volumeUuid,
12854                 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12855                 String[] grantedPermissions, Certificate[][] certificates) {
12856             super(user);
12857             this.origin = origin;
12858             this.move = move;
12859             this.observer = observer;
12860             this.installFlags = installFlags;
12861             this.installerPackageName = installerPackageName;
12862             this.volumeUuid = volumeUuid;
12863             this.verificationInfo = verificationInfo;
12864             this.packageAbiOverride = packageAbiOverride;
12865             this.grantedRuntimePermissions = grantedPermissions;
12866             this.certificates = certificates;
12867         }
12868
12869         @Override
12870         public String toString() {
12871             return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12872                     + " file=" + origin.file + " cid=" + origin.cid + "}";
12873         }
12874
12875         private int installLocationPolicy(PackageInfoLite pkgLite) {
12876             String packageName = pkgLite.packageName;
12877             int installLocation = pkgLite.installLocation;
12878             boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12879             // reader
12880             synchronized (mPackages) {
12881                 // Currently installed package which the new package is attempting to replace or
12882                 // null if no such package is installed.
12883                 PackageParser.Package installedPkg = mPackages.get(packageName);
12884                 // Package which currently owns the data which the new package will own if installed.
12885                 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12886                 // will be null whereas dataOwnerPkg will contain information about the package
12887                 // which was uninstalled while keeping its data.
12888                 PackageParser.Package dataOwnerPkg = installedPkg;
12889                 if (dataOwnerPkg  == null) {
12890                     PackageSetting ps = mSettings.mPackages.get(packageName);
12891                     if (ps != null) {
12892                         dataOwnerPkg = ps.pkg;
12893                     }
12894                 }
12895
12896                 if (dataOwnerPkg != null) {
12897                     // If installed, the package will get access to data left on the device by its
12898                     // predecessor. As a security measure, this is permited only if this is not a
12899                     // version downgrade or if the predecessor package is marked as debuggable and
12900                     // a downgrade is explicitly requested.
12901                     //
12902                     // On debuggable platform builds, downgrades are permitted even for
12903                     // non-debuggable packages to make testing easier. Debuggable platform builds do
12904                     // not offer security guarantees and thus it's OK to disable some security
12905                     // mechanisms to make debugging/testing easier on those builds. However, even on
12906                     // debuggable builds downgrades of packages are permitted only if requested via
12907                     // installFlags. This is because we aim to keep the behavior of debuggable
12908                     // platform builds as close as possible to the behavior of non-debuggable
12909                     // platform builds.
12910                     final boolean downgradeRequested =
12911                             (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12912                     final boolean packageDebuggable =
12913                                 (dataOwnerPkg.applicationInfo.flags
12914                                         & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12915                     final boolean downgradePermitted =
12916                             (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12917                     if (!downgradePermitted) {
12918                         try {
12919                             checkDowngrade(dataOwnerPkg, pkgLite);
12920                         } catch (PackageManagerException e) {
12921                             Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12922                             return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12923                         }
12924                     }
12925                 }
12926
12927                 if (installedPkg != null) {
12928                     if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12929                         // Check for updated system application.
12930                         if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12931                             if (onSd) {
12932                                 Slog.w(TAG, "Cannot install update to system app on sdcard");
12933                                 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12934                             }
12935                             return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12936                         } else {
12937                             if (onSd) {
12938                                 // Install flag overrides everything.
12939                                 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12940                             }
12941                             // If current upgrade specifies particular preference
12942                             if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12943                                 // Application explicitly specified internal.
12944                                 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12945                             } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12946                                 // App explictly prefers external. Let policy decide
12947                             } else {
12948                                 // Prefer previous location
12949                                 if (isExternal(installedPkg)) {
12950                                     return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12951                                 }
12952                                 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12953                             }
12954                         }
12955                     } else {
12956                         // Invalid install. Return error code
12957                         return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12958                     }
12959                 }
12960             }
12961             // All the special cases have been taken care of.
12962             // Return result based on recommended install location.
12963             if (onSd) {
12964                 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12965             }
12966             return pkgLite.recommendedInstallLocation;
12967         }
12968
12969         /*
12970          * Invoke remote method to get package information and install
12971          * location values. Override install location based on default
12972          * policy if needed and then create install arguments based
12973          * on the install location.
12974          */
12975         public void handleStartCopy() throws RemoteException {
12976             int ret = PackageManager.INSTALL_SUCCEEDED;
12977
12978             // If we're already staged, we've firmly committed to an install location
12979             if (origin.staged) {
12980                 if (origin.file != null) {
12981                     installFlags |= PackageManager.INSTALL_INTERNAL;
12982                     installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12983                 } else if (origin.cid != null) {
12984                     installFlags |= PackageManager.INSTALL_EXTERNAL;
12985                     installFlags &= ~PackageManager.INSTALL_INTERNAL;
12986                 } else {
12987                     throw new IllegalStateException("Invalid stage location");
12988                 }
12989             }
12990
12991             final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12992             final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12993             final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12994             PackageInfoLite pkgLite = null;
12995
12996             if (onInt && onSd) {
12997                 // Check if both bits are set.
12998                 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12999                 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13000             } else if (onSd && ephemeral) {
13001                 Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
13002                 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13003             } else {
13004                 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13005                         packageAbiOverride);
13006
13007                 if (DEBUG_EPHEMERAL && ephemeral) {
13008                     Slog.v(TAG, "pkgLite for install: " + pkgLite);
13009                 }
13010
13011                 /*
13012                  * If we have too little free space, try to free cache
13013                  * before giving up.
13014                  */
13015                 if (!origin.staged && pkgLite.recommendedInstallLocation
13016                         == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13017                     // TODO: focus freeing disk space on the target device
13018                     final StorageManager storage = StorageManager.from(mContext);
13019                     final long lowThreshold = storage.getStorageLowBytes(
13020                             Environment.getDataDirectory());
13021
13022                     final long sizeBytes = mContainerService.calculateInstalledSize(
13023                             origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13024
13025                     try {
13026                         mInstaller.freeCache(null, sizeBytes + lowThreshold);
13027                         pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13028                                 installFlags, packageAbiOverride);
13029                     } catch (InstallerException e) {
13030                         Slog.w(TAG, "Failed to free cache", e);
13031                     }
13032
13033                     /*
13034                      * The cache free must have deleted the file we
13035                      * downloaded to install.
13036                      *
13037                      * TODO: fix the "freeCache" call to not delete
13038                      *       the file we care about.
13039                      */
13040                     if (pkgLite.recommendedInstallLocation
13041                             == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13042                         pkgLite.recommendedInstallLocation
13043                             = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13044                     }
13045                 }
13046             }
13047
13048             if (ret == PackageManager.INSTALL_SUCCEEDED) {
13049                 int loc = pkgLite.recommendedInstallLocation;
13050                 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13051                     ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13052                 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13053                     ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13054                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13055                     ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13056                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13057                     ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13058                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13059                     ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13060                 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13061                     ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13062                 } else {
13063                     // Override with defaults if needed.
13064                     loc = installLocationPolicy(pkgLite);
13065                     if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13066                         ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13067                     } else if (!onSd && !onInt) {
13068                         // Override install location with flags
13069                         if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13070                             // Set the flag to install on external media.
13071                             installFlags |= PackageManager.INSTALL_EXTERNAL;
13072                             installFlags &= ~PackageManager.INSTALL_INTERNAL;
13073                         } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13074                             if (DEBUG_EPHEMERAL) {
13075                                 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13076                             }
13077                             installFlags |= PackageManager.INSTALL_EPHEMERAL;
13078                             installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13079                                     |PackageManager.INSTALL_INTERNAL);
13080                         } else {
13081                             // Make sure the flag for installing on external
13082                             // media is unset
13083                             installFlags |= PackageManager.INSTALL_INTERNAL;
13084                             installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13085                         }
13086                     }
13087                 }
13088             }
13089
13090             final InstallArgs args = createInstallArgs(this);
13091             mArgs = args;
13092
13093             if (ret == PackageManager.INSTALL_SUCCEEDED) {
13094                 // TODO: http://b/22976637
13095                 // Apps installed for "all" users use the device owner to verify the app
13096                 UserHandle verifierUser = getUser();
13097                 if (verifierUser == UserHandle.ALL) {
13098                     verifierUser = UserHandle.SYSTEM;
13099                 }
13100
13101                 /*
13102                  * Determine if we have any installed package verifiers. If we
13103                  * do, then we'll defer to them to verify the packages.
13104                  */
13105                 final int requiredUid = mRequiredVerifierPackage == null ? -1
13106                         : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13107                                 verifierUser.getIdentifier());
13108                 if (!origin.existing && requiredUid != -1
13109                         && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13110                     final Intent verification = new Intent(
13111                             Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13112                     verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13113                     verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13114                             PACKAGE_MIME_TYPE);
13115                     verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13116
13117                     // Query all live verifiers based on current user state
13118                     final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13119                             PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13120
13121                     if (DEBUG_VERIFY) {
13122                         Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13123                                 + verification.toString() + " with " + pkgLite.verifiers.length
13124                                 + " optional verifiers");
13125                     }
13126
13127                     final int verificationId = mPendingVerificationToken++;
13128
13129                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13130
13131                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13132                             installerPackageName);
13133
13134                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13135                             installFlags);
13136
13137                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13138                             pkgLite.packageName);
13139
13140                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13141                             pkgLite.versionCode);
13142
13143                     if (verificationInfo != null) {
13144                         if (verificationInfo.originatingUri != null) {
13145                             verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13146                                     verificationInfo.originatingUri);
13147                         }
13148                         if (verificationInfo.referrer != null) {
13149                             verification.putExtra(Intent.EXTRA_REFERRER,
13150                                     verificationInfo.referrer);
13151                         }
13152                         if (verificationInfo.originatingUid >= 0) {
13153                             verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13154                                     verificationInfo.originatingUid);
13155                         }
13156                         if (verificationInfo.installerUid >= 0) {
13157                             verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13158                                     verificationInfo.installerUid);
13159                         }
13160                     }
13161
13162                     final PackageVerificationState verificationState = new PackageVerificationState(
13163                             requiredUid, args);
13164
13165                     mPendingVerification.append(verificationId, verificationState);
13166
13167                     final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13168                             receivers, verificationState);
13169
13170                     /*
13171                      * If any sufficient verifiers were listed in the package
13172                      * manifest, attempt to ask them.
13173                      */
13174                     if (sufficientVerifiers != null) {
13175                         final int N = sufficientVerifiers.size();
13176                         if (N == 0) {
13177                             Slog.i(TAG, "Additional verifiers required, but none installed.");
13178                             ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13179                         } else {
13180                             for (int i = 0; i < N; i++) {
13181                                 final ComponentName verifierComponent = sufficientVerifiers.get(i);
13182
13183                                 final Intent sufficientIntent = new Intent(verification);
13184                                 sufficientIntent.setComponent(verifierComponent);
13185                                 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13186                             }
13187                         }
13188                     }
13189
13190                     final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13191                             mRequiredVerifierPackage, receivers);
13192                     if (ret == PackageManager.INSTALL_SUCCEEDED
13193                             && mRequiredVerifierPackage != null) {
13194                         Trace.asyncTraceBegin(
13195                                 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13196                         /*
13197                          * Send the intent to the required verification agent,
13198                          * but only start the verification timeout after the
13199                          * target BroadcastReceivers have run.
13200                          */
13201                         verification.setComponent(requiredVerifierComponent);
13202                         mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13203                                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13204                                 new BroadcastReceiver() {
13205                                     @Override
13206                                     public void onReceive(Context context, Intent intent) {
13207                                         final Message msg = mHandler
13208                                                 .obtainMessage(CHECK_PENDING_VERIFICATION);
13209                                         msg.arg1 = verificationId;
13210                                         mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13211                                     }
13212                                 }, null, 0, null, null);
13213
13214                         /*
13215                          * We don't want the copy to proceed until verification
13216                          * succeeds, so null out this field.
13217                          */
13218                         mArgs = null;
13219                     }
13220                 } else {
13221                     /*
13222                      * No package verification is enabled, so immediately start
13223                      * the remote call to initiate copy using temporary file.
13224                      */
13225                     ret = args.copyApk(mContainerService, true);
13226                 }
13227             }
13228
13229             mRet = ret;
13230         }
13231
13232         @Override
13233         void handleReturnCode() {
13234             // If mArgs is null, then MCS couldn't be reached. When it
13235             // reconnects, it will try again to install. At that point, this
13236             // will succeed.
13237             if (mArgs != null) {
13238                 processPendingInstall(mArgs, mRet);
13239             }
13240         }
13241
13242         @Override
13243         void handleServiceError() {
13244             mArgs = createInstallArgs(this);
13245             mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13246         }
13247
13248         public boolean isForwardLocked() {
13249             return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13250         }
13251     }
13252
13253     /**
13254      * Used during creation of InstallArgs
13255      *
13256      * @param installFlags package installation flags
13257      * @return true if should be installed on external storage
13258      */
13259     private static boolean installOnExternalAsec(int installFlags) {
13260         if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13261             return false;
13262         }
13263         if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13264             return true;
13265         }
13266         return false;
13267     }
13268
13269     /**
13270      * Used during creation of InstallArgs
13271      *
13272      * @param installFlags package installation flags
13273      * @return true if should be installed as forward locked
13274      */
13275     private static boolean installForwardLocked(int installFlags) {
13276         return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13277     }
13278
13279     private InstallArgs createInstallArgs(InstallParams params) {
13280         if (params.move != null) {
13281             return new MoveInstallArgs(params);
13282         } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13283             return new AsecInstallArgs(params);
13284         } else {
13285             return new FileInstallArgs(params);
13286         }
13287     }
13288
13289     /**
13290      * Create args that describe an existing installed package. Typically used
13291      * when cleaning up old installs, or used as a move source.
13292      */
13293     private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13294             String resourcePath, String[] instructionSets) {
13295         final boolean isInAsec;
13296         if (installOnExternalAsec(installFlags)) {
13297             /* Apps on SD card are always in ASEC containers. */
13298             isInAsec = true;
13299         } else if (installForwardLocked(installFlags)
13300                 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13301             /*
13302              * Forward-locked apps are only in ASEC containers if they're the
13303              * new style
13304              */
13305             isInAsec = true;
13306         } else {
13307             isInAsec = false;
13308         }
13309
13310         if (isInAsec) {
13311             return new AsecInstallArgs(codePath, instructionSets,
13312                     installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13313         } else {
13314             return new FileInstallArgs(codePath, resourcePath, instructionSets);
13315         }
13316     }
13317
13318     static abstract class InstallArgs {
13319         /** @see InstallParams#origin */
13320         final OriginInfo origin;
13321         /** @see InstallParams#move */
13322         final MoveInfo move;
13323
13324         final IPackageInstallObserver2 observer;
13325         // Always refers to PackageManager flags only
13326         final int installFlags;
13327         final String installerPackageName;
13328         final String volumeUuid;
13329         final UserHandle user;
13330         final String abiOverride;
13331         final String[] installGrantPermissions;
13332         /** If non-null, drop an async trace when the install completes */
13333         final String traceMethod;
13334         final int traceCookie;
13335         final Certificate[][] certificates;
13336
13337         // The list of instruction sets supported by this app. This is currently
13338         // only used during the rmdex() phase to clean up resources. We can get rid of this
13339         // if we move dex files under the common app path.
13340         /* nullable */ String[] instructionSets;
13341
13342         InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13343                 int installFlags, String installerPackageName, String volumeUuid,
13344                 UserHandle user, String[] instructionSets,
13345                 String abiOverride, String[] installGrantPermissions,
13346                 String traceMethod, int traceCookie, Certificate[][] certificates) {
13347             this.origin = origin;
13348             this.move = move;
13349             this.installFlags = installFlags;
13350             this.observer = observer;
13351             this.installerPackageName = installerPackageName;
13352             this.volumeUuid = volumeUuid;
13353             this.user = user;
13354             this.instructionSets = instructionSets;
13355             this.abiOverride = abiOverride;
13356             this.installGrantPermissions = installGrantPermissions;
13357             this.traceMethod = traceMethod;
13358             this.traceCookie = traceCookie;
13359             this.certificates = certificates;
13360         }
13361
13362         abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13363         abstract int doPreInstall(int status);
13364
13365         /**
13366          * Rename package into final resting place. All paths on the given
13367          * scanned package should be updated to reflect the rename.
13368          */
13369         abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13370         abstract int doPostInstall(int status, int uid);
13371
13372         /** @see PackageSettingBase#codePathString */
13373         abstract String getCodePath();
13374         /** @see PackageSettingBase#resourcePathString */
13375         abstract String getResourcePath();
13376
13377         // Need installer lock especially for dex file removal.
13378         abstract void cleanUpResourcesLI();
13379         abstract boolean doPostDeleteLI(boolean delete);
13380
13381         /**
13382          * Called before the source arguments are copied. This is used mostly
13383          * for MoveParams when it needs to read the source file to put it in the
13384          * destination.
13385          */
13386         int doPreCopy() {
13387             return PackageManager.INSTALL_SUCCEEDED;
13388         }
13389
13390         /**
13391          * Called after the source arguments are copied. This is used mostly for
13392          * MoveParams when it needs to read the source file to put it in the
13393          * destination.
13394          */
13395         int doPostCopy(int uid) {
13396             return PackageManager.INSTALL_SUCCEEDED;
13397         }
13398
13399         protected boolean isFwdLocked() {
13400             return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13401         }
13402
13403         protected boolean isExternalAsec() {
13404             return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13405         }
13406
13407         protected boolean isEphemeral() {
13408             return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13409         }
13410
13411         UserHandle getUser() {
13412             return user;
13413         }
13414     }
13415
13416     private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13417         if (!allCodePaths.isEmpty()) {
13418             if (instructionSets == null) {
13419                 throw new IllegalStateException("instructionSet == null");
13420             }
13421             String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13422             for (String codePath : allCodePaths) {
13423                 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13424                     try {
13425                         mInstaller.rmdex(codePath, dexCodeInstructionSet);
13426                     } catch (InstallerException ignored) {
13427                     }
13428                 }
13429             }
13430         }
13431     }
13432
13433     /**
13434      * Logic to handle installation of non-ASEC applications, including copying
13435      * and renaming logic.
13436      */
13437     class FileInstallArgs extends InstallArgs {
13438         private File codeFile;
13439         private File resourceFile;
13440
13441         // Example topology:
13442         // /data/app/com.example/base.apk
13443         // /data/app/com.example/split_foo.apk
13444         // /data/app/com.example/lib/arm/libfoo.so
13445         // /data/app/com.example/lib/arm64/libfoo.so
13446         // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13447
13448         /** New install */
13449         FileInstallArgs(InstallParams params) {
13450             super(params.origin, params.move, params.observer, params.installFlags,
13451                     params.installerPackageName, params.volumeUuid,
13452                     params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13453                     params.grantedRuntimePermissions,
13454                     params.traceMethod, params.traceCookie, params.certificates);
13455             if (isFwdLocked()) {
13456                 throw new IllegalArgumentException("Forward locking only supported in ASEC");
13457             }
13458         }
13459
13460         /** Existing install */
13461         FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13462             super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13463                     null, null, null, 0, null /*certificates*/);
13464             this.codeFile = (codePath != null) ? new File(codePath) : null;
13465             this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13466         }
13467
13468         int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13469             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13470             try {
13471                 return doCopyApk(imcs, temp);
13472             } finally {
13473                 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13474             }
13475         }
13476
13477         private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13478             if (origin.staged) {
13479                 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13480                 codeFile = origin.file;
13481                 resourceFile = origin.file;
13482                 return PackageManager.INSTALL_SUCCEEDED;
13483             }
13484
13485             try {
13486                 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13487                 final File tempDir =
13488                         mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13489                 codeFile = tempDir;
13490                 resourceFile = tempDir;
13491             } catch (IOException e) {
13492                 Slog.w(TAG, "Failed to create copy file: " + e);
13493                 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13494             }
13495
13496             final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13497                 @Override
13498                 public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13499                     if (!FileUtils.isValidExtFilename(name)) {
13500                         throw new IllegalArgumentException("Invalid filename: " + name);
13501                     }
13502                     try {
13503                         final File file = new File(codeFile, name);
13504                         final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13505                                 O_RDWR | O_CREAT, 0644);
13506                         Os.chmod(file.getAbsolutePath(), 0644);
13507                         return new ParcelFileDescriptor(fd);
13508                     } catch (ErrnoException e) {
13509                         throw new RemoteException("Failed to open: " + e.getMessage());
13510                     }
13511                 }
13512             };
13513
13514             int ret = PackageManager.INSTALL_SUCCEEDED;
13515             ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13516             if (ret != PackageManager.INSTALL_SUCCEEDED) {
13517                 Slog.e(TAG, "Failed to copy package");
13518                 return ret;
13519             }
13520
13521             final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13522             NativeLibraryHelper.Handle handle = null;
13523             try {
13524                 handle = NativeLibraryHelper.Handle.create(codeFile);
13525                 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13526                         abiOverride);
13527             } catch (IOException e) {
13528                 Slog.e(TAG, "Copying native libraries failed", e);
13529                 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13530             } finally {
13531                 IoUtils.closeQuietly(handle);
13532             }
13533
13534             return ret;
13535         }
13536
13537         int doPreInstall(int status) {
13538             if (status != PackageManager.INSTALL_SUCCEEDED) {
13539                 cleanUp();
13540             }
13541             return status;
13542         }
13543
13544         boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13545             if (status != PackageManager.INSTALL_SUCCEEDED) {
13546                 cleanUp();
13547                 return false;
13548             }
13549
13550             final File targetDir = codeFile.getParentFile();
13551             final File beforeCodeFile = codeFile;
13552             final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13553
13554             if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13555             try {
13556                 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13557             } catch (ErrnoException e) {
13558                 Slog.w(TAG, "Failed to rename", e);
13559                 return false;
13560             }
13561
13562             if (!SELinux.restoreconRecursive(afterCodeFile)) {
13563                 Slog.w(TAG, "Failed to restorecon");
13564                 return false;
13565             }
13566
13567             // Reflect the rename internally
13568             codeFile = afterCodeFile;
13569             resourceFile = afterCodeFile;
13570
13571             // Reflect the rename in scanned details
13572             pkg.setCodePath(afterCodeFile.getAbsolutePath());
13573             pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13574                     afterCodeFile, pkg.baseCodePath));
13575             pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13576                     afterCodeFile, pkg.splitCodePaths));
13577
13578             // Reflect the rename in app info
13579             pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13580             pkg.setApplicationInfoCodePath(pkg.codePath);
13581             pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13582             pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13583             pkg.setApplicationInfoResourcePath(pkg.codePath);
13584             pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13585             pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13586
13587             return true;
13588         }
13589
13590         int doPostInstall(int status, int uid) {
13591             if (status != PackageManager.INSTALL_SUCCEEDED) {
13592                 cleanUp();
13593             }
13594             return status;
13595         }
13596
13597         @Override
13598         String getCodePath() {
13599             return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13600         }
13601
13602         @Override
13603         String getResourcePath() {
13604             return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13605         }
13606
13607         private boolean cleanUp() {
13608             if (codeFile == null || !codeFile.exists()) {
13609                 return false;
13610             }
13611
13612             removeCodePathLI(codeFile);
13613
13614             if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13615                 resourceFile.delete();
13616             }
13617
13618             return true;
13619         }
13620
13621         void cleanUpResourcesLI() {
13622             // Try enumerating all code paths before deleting
13623             List<String> allCodePaths = Collections.EMPTY_LIST;
13624             if (codeFile != null && codeFile.exists()) {
13625                 try {
13626                     final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13627                     allCodePaths = pkg.getAllCodePaths();
13628                 } catch (PackageParserException e) {
13629                     // Ignored; we tried our best
13630                 }
13631             }
13632
13633             cleanUp();
13634             removeDexFiles(allCodePaths, instructionSets);
13635         }
13636
13637         boolean doPostDeleteLI(boolean delete) {
13638             // XXX err, shouldn't we respect the delete flag?
13639             cleanUpResourcesLI();
13640             return true;
13641         }
13642     }
13643
13644     private boolean isAsecExternal(String cid) {
13645         final String asecPath = PackageHelper.getSdFilesystem(cid);
13646         return !asecPath.startsWith(mAsecInternalPath);
13647     }
13648
13649     private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13650             PackageManagerException {
13651         if (copyRet < 0) {
13652             if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13653                     copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13654                 throw new PackageManagerException(copyRet, message);
13655             }
13656         }
13657     }
13658
13659     /**
13660      * Extract the MountService "container ID" from the full code path of an
13661      * .apk.
13662      */
13663     static String cidFromCodePath(String fullCodePath) {
13664         int eidx = fullCodePath.lastIndexOf("/");
13665         String subStr1 = fullCodePath.substring(0, eidx);
13666         int sidx = subStr1.lastIndexOf("/");
13667         return subStr1.substring(sidx+1, eidx);
13668     }
13669
13670     /**
13671      * Logic to handle installation of ASEC applications, including copying and
13672      * renaming logic.
13673      */
13674     class AsecInstallArgs extends InstallArgs {
13675         static final String RES_FILE_NAME = "pkg.apk";
13676         static final String PUBLIC_RES_FILE_NAME = "res.zip";
13677
13678         String cid;
13679         String packagePath;
13680         String resourcePath;
13681
13682         /** New install */
13683         AsecInstallArgs(InstallParams params) {
13684             super(params.origin, params.move, params.observer, params.installFlags,
13685                     params.installerPackageName, params.volumeUuid,
13686                     params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13687                     params.grantedRuntimePermissions,
13688                     params.traceMethod, params.traceCookie, params.certificates);
13689         }
13690
13691         /** Existing install */
13692         AsecInstallArgs(String fullCodePath, String[] instructionSets,
13693                         boolean isExternal, boolean isForwardLocked) {
13694             super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13695               | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13696                     instructionSets, null, null, null, 0, null /*certificates*/);
13697             // Hackily pretend we're still looking at a full code path
13698             if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13699                 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13700             }
13701
13702             // Extract cid from fullCodePath
13703             int eidx = fullCodePath.lastIndexOf("/");
13704             String subStr1 = fullCodePath.substring(0, eidx);
13705             int sidx = subStr1.lastIndexOf("/");
13706             cid = subStr1.substring(sidx+1, eidx);
13707             setMountPath(subStr1);
13708         }
13709
13710         AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13711             super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13712               | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13713                     instructionSets, null, null, null, 0, null /*certificates*/);
13714             this.cid = cid;
13715             setMountPath(PackageHelper.getSdDir(cid));
13716         }
13717
13718         void createCopyFile() {
13719             cid = mInstallerService.allocateExternalStageCidLegacy();
13720         }
13721
13722         int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13723             if (origin.staged && origin.cid != null) {
13724                 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13725                 cid = origin.cid;
13726                 setMountPath(PackageHelper.getSdDir(cid));
13727                 return PackageManager.INSTALL_SUCCEEDED;
13728             }
13729
13730             if (temp) {
13731                 createCopyFile();
13732             } else {
13733                 /*
13734                  * Pre-emptively destroy the container since it's destroyed if
13735                  * copying fails due to it existing anyway.
13736                  */
13737                 PackageHelper.destroySdDir(cid);
13738             }
13739
13740             final String newMountPath = imcs.copyPackageToContainer(
13741                     origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13742                     isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13743
13744             if (newMountPath != null) {
13745                 setMountPath(newMountPath);
13746                 return PackageManager.INSTALL_SUCCEEDED;
13747             } else {
13748                 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13749             }
13750         }
13751
13752         @Override
13753         String getCodePath() {
13754             return packagePath;
13755         }
13756
13757         @Override
13758         String getResourcePath() {
13759             return resourcePath;
13760         }
13761
13762         int doPreInstall(int status) {
13763             if (status != PackageManager.INSTALL_SUCCEEDED) {
13764                 // Destroy container
13765                 PackageHelper.destroySdDir(cid);
13766             } else {
13767                 boolean mounted = PackageHelper.isContainerMounted(cid);
13768                 if (!mounted) {
13769                     String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13770                             Process.SYSTEM_UID);
13771                     if (newMountPath != null) {
13772                         setMountPath(newMountPath);
13773                     } else {
13774                         return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13775                     }
13776                 }
13777             }
13778             return status;
13779         }
13780
13781         boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13782             String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13783             String newMountPath = null;
13784             if (PackageHelper.isContainerMounted(cid)) {
13785                 // Unmount the container
13786                 if (!PackageHelper.unMountSdDir(cid)) {
13787                     Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13788                     return false;
13789                 }
13790             }
13791             if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13792                 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13793                         " which might be stale. Will try to clean up.");
13794                 // Clean up the stale container and proceed to recreate.
13795                 if (!PackageHelper.destroySdDir(newCacheId)) {
13796                     Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13797                     return false;
13798                 }
13799                 // Successfully cleaned up stale container. Try to rename again.
13800                 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13801                     Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13802                             + " inspite of cleaning it up.");
13803                     return false;
13804                 }
13805             }
13806             if (!PackageHelper.isContainerMounted(newCacheId)) {
13807                 Slog.w(TAG, "Mounting container " + newCacheId);
13808                 newMountPath = PackageHelper.mountSdDir(newCacheId,
13809                         getEncryptKey(), Process.SYSTEM_UID);
13810             } else {
13811                 newMountPath = PackageHelper.getSdDir(newCacheId);
13812             }
13813             if (newMountPath == null) {
13814                 Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13815                 return false;
13816             }
13817             Log.i(TAG, "Succesfully renamed " + cid +
13818                     " to " + newCacheId +
13819                     " at new path: " + newMountPath);
13820             cid = newCacheId;
13821
13822             final File beforeCodeFile = new File(packagePath);
13823             setMountPath(newMountPath);
13824             final File afterCodeFile = new File(packagePath);
13825
13826             // Reflect the rename in scanned details
13827             pkg.setCodePath(afterCodeFile.getAbsolutePath());
13828             pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13829                     afterCodeFile, pkg.baseCodePath));
13830             pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13831                     afterCodeFile, pkg.splitCodePaths));
13832
13833             // Reflect the rename in app info
13834             pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13835             pkg.setApplicationInfoCodePath(pkg.codePath);
13836             pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13837             pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13838             pkg.setApplicationInfoResourcePath(pkg.codePath);
13839             pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13840             pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13841
13842             return true;
13843         }
13844
13845         private void setMountPath(String mountPath) {
13846             final File mountFile = new File(mountPath);
13847
13848             final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13849             if (monolithicFile.exists()) {
13850                 packagePath = monolithicFile.getAbsolutePath();
13851                 if (isFwdLocked()) {
13852                     resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13853                 } else {
13854                     resourcePath = packagePath;
13855                 }
13856             } else {
13857                 packagePath = mountFile.getAbsolutePath();
13858                 resourcePath = packagePath;
13859             }
13860         }
13861
13862         int doPostInstall(int status, int uid) {
13863             if (status != PackageManager.INSTALL_SUCCEEDED) {
13864                 cleanUp();
13865             } else {
13866                 final int groupOwner;
13867                 final String protectedFile;
13868                 if (isFwdLocked()) {
13869                     groupOwner = UserHandle.getSharedAppGid(uid);
13870                     protectedFile = RES_FILE_NAME;
13871                 } else {
13872                     groupOwner = -1;
13873                     protectedFile = null;
13874                 }
13875
13876                 if (uid < Process.FIRST_APPLICATION_UID
13877                         || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13878                     Slog.e(TAG, "Failed to finalize " + cid);
13879                     PackageHelper.destroySdDir(cid);
13880                     return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13881                 }
13882
13883                 boolean mounted = PackageHelper.isContainerMounted(cid);
13884                 if (!mounted) {
13885                     PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13886                 }
13887             }
13888             return status;
13889         }
13890
13891         private void cleanUp() {
13892             if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13893
13894             // Destroy secure container
13895             PackageHelper.destroySdDir(cid);
13896         }
13897
13898         private List<String> getAllCodePaths() {
13899             final File codeFile = new File(getCodePath());
13900             if (codeFile != null && codeFile.exists()) {
13901                 try {
13902                     final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13903                     return pkg.getAllCodePaths();
13904                 } catch (PackageParserException e) {
13905                     // Ignored; we tried our best
13906                 }
13907             }
13908             return Collections.EMPTY_LIST;
13909         }
13910
13911         void cleanUpResourcesLI() {
13912             // Enumerate all code paths before deleting
13913             cleanUpResourcesLI(getAllCodePaths());
13914         }
13915
13916         private void cleanUpResourcesLI(List<String> allCodePaths) {
13917             cleanUp();
13918             removeDexFiles(allCodePaths, instructionSets);
13919         }
13920
13921         String getPackageName() {
13922             return getAsecPackageName(cid);
13923         }
13924
13925         boolean doPostDeleteLI(boolean delete) {
13926             if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13927             final List<String> allCodePaths = getAllCodePaths();
13928             boolean mounted = PackageHelper.isContainerMounted(cid);
13929             if (mounted) {
13930                 // Unmount first
13931                 if (PackageHelper.unMountSdDir(cid)) {
13932                     mounted = false;
13933                 }
13934             }
13935             if (!mounted && delete) {
13936                 cleanUpResourcesLI(allCodePaths);
13937             }
13938             return !mounted;
13939         }
13940
13941         @Override
13942         int doPreCopy() {
13943             if (isFwdLocked()) {
13944                 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13945                         MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13946                     return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13947                 }
13948             }
13949
13950             return PackageManager.INSTALL_SUCCEEDED;
13951         }
13952
13953         @Override
13954         int doPostCopy(int uid) {
13955             if (isFwdLocked()) {
13956                 if (uid < Process.FIRST_APPLICATION_UID
13957                         || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13958                                 RES_FILE_NAME)) {
13959                     Slog.e(TAG, "Failed to finalize " + cid);
13960                     PackageHelper.destroySdDir(cid);
13961                     return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13962                 }
13963             }
13964
13965             return PackageManager.INSTALL_SUCCEEDED;
13966         }
13967     }
13968
13969     /**
13970      * Logic to handle movement of existing installed applications.
13971      */
13972     class MoveInstallArgs extends InstallArgs {
13973         private File codeFile;
13974         private File resourceFile;
13975
13976         /** New install */
13977         MoveInstallArgs(InstallParams params) {
13978             super(params.origin, params.move, params.observer, params.installFlags,
13979                     params.installerPackageName, params.volumeUuid,
13980                     params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13981                     params.grantedRuntimePermissions,
13982                     params.traceMethod, params.traceCookie, params.certificates);
13983         }
13984
13985         int copyApk(IMediaContainerService imcs, boolean temp) {
13986             if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13987                     + move.fromUuid + " to " + move.toUuid);
13988             synchronized (mInstaller) {
13989                 try {
13990                     mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13991                             move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13992                 } catch (InstallerException e) {
13993                     Slog.w(TAG, "Failed to move app", e);
13994                     return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13995                 }
13996             }
13997
13998             codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13999             resourceFile = codeFile;
14000             if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14001
14002             return PackageManager.INSTALL_SUCCEEDED;
14003         }
14004
14005         int doPreInstall(int status) {
14006             if (status != PackageManager.INSTALL_SUCCEEDED) {
14007                 cleanUp(move.toUuid);
14008             }
14009             return status;
14010         }
14011
14012         boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14013             if (status != PackageManager.INSTALL_SUCCEEDED) {
14014                 cleanUp(move.toUuid);
14015                 return false;
14016             }
14017
14018             // Reflect the move in app info
14019             pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14020             pkg.setApplicationInfoCodePath(pkg.codePath);
14021             pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14022             pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14023             pkg.setApplicationInfoResourcePath(pkg.codePath);
14024             pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14025             pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14026
14027             return true;
14028         }
14029
14030         int doPostInstall(int status, int uid) {
14031             if (status == PackageManager.INSTALL_SUCCEEDED) {
14032                 cleanUp(move.fromUuid);
14033             } else {
14034                 cleanUp(move.toUuid);
14035             }
14036             return status;
14037         }
14038
14039         @Override
14040         String getCodePath() {
14041             return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14042         }
14043
14044         @Override
14045         String getResourcePath() {
14046             return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14047         }
14048
14049         private boolean cleanUp(String volumeUuid) {
14050             final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14051                     move.dataAppName);
14052             Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14053             final int[] userIds = sUserManager.getUserIds();
14054             synchronized (mInstallLock) {
14055                 // Clean up both app data and code
14056                 // All package moves are frozen until finished
14057                 for (int userId : userIds) {
14058                     try {
14059                         mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14060                                 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14061                     } catch (InstallerException e) {
14062                         Slog.w(TAG, String.valueOf(e));
14063                     }
14064                 }
14065                 removeCodePathLI(codeFile);
14066             }
14067             return true;
14068         }
14069
14070         void cleanUpResourcesLI() {
14071             throw new UnsupportedOperationException();
14072         }
14073
14074         boolean doPostDeleteLI(boolean delete) {
14075             throw new UnsupportedOperationException();
14076         }
14077     }
14078
14079     static String getAsecPackageName(String packageCid) {
14080         int idx = packageCid.lastIndexOf("-");
14081         if (idx == -1) {
14082             return packageCid;
14083         }
14084         return packageCid.substring(0, idx);
14085     }
14086
14087     // Utility method used to create code paths based on package name and available index.
14088     private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14089         String idxStr = "";
14090         int idx = 1;
14091         // Fall back to default value of idx=1 if prefix is not
14092         // part of oldCodePath
14093         if (oldCodePath != null) {
14094             String subStr = oldCodePath;
14095             // Drop the suffix right away
14096             if (suffix != null && subStr.endsWith(suffix)) {
14097                 subStr = subStr.substring(0, subStr.length() - suffix.length());
14098             }
14099             // If oldCodePath already contains prefix find out the
14100             // ending index to either increment or decrement.
14101             int sidx = subStr.lastIndexOf(prefix);
14102             if (sidx != -1) {
14103                 subStr = subStr.substring(sidx + prefix.length());
14104                 if (subStr != null) {
14105                     if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14106                         subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14107                     }
14108                     try {
14109                         idx = Integer.parseInt(subStr);
14110                         if (idx <= 1) {
14111                             idx++;
14112                         } else {
14113                             idx--;
14114                         }
14115                     } catch(NumberFormatException e) {
14116                     }
14117                 }
14118             }
14119         }
14120         idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14121         return prefix + idxStr;
14122     }
14123
14124     private File getNextCodePath(File targetDir, String packageName) {
14125         int suffix = 1;
14126         File result;
14127         do {
14128             result = new File(targetDir, packageName + "-" + suffix);
14129             suffix++;
14130         } while (result.exists());
14131         return result;
14132     }
14133
14134     // Utility method that returns the relative package path with respect
14135     // to the installation directory. Like say for /data/data/com.test-1.apk
14136     // string com.test-1 is returned.
14137     static String deriveCodePathName(String codePath) {
14138         if (codePath == null) {
14139             return null;
14140         }
14141         final File codeFile = new File(codePath);
14142         final String name = codeFile.getName();
14143         if (codeFile.isDirectory()) {
14144             return name;
14145         } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14146             final int lastDot = name.lastIndexOf('.');
14147             return name.substring(0, lastDot);
14148         } else {
14149             Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14150             return null;
14151         }
14152     }
14153
14154     static class PackageInstalledInfo {
14155         String name;
14156         int uid;
14157         // The set of users that originally had this package installed.
14158         int[] origUsers;
14159         // The set of users that now have this package installed.
14160         int[] newUsers;
14161         PackageParser.Package pkg;
14162         int returnCode;
14163         String returnMsg;
14164         PackageRemovedInfo removedInfo;
14165         ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14166
14167         public void setError(int code, String msg) {
14168             setReturnCode(code);
14169             setReturnMessage(msg);
14170             Slog.w(TAG, msg);
14171         }
14172
14173         public void setError(String msg, PackageParserException e) {
14174             setReturnCode(e.error);
14175             setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14176             Slog.w(TAG, msg, e);
14177         }
14178
14179         public void setError(String msg, PackageManagerException e) {
14180             returnCode = e.error;
14181             setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14182             Slog.w(TAG, msg, e);
14183         }
14184
14185         public void setReturnCode(int returnCode) {
14186             this.returnCode = returnCode;
14187             final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14188             for (int i = 0; i < childCount; i++) {
14189                 addedChildPackages.valueAt(i).returnCode = returnCode;
14190             }
14191         }
14192
14193         private void setReturnMessage(String returnMsg) {
14194             this.returnMsg = returnMsg;
14195             final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14196             for (int i = 0; i < childCount; i++) {
14197                 addedChildPackages.valueAt(i).returnMsg = returnMsg;
14198             }
14199         }
14200
14201         // In some error cases we want to convey more info back to the observer
14202         String origPackage;
14203         String origPermission;
14204     }
14205
14206     /*
14207      * Install a non-existing package.
14208      */
14209     private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14210             int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14211             PackageInstalledInfo res) {
14212         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14213
14214         // Remember this for later, in case we need to rollback this install
14215         String pkgName = pkg.packageName;
14216
14217         if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14218
14219         synchronized(mPackages) {
14220             if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14221                 // A package with the same name is already installed, though
14222                 // it has been renamed to an older name.  The package we
14223                 // are trying to install should be installed as an update to
14224                 // the existing one, but that has not been requested, so bail.
14225                 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14226                         + " without first uninstalling package running as "
14227                         + mSettings.mRenamedPackages.get(pkgName));
14228                 return;
14229             }
14230             if (mPackages.containsKey(pkgName)) {
14231                 // Don't allow installation over an existing package with the same name.
14232                 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14233                         + " without first uninstalling.");
14234                 return;
14235             }
14236         }
14237
14238         try {
14239             PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14240                     System.currentTimeMillis(), user);
14241
14242             updateSettingsLI(newPackage, installerPackageName, null, res, user);
14243
14244             if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14245                 prepareAppDataAfterInstallLIF(newPackage);
14246
14247             } else {
14248                 // Remove package from internal structures, but keep around any
14249                 // data that might have already existed
14250                 deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14251                         PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14252             }
14253         } catch (PackageManagerException e) {
14254             res.setError("Package couldn't be installed in " + pkg.codePath, e);
14255         }
14256
14257         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14258     }
14259
14260     private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14261         // Can't rotate keys during boot or if sharedUser.
14262         if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14263                 || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14264             return false;
14265         }
14266         // app is using upgradeKeySets; make sure all are valid
14267         KeySetManagerService ksms = mSettings.mKeySetManagerService;
14268         long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14269         for (int i = 0; i < upgradeKeySets.length; i++) {
14270             if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14271                 Slog.wtf(TAG, "Package "
14272                          + (oldPs.name != null ? oldPs.name : "<null>")
14273                          + " contains upgrade-key-set reference to unknown key-set: "
14274                          + upgradeKeySets[i]
14275                          + " reverting to signatures check.");
14276                 return false;
14277             }
14278         }
14279         return true;
14280     }
14281
14282     private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14283         // Upgrade keysets are being used.  Determine if new package has a superset of the
14284         // required keys.
14285         long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14286         KeySetManagerService ksms = mSettings.mKeySetManagerService;
14287         for (int i = 0; i < upgradeKeySets.length; i++) {
14288             Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14289             if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14290                 return true;
14291             }
14292         }
14293         return false;
14294     }
14295
14296     private static void updateDigest(MessageDigest digest, File file) throws IOException {
14297         try (DigestInputStream digestStream =
14298                 new DigestInputStream(new FileInputStream(file), digest)) {
14299             while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14300         }
14301     }
14302
14303     private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14304             UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14305         final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14306
14307         final PackageParser.Package oldPackage;
14308         final String pkgName = pkg.packageName;
14309         final int[] allUsers;
14310         final int[] installedUsers;
14311
14312         synchronized(mPackages) {
14313             oldPackage = mPackages.get(pkgName);
14314             if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14315
14316             // don't allow upgrade to target a release SDK from a pre-release SDK
14317             final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14318                     == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14319             final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14320                     == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14321             if (oldTargetsPreRelease
14322                     && !newTargetsPreRelease
14323                     && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14324                 Slog.w(TAG, "Can't install package targeting released sdk");
14325                 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14326                 return;
14327             }
14328
14329             // don't allow an upgrade from full to ephemeral
14330             final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14331             if (isEphemeral && !oldIsEphemeral) {
14332                 // can't downgrade from full to ephemeral
14333                 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14334                 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14335                 return;
14336             }
14337
14338             // verify signatures are valid
14339             final PackageSetting ps = mSettings.mPackages.get(pkgName);
14340             if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14341                 if (!checkUpgradeKeySetLP(ps, pkg)) {
14342                     res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14343                             "New package not signed by keys specified by upgrade-keysets: "
14344                                     + pkgName);
14345                     return;
14346                 }
14347             } else {
14348                 // default to original signature matching
14349                 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14350                         != PackageManager.SIGNATURE_MATCH) {
14351                     res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14352                             "New package has a different signature: " + pkgName);
14353                     return;
14354                 }
14355             }
14356
14357             // don't allow a system upgrade unless the upgrade hash matches
14358             if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14359                 byte[] digestBytes = null;
14360                 try {
14361                     final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14362                     updateDigest(digest, new File(pkg.baseCodePath));
14363                     if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14364                         for (String path : pkg.splitCodePaths) {
14365                             updateDigest(digest, new File(path));
14366                         }
14367                     }
14368                     digestBytes = digest.digest();
14369                 } catch (NoSuchAlgorithmException | IOException e) {
14370                     res.setError(INSTALL_FAILED_INVALID_APK,
14371                             "Could not compute hash: " + pkgName);
14372                     return;
14373                 }
14374                 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14375                     res.setError(INSTALL_FAILED_INVALID_APK,
14376                             "New package fails restrict-update check: " + pkgName);
14377                     return;
14378                 }
14379                 // retain upgrade restriction
14380                 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14381             }
14382
14383             // Check for shared user id changes
14384             String invalidPackageName =
14385                     getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14386             if (invalidPackageName != null) {
14387                 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14388                         "Package " + invalidPackageName + " tried to change user "
14389                                 + oldPackage.mSharedUserId);
14390                 return;
14391             }
14392
14393             // In case of rollback, remember per-user/profile install state
14394             allUsers = sUserManager.getUserIds();
14395             installedUsers = ps.queryInstalledUsers(allUsers, true);
14396         }
14397
14398         // Update what is removed
14399         res.removedInfo = new PackageRemovedInfo();
14400         res.removedInfo.uid = oldPackage.applicationInfo.uid;
14401         res.removedInfo.removedPackage = oldPackage.packageName;
14402         res.removedInfo.isUpdate = true;
14403         res.removedInfo.origUsers = installedUsers;
14404         final int childCount = (oldPackage.childPackages != null)
14405                 ? oldPackage.childPackages.size() : 0;
14406         for (int i = 0; i < childCount; i++) {
14407             boolean childPackageUpdated = false;
14408             PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14409             if (res.addedChildPackages != null) {
14410                 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14411                 if (childRes != null) {
14412                     childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14413                     childRes.removedInfo.removedPackage = childPkg.packageName;
14414                     childRes.removedInfo.isUpdate = true;
14415                     childPackageUpdated = true;
14416                 }
14417             }
14418             if (!childPackageUpdated) {
14419                 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14420                 childRemovedRes.removedPackage = childPkg.packageName;
14421                 childRemovedRes.isUpdate = false;
14422                 childRemovedRes.dataRemoved = true;
14423                 synchronized (mPackages) {
14424                     PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14425                     if (childPs != null) {
14426                         childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14427                     }
14428                 }
14429                 if (res.removedInfo.removedChildPackages == null) {
14430                     res.removedInfo.removedChildPackages = new ArrayMap<>();
14431                 }
14432                 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14433             }
14434         }
14435
14436         boolean sysPkg = (isSystemApp(oldPackage));
14437         if (sysPkg) {
14438             // Set the system/privileged flags as needed
14439             final boolean privileged =
14440                     (oldPackage.applicationInfo.privateFlags
14441                             & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14442             final int systemPolicyFlags = policyFlags
14443                     | PackageParser.PARSE_IS_SYSTEM
14444                     | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14445
14446             replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14447                     user, allUsers, installerPackageName, res);
14448         } else {
14449             replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14450                     user, allUsers, installerPackageName, res);
14451         }
14452     }
14453
14454     public List<String> getPreviousCodePaths(String packageName) {
14455         final PackageSetting ps = mSettings.mPackages.get(packageName);
14456         final List<String> result = new ArrayList<String>();
14457         if (ps != null && ps.oldCodePaths != null) {
14458             result.addAll(ps.oldCodePaths);
14459         }
14460         return result;
14461     }
14462
14463     private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14464             PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14465             int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14466         if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14467                 + deletedPackage);
14468
14469         String pkgName = deletedPackage.packageName;
14470         boolean deletedPkg = true;
14471         boolean addedPkg = false;
14472         boolean updatedSettings = false;
14473         final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14474         final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14475                 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14476
14477         final long origUpdateTime = (pkg.mExtras != null)
14478                 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14479
14480         // First delete the existing package while retaining the data directory
14481         if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14482                 res.removedInfo, true, pkg)) {
14483             // If the existing package wasn't successfully deleted
14484             res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14485             deletedPkg = false;
14486         } else {
14487             // Successfully deleted the old package; proceed with replace.
14488
14489             // If deleted package lived in a container, give users a chance to
14490             // relinquish resources before killing.
14491             if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14492                 if (DEBUG_INSTALL) {
14493                     Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14494                 }
14495                 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14496                 final ArrayList<String> pkgList = new ArrayList<String>(1);
14497                 pkgList.add(deletedPackage.applicationInfo.packageName);
14498                 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14499             }
14500
14501             clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14502                     | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14503             clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14504
14505             try {
14506                 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14507                         scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14508                 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14509
14510                 // Update the in-memory copy of the previous code paths.
14511                 PackageSetting ps = mSettings.mPackages.get(pkgName);
14512                 if (!killApp) {
14513                     if (ps.oldCodePaths == null) {
14514                         ps.oldCodePaths = new ArraySet<>();
14515                     }
14516                     Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14517                     if (deletedPackage.splitCodePaths != null) {
14518                         Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14519                     }
14520                 } else {
14521                     ps.oldCodePaths = null;
14522                 }
14523                 if (ps.childPackageNames != null) {
14524                     for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14525                         final String childPkgName = ps.childPackageNames.get(i);
14526                         final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14527                         childPs.oldCodePaths = ps.oldCodePaths;
14528                     }
14529                 }
14530                 prepareAppDataAfterInstallLIF(newPackage);
14531                 addedPkg = true;
14532             } catch (PackageManagerException e) {
14533                 res.setError("Package couldn't be installed in " + pkg.codePath, e);
14534             }
14535         }
14536
14537         if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14538             if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14539
14540             // Revert all internal state mutations and added folders for the failed install
14541             if (addedPkg) {
14542                 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14543                         res.removedInfo, true, null);
14544             }
14545
14546             // Restore the old package
14547             if (deletedPkg) {
14548                 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14549                 File restoreFile = new File(deletedPackage.codePath);
14550                 // Parse old package
14551                 boolean oldExternal = isExternal(deletedPackage);
14552                 int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14553                         (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14554                         (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14555                 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14556                 try {
14557                     scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14558                             null);
14559                 } catch (PackageManagerException e) {
14560                     Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14561                             + e.getMessage());
14562                     return;
14563                 }
14564
14565                 synchronized (mPackages) {
14566                     // Ensure the installer package name up to date
14567                     setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14568
14569                     // Update permissions for restored package
14570                     updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14571
14572                     mSettings.writeLPr();
14573                 }
14574
14575                 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14576             }
14577         } else {
14578             synchronized (mPackages) {
14579                 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14580                 if (ps != null) {
14581                     res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14582                     if (res.removedInfo.removedChildPackages != null) {
14583                         final int childCount = res.removedInfo.removedChildPackages.size();
14584                         // Iterate in reverse as we may modify the collection
14585                         for (int i = childCount - 1; i >= 0; i--) {
14586                             String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14587                             if (res.addedChildPackages.containsKey(childPackageName)) {
14588                                 res.removedInfo.removedChildPackages.removeAt(i);
14589                             } else {
14590                                 PackageRemovedInfo childInfo = res.removedInfo
14591                                         .removedChildPackages.valueAt(i);
14592                                 childInfo.removedForAllUsers = mPackages.get(
14593                                         childInfo.removedPackage) == null;
14594                             }
14595                         }
14596                     }
14597                 }
14598             }
14599         }
14600     }
14601
14602     private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14603             PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14604             int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14605         if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14606                 + ", old=" + deletedPackage);
14607
14608         final boolean disabledSystem;
14609
14610         // Remove existing system package
14611         removePackageLI(deletedPackage, true);
14612
14613         synchronized (mPackages) {
14614             disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14615         }
14616         if (!disabledSystem) {
14617             // We didn't need to disable the .apk as a current system package,
14618             // which means we are replacing another update that is already
14619             // installed.  We need to make sure to delete the older one's .apk.
14620             res.removedInfo.args = createInstallArgsForExisting(0,
14621                     deletedPackage.applicationInfo.getCodePath(),
14622                     deletedPackage.applicationInfo.getResourcePath(),
14623                     getAppDexInstructionSets(deletedPackage.applicationInfo));
14624         } else {
14625             res.removedInfo.args = null;
14626         }
14627
14628         // Successfully disabled the old package. Now proceed with re-installation
14629         clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14630                 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14631         clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14632
14633         res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14634         pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14635                 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14636
14637         PackageParser.Package newPackage = null;
14638         try {
14639             // Add the package to the internal data structures
14640             newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14641
14642             // Set the update and install times
14643             PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14644             setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14645                     System.currentTimeMillis());
14646
14647             // Update the package dynamic state if succeeded
14648             if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14649                 // Now that the install succeeded make sure we remove data
14650                 // directories for any child package the update removed.
14651                 final int deletedChildCount = (deletedPackage.childPackages != null)
14652                         ? deletedPackage.childPackages.size() : 0;
14653                 final int newChildCount = (newPackage.childPackages != null)
14654                         ? newPackage.childPackages.size() : 0;
14655                 for (int i = 0; i < deletedChildCount; i++) {
14656                     PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14657                     boolean childPackageDeleted = true;
14658                     for (int j = 0; j < newChildCount; j++) {
14659                         PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14660                         if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14661                             childPackageDeleted = false;
14662                             break;
14663                         }
14664                     }
14665                     if (childPackageDeleted) {
14666                         PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14667                                 deletedChildPkg.packageName);
14668                         if (ps != null && res.removedInfo.removedChildPackages != null) {
14669                             PackageRemovedInfo removedChildRes = res.removedInfo
14670                                     .removedChildPackages.get(deletedChildPkg.packageName);
14671                             removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14672                             removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14673                         }
14674                     }
14675                 }
14676
14677                 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14678                 prepareAppDataAfterInstallLIF(newPackage);
14679             }
14680         } catch (PackageManagerException e) {
14681             res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14682             res.setError("Package couldn't be installed in " + pkg.codePath, e);
14683         }
14684
14685         if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14686             // Re installation failed. Restore old information
14687             // Remove new pkg information
14688             if (newPackage != null) {
14689                 removeInstalledPackageLI(newPackage, true);
14690             }
14691             // Add back the old system package
14692             try {
14693                 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14694             } catch (PackageManagerException e) {
14695                 Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14696             }
14697
14698             synchronized (mPackages) {
14699                 if (disabledSystem) {
14700                     enableSystemPackageLPw(deletedPackage);
14701                 }
14702
14703                 // Ensure the installer package name up to date
14704                 setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14705
14706                 // Update permissions for restored package
14707                 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14708
14709                 mSettings.writeLPr();
14710             }
14711
14712             Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14713                     + " after failed upgrade");
14714         }
14715     }
14716
14717     /**
14718      * Checks whether the parent or any of the child packages have a change shared
14719      * user. For a package to be a valid update the shred users of the parent and
14720      * the children should match. We may later support changing child shared users.
14721      * @param oldPkg The updated package.
14722      * @param newPkg The update package.
14723      * @return The shared user that change between the versions.
14724      */
14725     private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14726             PackageParser.Package newPkg) {
14727         // Check parent shared user
14728         if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14729             return newPkg.packageName;
14730         }
14731         // Check child shared users
14732         final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14733         final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14734         for (int i = 0; i < newChildCount; i++) {
14735             PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14736             // If this child was present, did it have the same shared user?
14737             for (int j = 0; j < oldChildCount; j++) {
14738                 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14739                 if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14740                         && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14741                     return newChildPkg.packageName;
14742                 }
14743             }
14744         }
14745         return null;
14746     }
14747
14748     private void removeNativeBinariesLI(PackageSetting ps) {
14749         // Remove the lib path for the parent package
14750         if (ps != null) {
14751             NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14752             // Remove the lib path for the child packages
14753             final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14754             for (int i = 0; i < childCount; i++) {
14755                 PackageSetting childPs = null;
14756                 synchronized (mPackages) {
14757                     childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14758                 }
14759                 if (childPs != null) {
14760                     NativeLibraryHelper.removeNativeBinariesLI(childPs
14761                             .legacyNativeLibraryPathString);
14762                 }
14763             }
14764         }
14765     }
14766
14767     private void enableSystemPackageLPw(PackageParser.Package pkg) {
14768         // Enable the parent package
14769         mSettings.enableSystemPackageLPw(pkg.packageName);
14770         // Enable the child packages
14771         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14772         for (int i = 0; i < childCount; i++) {
14773             PackageParser.Package childPkg = pkg.childPackages.get(i);
14774             mSettings.enableSystemPackageLPw(childPkg.packageName);
14775         }
14776     }
14777
14778     private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14779             PackageParser.Package newPkg) {
14780         // Disable the parent package (parent always replaced)
14781         boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14782         // Disable the child packages
14783         final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14784         for (int i = 0; i < childCount; i++) {
14785             PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14786             final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14787             disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14788         }
14789         return disabled;
14790     }
14791
14792     private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14793             String installerPackageName) {
14794         // Enable the parent package
14795         mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14796         // Enable the child packages
14797         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14798         for (int i = 0; i < childCount; i++) {
14799             PackageParser.Package childPkg = pkg.childPackages.get(i);
14800             mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14801         }
14802     }
14803
14804     private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14805         // Collect all used permissions in the UID
14806         ArraySet<String> usedPermissions = new ArraySet<>();
14807         final int packageCount = su.packages.size();
14808         for (int i = 0; i < packageCount; i++) {
14809             PackageSetting ps = su.packages.valueAt(i);
14810             if (ps.pkg == null) {
14811                 continue;
14812             }
14813             final int requestedPermCount = ps.pkg.requestedPermissions.size();
14814             for (int j = 0; j < requestedPermCount; j++) {
14815                 String permission = ps.pkg.requestedPermissions.get(j);
14816                 BasePermission bp = mSettings.mPermissions.get(permission);
14817                 if (bp != null) {
14818                     usedPermissions.add(permission);
14819                 }
14820             }
14821         }
14822
14823         PermissionsState permissionsState = su.getPermissionsState();
14824         // Prune install permissions
14825         List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14826         final int installPermCount = installPermStates.size();
14827         for (int i = installPermCount - 1; i >= 0;  i--) {
14828             PermissionState permissionState = installPermStates.get(i);
14829             if (!usedPermissions.contains(permissionState.getName())) {
14830                 BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14831                 if (bp != null) {
14832                     permissionsState.revokeInstallPermission(bp);
14833                     permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14834                             PackageManager.MASK_PERMISSION_FLAGS, 0);
14835                 }
14836             }
14837         }
14838
14839         int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14840
14841         // Prune runtime permissions
14842         for (int userId : allUserIds) {
14843             List<PermissionState> runtimePermStates = permissionsState
14844                     .getRuntimePermissionStates(userId);
14845             final int runtimePermCount = runtimePermStates.size();
14846             for (int i = runtimePermCount - 1; i >= 0; i--) {
14847                 PermissionState permissionState = runtimePermStates.get(i);
14848                 if (!usedPermissions.contains(permissionState.getName())) {
14849                     BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14850                     if (bp != null) {
14851                         permissionsState.revokeRuntimePermission(bp, userId);
14852                         permissionsState.updatePermissionFlags(bp, userId,
14853                                 PackageManager.MASK_PERMISSION_FLAGS, 0);
14854                         runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14855                                 runtimePermissionChangedUserIds, userId);
14856                     }
14857                 }
14858             }
14859         }
14860
14861         return runtimePermissionChangedUserIds;
14862     }
14863
14864     private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14865             int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14866         // Update the parent package setting
14867         updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14868                 res, user);
14869         // Update the child packages setting
14870         final int childCount = (newPackage.childPackages != null)
14871                 ? newPackage.childPackages.size() : 0;
14872         for (int i = 0; i < childCount; i++) {
14873             PackageParser.Package childPackage = newPackage.childPackages.get(i);
14874             PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14875             updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14876                     childRes.origUsers, childRes, user);
14877         }
14878     }
14879
14880     private void updateSettingsInternalLI(PackageParser.Package newPackage,
14881             String installerPackageName, int[] allUsers, int[] installedForUsers,
14882             PackageInstalledInfo res, UserHandle user) {
14883         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14884
14885         String pkgName = newPackage.packageName;
14886         synchronized (mPackages) {
14887             //write settings. the installStatus will be incomplete at this stage.
14888             //note that the new package setting would have already been
14889             //added to mPackages. It hasn't been persisted yet.
14890             mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14891             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14892             mSettings.writeLPr();
14893             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14894         }
14895
14896         if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14897         synchronized (mPackages) {
14898             updatePermissionsLPw(newPackage.packageName, newPackage,
14899                     UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14900                             ? UPDATE_PERMISSIONS_ALL : 0));
14901             // For system-bundled packages, we assume that installing an upgraded version
14902             // of the package implies that the user actually wants to run that new code,
14903             // so we enable the package.
14904             PackageSetting ps = mSettings.mPackages.get(pkgName);
14905             final int userId = user.getIdentifier();
14906             if (ps != null) {
14907                 if (isSystemApp(newPackage)) {
14908                     if (DEBUG_INSTALL) {
14909                         Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14910                     }
14911                     // Enable system package for requested users
14912                     if (res.origUsers != null) {
14913                         for (int origUserId : res.origUsers) {
14914                             if (userId == UserHandle.USER_ALL || userId == origUserId) {
14915                                 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14916                                         origUserId, installerPackageName);
14917                             }
14918                         }
14919                     }
14920                     // Also convey the prior install/uninstall state
14921                     if (allUsers != null && installedForUsers != null) {
14922                         for (int currentUserId : allUsers) {
14923                             final boolean installed = ArrayUtils.contains(
14924                                     installedForUsers, currentUserId);
14925                             if (DEBUG_INSTALL) {
14926                                 Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14927                             }
14928                             ps.setInstalled(installed, currentUserId);
14929                         }
14930                         // these install state changes will be persisted in the
14931                         // upcoming call to mSettings.writeLPr().
14932                     }
14933                 }
14934                 // It's implied that when a user requests installation, they want the app to be
14935                 // installed and enabled.
14936                 if (userId != UserHandle.USER_ALL) {
14937                     ps.setInstalled(true, userId);
14938                     ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14939                 }
14940             }
14941             res.name = pkgName;
14942             res.uid = newPackage.applicationInfo.uid;
14943             res.pkg = newPackage;
14944             mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14945             mSettings.setInstallerPackageName(pkgName, installerPackageName);
14946             res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14947             //to update install status
14948             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14949             mSettings.writeLPr();
14950             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14951         }
14952
14953         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14954     }
14955
14956     private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14957         try {
14958             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14959             installPackageLI(args, res);
14960         } finally {
14961             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14962         }
14963     }
14964
14965     private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14966         final int installFlags = args.installFlags;
14967         final String installerPackageName = args.installerPackageName;
14968         final String volumeUuid = args.volumeUuid;
14969         final File tmpPackageFile = new File(args.getCodePath());
14970         final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14971         final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14972                 || (args.volumeUuid != null));
14973         final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14974         final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14975         boolean replace = false;
14976         int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14977         if (args.move != null) {
14978             // moving a complete application; perform an initial scan on the new install location
14979             scanFlags |= SCAN_INITIAL;
14980         }
14981         if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14982             scanFlags |= SCAN_DONT_KILL_APP;
14983         }
14984
14985         // Result object to be returned
14986         res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14987
14988         if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14989
14990         // Sanity check
14991         if (ephemeral && (forwardLocked || onExternal)) {
14992             Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14993                     + " external=" + onExternal);
14994             res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14995             return;
14996         }
14997
14998         // Retrieve PackageSettings and parse package
14999         final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15000                 | PackageParser.PARSE_ENFORCE_CODE
15001                 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15002                 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15003                 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15004                 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15005         PackageParser pp = new PackageParser();
15006         pp.setSeparateProcesses(mSeparateProcesses);
15007         pp.setDisplayMetrics(mMetrics);
15008
15009         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15010         final PackageParser.Package pkg;
15011         try {
15012             pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15013         } catch (PackageParserException e) {
15014             res.setError("Failed parse during installPackageLI", e);
15015             return;
15016         } finally {
15017             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15018         }
15019
15020         // If we are installing a clustered package add results for the children
15021         if (pkg.childPackages != null) {
15022             synchronized (mPackages) {
15023                 final int childCount = pkg.childPackages.size();
15024                 for (int i = 0; i < childCount; i++) {
15025                     PackageParser.Package childPkg = pkg.childPackages.get(i);
15026                     PackageInstalledInfo childRes = new PackageInstalledInfo();
15027                     childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15028                     childRes.pkg = childPkg;
15029                     childRes.name = childPkg.packageName;
15030                     PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15031                     if (childPs != null) {
15032                         childRes.origUsers = childPs.queryInstalledUsers(
15033                                 sUserManager.getUserIds(), true);
15034                     }
15035                     if ((mPackages.containsKey(childPkg.packageName))) {
15036                         childRes.removedInfo = new PackageRemovedInfo();
15037                         childRes.removedInfo.removedPackage = childPkg.packageName;
15038                     }
15039                     if (res.addedChildPackages == null) {
15040                         res.addedChildPackages = new ArrayMap<>();
15041                     }
15042                     res.addedChildPackages.put(childPkg.packageName, childRes);
15043                 }
15044             }
15045         }
15046
15047         // If package doesn't declare API override, mark that we have an install
15048         // time CPU ABI override.
15049         if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15050             pkg.cpuAbiOverride = args.abiOverride;
15051         }
15052
15053         String pkgName = res.name = pkg.packageName;
15054         if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15055             if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15056                 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15057                 return;
15058             }
15059         }
15060
15061         try {
15062             // either use what we've been given or parse directly from the APK
15063             if (args.certificates != null) {
15064                 try {
15065                     PackageParser.populateCertificates(pkg, args.certificates);
15066                 } catch (PackageParserException e) {
15067                     // there was something wrong with the certificates we were given;
15068                     // try to pull them from the APK
15069                     PackageParser.collectCertificates(pkg, parseFlags);
15070                 }
15071             } else {
15072                 PackageParser.collectCertificates(pkg, parseFlags);
15073             }
15074         } catch (PackageParserException e) {
15075             res.setError("Failed collect during installPackageLI", e);
15076             return;
15077         }
15078
15079         // Get rid of all references to package scan path via parser.
15080         pp = null;
15081         String oldCodePath = null;
15082         boolean systemApp = false;
15083         synchronized (mPackages) {
15084             // Check if installing already existing package
15085             if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15086                 String oldName = mSettings.mRenamedPackages.get(pkgName);
15087                 if (pkg.mOriginalPackages != null
15088                         && pkg.mOriginalPackages.contains(oldName)
15089                         && mPackages.containsKey(oldName)) {
15090                     // This package is derived from an original package,
15091                     // and this device has been updating from that original
15092                     // name.  We must continue using the original name, so
15093                     // rename the new package here.
15094                     pkg.setPackageName(oldName);
15095                     pkgName = pkg.packageName;
15096                     replace = true;
15097                     if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15098                             + oldName + " pkgName=" + pkgName);
15099                 } else if (mPackages.containsKey(pkgName)) {
15100                     // This package, under its official name, already exists
15101                     // on the device; we should replace it.
15102                     replace = true;
15103                     if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15104                 }
15105
15106                 // Child packages are installed through the parent package
15107                 if (pkg.parentPackage != null) {
15108                     res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15109                             "Package " + pkg.packageName + " is child of package "
15110                                     + pkg.parentPackage.parentPackage + ". Child packages "
15111                                     + "can be updated only through the parent package.");
15112                     return;
15113                 }
15114
15115                 if (replace) {
15116                     // Prevent apps opting out from runtime permissions
15117                     PackageParser.Package oldPackage = mPackages.get(pkgName);
15118                     final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15119                     final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15120                     if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15121                             && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15122                         res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15123                                 "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15124                                         + " doesn't support runtime permissions but the old"
15125                                         + " target SDK " + oldTargetSdk + " does.");
15126                         return;
15127                     }
15128
15129                     // Prevent installing of child packages
15130                     if (oldPackage.parentPackage != null) {
15131                         res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15132                                 "Package " + pkg.packageName + " is child of package "
15133                                         + oldPackage.parentPackage + ". Child packages "
15134                                         + "can be updated only through the parent package.");
15135                         return;
15136                     }
15137                 }
15138             }
15139
15140             PackageSetting ps = mSettings.mPackages.get(pkgName);
15141             if (ps != null) {
15142                 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15143
15144                 // Quick sanity check that we're signed correctly if updating;
15145                 // we'll check this again later when scanning, but we want to
15146                 // bail early here before tripping over redefined permissions.
15147                 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15148                     if (!checkUpgradeKeySetLP(ps, pkg)) {
15149                         res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15150                                 + pkg.packageName + " upgrade keys do not match the "
15151                                 + "previously installed version");
15152                         return;
15153                     }
15154                 } else {
15155                     try {
15156                         verifySignaturesLP(ps, pkg);
15157                     } catch (PackageManagerException e) {
15158                         res.setError(e.error, e.getMessage());
15159                         return;
15160                     }
15161                 }
15162
15163                 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15164                 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15165                     systemApp = (ps.pkg.applicationInfo.flags &
15166                             ApplicationInfo.FLAG_SYSTEM) != 0;
15167                 }
15168                 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15169             }
15170
15171             // Check whether the newly-scanned package wants to define an already-defined perm
15172             int N = pkg.permissions.size();
15173             for (int i = N-1; i >= 0; i--) {
15174                 PackageParser.Permission perm = pkg.permissions.get(i);
15175                 BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15176                 if (bp != null) {
15177                     // If the defining package is signed with our cert, it's okay.  This
15178                     // also includes the "updating the same package" case, of course.
15179                     // "updating same package" could also involve key-rotation.
15180                     final boolean sigsOk;
15181                     if (bp.sourcePackage.equals(pkg.packageName)
15182                             && (bp.packageSetting instanceof PackageSetting)
15183                             && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15184                                     scanFlags))) {
15185                         sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15186                     } else {
15187                         sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15188                                 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15189                     }
15190                     if (!sigsOk) {
15191                         // If the owning package is the system itself, we log but allow
15192                         // install to proceed; we fail the install on all other permission
15193                         // redefinitions.
15194                         if (!bp.sourcePackage.equals("android")) {
15195                             res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15196                                     + pkg.packageName + " attempting to redeclare permission "
15197                                     + perm.info.name + " already owned by " + bp.sourcePackage);
15198                             res.origPermission = perm.info.name;
15199                             res.origPackage = bp.sourcePackage;
15200                             return;
15201                         } else {
15202                             Slog.w(TAG, "Package " + pkg.packageName
15203                                     + " attempting to redeclare system permission "
15204                                     + perm.info.name + "; ignoring new declaration");
15205                             pkg.permissions.remove(i);
15206                         }
15207                     }
15208                 }
15209             }
15210         }
15211
15212         if (systemApp) {
15213             if (onExternal) {
15214                 // Abort update; system app can't be replaced with app on sdcard
15215                 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15216                         "Cannot install updates to system apps on sdcard");
15217                 return;
15218             } else if (ephemeral) {
15219                 // Abort update; system app can't be replaced with an ephemeral app
15220                 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15221                         "Cannot update a system app with an ephemeral app");
15222                 return;
15223             }
15224         }
15225
15226         if (args.move != null) {
15227             // We did an in-place move, so dex is ready to roll
15228             scanFlags |= SCAN_NO_DEX;
15229             scanFlags |= SCAN_MOVE;
15230
15231             synchronized (mPackages) {
15232                 final PackageSetting ps = mSettings.mPackages.get(pkgName);
15233                 if (ps == null) {
15234                     res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15235                             "Missing settings for moved package " + pkgName);
15236                 }
15237
15238                 // We moved the entire application as-is, so bring over the
15239                 // previously derived ABI information.
15240                 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15241                 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15242             }
15243
15244         } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15245             // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15246             scanFlags |= SCAN_NO_DEX;
15247
15248             try {
15249                 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15250                     args.abiOverride : pkg.cpuAbiOverride);
15251                 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15252                         true /* extract libs */);
15253             } catch (PackageManagerException pme) {
15254                 Slog.e(TAG, "Error deriving application ABI", pme);
15255                 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15256                 return;
15257             }
15258
15259             // Shared libraries for the package need to be updated.
15260             synchronized (mPackages) {
15261                 try {
15262                     updateSharedLibrariesLPw(pkg, null);
15263                 } catch (PackageManagerException e) {
15264                     Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15265                 }
15266             }
15267             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15268             // Do not run PackageDexOptimizer through the local performDexOpt
15269             // method because `pkg` may not be in `mPackages` yet.
15270             //
15271             // Also, don't fail application installs if the dexopt step fails.
15272             mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15273                     null /* instructionSets */, false /* checkProfiles */,
15274                     getCompilerFilterForReason(REASON_INSTALL),
15275                     getOrCreateCompilerPackageStats(pkg));
15276             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15277
15278             // Notify BackgroundDexOptService that the package has been changed.
15279             // If this is an update of a package which used to fail to compile,
15280             // BDOS will remove it from its blacklist.
15281             BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15282         }
15283
15284         if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15285             res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15286             return;
15287         }
15288
15289         startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15290
15291         try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15292                 "installPackageLI")) {
15293             if (replace) {
15294                 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15295                         installerPackageName, res);
15296             } else {
15297                 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15298                         args.user, installerPackageName, volumeUuid, res);
15299             }
15300         }
15301         synchronized (mPackages) {
15302             final PackageSetting ps = mSettings.mPackages.get(pkgName);
15303             if (ps != null) {
15304                 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15305             }
15306
15307             final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15308             for (int i = 0; i < childCount; i++) {
15309                 PackageParser.Package childPkg = pkg.childPackages.get(i);
15310                 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15311                 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15312                 if (childPs != null) {
15313                     childRes.newUsers = childPs.queryInstalledUsers(
15314                             sUserManager.getUserIds(), true);
15315                 }
15316             }
15317         }
15318     }
15319
15320     private void startIntentFilterVerifications(int userId, boolean replacing,
15321             PackageParser.Package pkg) {
15322         if (mIntentFilterVerifierComponent == null) {
15323             Slog.w(TAG, "No IntentFilter verification will not be done as "
15324                     + "there is no IntentFilterVerifier available!");
15325             return;
15326         }
15327
15328         final int verifierUid = getPackageUid(
15329                 mIntentFilterVerifierComponent.getPackageName(),
15330                 MATCH_DEBUG_TRIAGED_MISSING,
15331                 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15332
15333         Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15334         msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15335         mHandler.sendMessage(msg);
15336
15337         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15338         for (int i = 0; i < childCount; i++) {
15339             PackageParser.Package childPkg = pkg.childPackages.get(i);
15340             msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15341             msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15342             mHandler.sendMessage(msg);
15343         }
15344     }
15345
15346     private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15347             PackageParser.Package pkg) {
15348         int size = pkg.activities.size();
15349         if (size == 0) {
15350             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15351                     "No activity, so no need to verify any IntentFilter!");
15352             return;
15353         }
15354
15355         final boolean hasDomainURLs = hasDomainURLs(pkg);
15356         if (!hasDomainURLs) {
15357             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15358                     "No domain URLs, so no need to verify any IntentFilter!");
15359             return;
15360         }
15361
15362         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15363                 + " if any IntentFilter from the " + size
15364                 + " Activities needs verification ...");
15365
15366         int count = 0;
15367         final String packageName = pkg.packageName;
15368
15369         synchronized (mPackages) {
15370             // If this is a new install and we see that we've already run verification for this
15371             // package, we have nothing to do: it means the state was restored from backup.
15372             if (!replacing) {
15373                 IntentFilterVerificationInfo ivi =
15374                         mSettings.getIntentFilterVerificationLPr(packageName);
15375                 if (ivi != null) {
15376                     if (DEBUG_DOMAIN_VERIFICATION) {
15377                         Slog.i(TAG, "Package " + packageName+ " already verified: status="
15378                                 + ivi.getStatusString());
15379                     }
15380                     return;
15381                 }
15382             }
15383
15384             // If any filters need to be verified, then all need to be.
15385             boolean needToVerify = false;
15386             for (PackageParser.Activity a : pkg.activities) {
15387                 for (ActivityIntentInfo filter : a.intents) {
15388                     if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15389                         if (DEBUG_DOMAIN_VERIFICATION) {
15390                             Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15391                         }
15392                         needToVerify = true;
15393                         break;
15394                     }
15395                 }
15396             }
15397
15398             if (needToVerify) {
15399                 final int verificationId = mIntentFilterVerificationToken++;
15400                 for (PackageParser.Activity a : pkg.activities) {
15401                     for (ActivityIntentInfo filter : a.intents) {
15402                         if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15403                             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15404                                     "Verification needed for IntentFilter:" + filter.toString());
15405                             mIntentFilterVerifier.addOneIntentFilterVerification(
15406                                     verifierUid, userId, verificationId, filter, packageName);
15407                             count++;
15408                         }
15409                     }
15410                 }
15411             }
15412         }
15413
15414         if (count > 0) {
15415             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15416                     + " IntentFilter verification" + (count > 1 ? "s" : "")
15417                     +  " for userId:" + userId);
15418             mIntentFilterVerifier.startVerifications(userId);
15419         } else {
15420             if (DEBUG_DOMAIN_VERIFICATION) {
15421                 Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15422             }
15423         }
15424     }
15425
15426     private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15427         final ComponentName cn  = filter.activity.getComponentName();
15428         final String packageName = cn.getPackageName();
15429
15430         IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15431                 packageName);
15432         if (ivi == null) {
15433             return true;
15434         }
15435         int status = ivi.getStatus();
15436         switch (status) {
15437             case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15438             case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15439                 return true;
15440
15441             default:
15442                 // Nothing to do
15443                 return false;
15444         }
15445     }
15446
15447     private static boolean isMultiArch(ApplicationInfo info) {
15448         return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15449     }
15450
15451     private static boolean isExternal(PackageParser.Package pkg) {
15452         return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15453     }
15454
15455     private static boolean isExternal(PackageSetting ps) {
15456         return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15457     }
15458
15459     private static boolean isEphemeral(PackageParser.Package pkg) {
15460         return pkg.applicationInfo.isEphemeralApp();
15461     }
15462
15463     private static boolean isEphemeral(PackageSetting ps) {
15464         return ps.pkg != null && isEphemeral(ps.pkg);
15465     }
15466
15467     private static boolean isSystemApp(PackageParser.Package pkg) {
15468         return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15469     }
15470
15471     private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15472         return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15473     }
15474
15475     private static boolean hasDomainURLs(PackageParser.Package pkg) {
15476         return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15477     }
15478
15479     private static boolean isSystemApp(PackageSetting ps) {
15480         return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15481     }
15482
15483     private static boolean isUpdatedSystemApp(PackageSetting ps) {
15484         return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15485     }
15486
15487     private int packageFlagsToInstallFlags(PackageSetting ps) {
15488         int installFlags = 0;
15489         if (isEphemeral(ps)) {
15490             installFlags |= PackageManager.INSTALL_EPHEMERAL;
15491         }
15492         if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15493             // This existing package was an external ASEC install when we have
15494             // the external flag without a UUID
15495             installFlags |= PackageManager.INSTALL_EXTERNAL;
15496         }
15497         if (ps.isForwardLocked()) {
15498             installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15499         }
15500         return installFlags;
15501     }
15502
15503     private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15504         if (isExternal(pkg)) {
15505             if (TextUtils.isEmpty(pkg.volumeUuid)) {
15506                 return StorageManager.UUID_PRIMARY_PHYSICAL;
15507             } else {
15508                 return pkg.volumeUuid;
15509             }
15510         } else {
15511             return StorageManager.UUID_PRIVATE_INTERNAL;
15512         }
15513     }
15514
15515     private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15516         if (isExternal(pkg)) {
15517             if (TextUtils.isEmpty(pkg.volumeUuid)) {
15518                 return mSettings.getExternalVersion();
15519             } else {
15520                 return mSettings.findOrCreateVersion(pkg.volumeUuid);
15521             }
15522         } else {
15523             return mSettings.getInternalVersion();
15524         }
15525     }
15526
15527     private void deleteTempPackageFiles() {
15528         final FilenameFilter filter = new FilenameFilter() {
15529             public boolean accept(File dir, String name) {
15530                 return name.startsWith("vmdl") && name.endsWith(".tmp");
15531             }
15532         };
15533         for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15534             file.delete();
15535         }
15536     }
15537
15538     @Override
15539     public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15540             int flags) {
15541         deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15542                 flags);
15543     }
15544
15545     @Override
15546     public void deletePackage(final String packageName,
15547             final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15548         mContext.enforceCallingOrSelfPermission(
15549                 android.Manifest.permission.DELETE_PACKAGES, null);
15550         Preconditions.checkNotNull(packageName);
15551         Preconditions.checkNotNull(observer);
15552         final int uid = Binder.getCallingUid();
15553         if (!isOrphaned(packageName)
15554                 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15555             try {
15556                 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15557                 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15558                 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15559                 observer.onUserActionRequired(intent);
15560             } catch (RemoteException re) {
15561             }
15562             return;
15563         }
15564         final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15565         final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15566         if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15567             mContext.enforceCallingOrSelfPermission(
15568                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15569                     "deletePackage for user " + userId);
15570         }
15571
15572         if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15573             try {
15574                 observer.onPackageDeleted(packageName,
15575                         PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15576             } catch (RemoteException re) {
15577             }
15578             return;
15579         }
15580
15581         if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15582             try {
15583                 observer.onPackageDeleted(packageName,
15584                         PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15585             } catch (RemoteException re) {
15586             }
15587             return;
15588         }
15589
15590         if (DEBUG_REMOVE) {
15591             Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15592                     + " deleteAllUsers: " + deleteAllUsers );
15593         }
15594         // Queue up an async operation since the package deletion may take a little while.
15595         mHandler.post(new Runnable() {
15596             public void run() {
15597                 mHandler.removeCallbacks(this);
15598                 int returnCode;
15599                 if (!deleteAllUsers) {
15600                     returnCode = deletePackageX(packageName, userId, deleteFlags);
15601                 } else {
15602                     int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15603                     // If nobody is blocking uninstall, proceed with delete for all users
15604                     if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15605                         returnCode = deletePackageX(packageName, userId, deleteFlags);
15606                     } else {
15607                         // Otherwise uninstall individually for users with blockUninstalls=false
15608                         final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15609                         for (int userId : users) {
15610                             if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15611                                 returnCode = deletePackageX(packageName, userId, userFlags);
15612                                 if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15613                                     Slog.w(TAG, "Package delete failed for user " + userId
15614                                             + ", returnCode " + returnCode);
15615                                 }
15616                             }
15617                         }
15618                         // The app has only been marked uninstalled for certain users.
15619                         // We still need to report that delete was blocked
15620                         returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15621                     }
15622                 }
15623                 try {
15624                     observer.onPackageDeleted(packageName, returnCode, null);
15625                 } catch (RemoteException e) {
15626                     Log.i(TAG, "Observer no longer exists.");
15627                 } //end catch
15628             } //end run
15629         });
15630     }
15631
15632     private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15633         if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15634               || callingUid == Process.SYSTEM_UID) {
15635             return true;
15636         }
15637         final int callingUserId = UserHandle.getUserId(callingUid);
15638         // If the caller installed the pkgName, then allow it to silently uninstall.
15639         if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15640             return true;
15641         }
15642
15643         // Allow package verifier to silently uninstall.
15644         if (mRequiredVerifierPackage != null &&
15645                 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15646             return true;
15647         }
15648
15649         // Allow package uninstaller to silently uninstall.
15650         if (mRequiredUninstallerPackage != null &&
15651                 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15652             return true;
15653         }
15654
15655         // Allow storage manager to silently uninstall.
15656         if (mStorageManagerPackage != null &&
15657                 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
15658             return true;
15659         }
15660         return false;
15661     }
15662
15663     private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15664         int[] result = EMPTY_INT_ARRAY;
15665         for (int userId : userIds) {
15666             if (getBlockUninstallForUser(packageName, userId)) {
15667                 result = ArrayUtils.appendInt(result, userId);
15668             }
15669         }
15670         return result;
15671     }
15672
15673     @Override
15674     public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15675         return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15676     }
15677
15678     private boolean isPackageDeviceAdmin(String packageName, int userId) {
15679         IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15680                 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15681         try {
15682             if (dpm != null) {
15683                 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15684                         /* callingUserOnly =*/ false);
15685                 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15686                         : deviceOwnerComponentName.getPackageName();
15687                 // Does the package contains the device owner?
15688                 // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15689                 // this check is probably not needed, since DO should be registered as a device
15690                 // admin on some user too. (Original bug for this: b/17657954)
15691                 if (packageName.equals(deviceOwnerPackageName)) {
15692                     return true;
15693                 }
15694                 // Does it contain a device admin for any user?
15695                 int[] users;
15696                 if (userId == UserHandle.USER_ALL) {
15697                     users = sUserManager.getUserIds();
15698                 } else {
15699                     users = new int[]{userId};
15700                 }
15701                 for (int i = 0; i < users.length; ++i) {
15702                     if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15703                         return true;
15704                     }
15705                 }
15706             }
15707         } catch (RemoteException e) {
15708         }
15709         return false;
15710     }
15711
15712     private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15713         return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15714     }
15715
15716     /**
15717      *  This method is an internal method that could be get invoked either
15718      *  to delete an installed package or to clean up a failed installation.
15719      *  After deleting an installed package, a broadcast is sent to notify any
15720      *  listeners that the package has been removed. For cleaning up a failed
15721      *  installation, the broadcast is not necessary since the package's
15722      *  installation wouldn't have sent the initial broadcast either
15723      *  The key steps in deleting a package are
15724      *  deleting the package information in internal structures like mPackages,
15725      *  deleting the packages base directories through installd
15726      *  updating mSettings to reflect current status
15727      *  persisting settings for later use
15728      *  sending a broadcast if necessary
15729      */
15730     private int deletePackageX(String packageName, int userId, int deleteFlags) {
15731         final PackageRemovedInfo info = new PackageRemovedInfo();
15732         final boolean res;
15733
15734         final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15735                 ? UserHandle.USER_ALL : userId;
15736
15737         if (isPackageDeviceAdmin(packageName, removeUser)) {
15738             Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15739             return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15740         }
15741
15742         PackageSetting uninstalledPs = null;
15743
15744         // for the uninstall-updates case and restricted profiles, remember the per-
15745         // user handle installed state
15746         int[] allUsers;
15747         synchronized (mPackages) {
15748             uninstalledPs = mSettings.mPackages.get(packageName);
15749             if (uninstalledPs == null) {
15750                 Slog.w(TAG, "Not removing non-existent package " + packageName);
15751                 return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15752             }
15753             allUsers = sUserManager.getUserIds();
15754             info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15755         }
15756
15757         final int freezeUser;
15758         if (isUpdatedSystemApp(uninstalledPs)
15759                 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15760             // We're downgrading a system app, which will apply to all users, so
15761             // freeze them all during the downgrade
15762             freezeUser = UserHandle.USER_ALL;
15763         } else {
15764             freezeUser = removeUser;
15765         }
15766
15767         synchronized (mInstallLock) {
15768             if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15769             try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15770                     deleteFlags, "deletePackageX")) {
15771                 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15772                         deleteFlags | REMOVE_CHATTY, info, true, null);
15773             }
15774             synchronized (mPackages) {
15775                 if (res) {
15776                     mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15777                 }
15778             }
15779         }
15780
15781         if (res) {
15782             final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15783             info.sendPackageRemovedBroadcasts(killApp);
15784             info.sendSystemPackageUpdatedBroadcasts();
15785             info.sendSystemPackageAppearedBroadcasts();
15786         }
15787         // Force a gc here.
15788         Runtime.getRuntime().gc();
15789         // Delete the resources here after sending the broadcast to let
15790         // other processes clean up before deleting resources.
15791         if (info.args != null) {
15792             synchronized (mInstallLock) {
15793                 info.args.doPostDeleteLI(true);
15794             }
15795         }
15796
15797         return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15798     }
15799
15800     class PackageRemovedInfo {
15801         String removedPackage;
15802         int uid = -1;
15803         int removedAppId = -1;
15804         int[] origUsers;
15805         int[] removedUsers = null;
15806         boolean isRemovedPackageSystemUpdate = false;
15807         boolean isUpdate;
15808         boolean dataRemoved;
15809         boolean removedForAllUsers;
15810         // Clean up resources deleted packages.
15811         InstallArgs args = null;
15812         ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15813         ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15814
15815         void sendPackageRemovedBroadcasts(boolean killApp) {
15816             sendPackageRemovedBroadcastInternal(killApp);
15817             final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15818             for (int i = 0; i < childCount; i++) {
15819                 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15820                 childInfo.sendPackageRemovedBroadcastInternal(killApp);
15821             }
15822         }
15823
15824         void sendSystemPackageUpdatedBroadcasts() {
15825             if (isRemovedPackageSystemUpdate) {
15826                 sendSystemPackageUpdatedBroadcastsInternal();
15827                 final int childCount = (removedChildPackages != null)
15828                         ? removedChildPackages.size() : 0;
15829                 for (int i = 0; i < childCount; i++) {
15830                     PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15831                     if (childInfo.isRemovedPackageSystemUpdate) {
15832                         childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15833                     }
15834                 }
15835             }
15836         }
15837
15838         void sendSystemPackageAppearedBroadcasts() {
15839             final int packageCount = (appearedChildPackages != null)
15840                     ? appearedChildPackages.size() : 0;
15841             for (int i = 0; i < packageCount; i++) {
15842                 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15843                 for (int userId : installedInfo.newUsers) {
15844                     sendPackageAddedForUser(installedInfo.name, true,
15845                             UserHandle.getAppId(installedInfo.uid), userId);
15846                 }
15847             }
15848         }
15849
15850         private void sendSystemPackageUpdatedBroadcastsInternal() {
15851             Bundle extras = new Bundle(2);
15852             extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15853             extras.putBoolean(Intent.EXTRA_REPLACING, true);
15854             sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15855                     extras, 0, null, null, null);
15856             sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15857                     extras, 0, null, null, null);
15858             sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15859                     null, 0, removedPackage, null, null);
15860         }
15861
15862         private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15863             Bundle extras = new Bundle(2);
15864             extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15865             extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15866             extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15867             if (isUpdate || isRemovedPackageSystemUpdate) {
15868                 extras.putBoolean(Intent.EXTRA_REPLACING, true);
15869             }
15870             extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15871             if (removedPackage != null) {
15872                 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15873                         extras, 0, null, null, removedUsers);
15874                 if (dataRemoved && !isRemovedPackageSystemUpdate) {
15875                     sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15876                             removedPackage, extras, 0, null, null, removedUsers);
15877                 }
15878             }
15879             if (removedAppId >= 0) {
15880                 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15881                         removedUsers);
15882             }
15883         }
15884     }
15885
15886     /*
15887      * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15888      * flag is not set, the data directory is removed as well.
15889      * make sure this flag is set for partially installed apps. If not its meaningless to
15890      * delete a partially installed application.
15891      */
15892     private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15893             PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15894         String packageName = ps.name;
15895         if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15896         // Retrieve object to delete permissions for shared user later on
15897         final PackageParser.Package deletedPkg;
15898         final PackageSetting deletedPs;
15899         // reader
15900         synchronized (mPackages) {
15901             deletedPkg = mPackages.get(packageName);
15902             deletedPs = mSettings.mPackages.get(packageName);
15903             if (outInfo != null) {
15904                 outInfo.removedPackage = packageName;
15905                 outInfo.removedUsers = deletedPs != null
15906                         ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15907                         : null;
15908             }
15909         }
15910
15911         removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15912
15913         if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15914             final PackageParser.Package resolvedPkg;
15915             if (deletedPkg != null) {
15916                 resolvedPkg = deletedPkg;
15917             } else {
15918                 // We don't have a parsed package when it lives on an ejected
15919                 // adopted storage device, so fake something together
15920                 resolvedPkg = new PackageParser.Package(ps.name);
15921                 resolvedPkg.setVolumeUuid(ps.volumeUuid);
15922             }
15923             destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15924                     StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15925             destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15926             if (outInfo != null) {
15927                 outInfo.dataRemoved = true;
15928             }
15929             schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15930         }
15931
15932         // writer
15933         synchronized (mPackages) {
15934             if (deletedPs != null) {
15935                 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15936                     clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15937                     clearDefaultBrowserIfNeeded(packageName);
15938                     if (outInfo != null) {
15939                         mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15940                         outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15941                     }
15942                     updatePermissionsLPw(deletedPs.name, null, 0);
15943                     if (deletedPs.sharedUser != null) {
15944                         // Remove permissions associated with package. Since runtime
15945                         // permissions are per user we have to kill the removed package
15946                         // or packages running under the shared user of the removed
15947                         // package if revoking the permissions requested only by the removed
15948                         // package is successful and this causes a change in gids.
15949                         for (int userId : UserManagerService.getInstance().getUserIds()) {
15950                             final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15951                                     userId);
15952                             if (userIdToKill == UserHandle.USER_ALL
15953                                     || userIdToKill >= UserHandle.USER_SYSTEM) {
15954                                 // If gids changed for this user, kill all affected packages.
15955                                 mHandler.post(new Runnable() {
15956                                     @Override
15957                                     public void run() {
15958                                         // This has to happen with no lock held.
15959                                         killApplication(deletedPs.name, deletedPs.appId,
15960                                                 KILL_APP_REASON_GIDS_CHANGED);
15961                                     }
15962                                 });
15963                                 break;
15964                             }
15965                         }
15966                     }
15967                     clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15968                 }
15969                 // make sure to preserve per-user disabled state if this removal was just
15970                 // a downgrade of a system app to the factory package
15971                 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15972                     if (DEBUG_REMOVE) {
15973                         Slog.d(TAG, "Propagating install state across downgrade");
15974                     }
15975                     for (int userId : allUserHandles) {
15976                         final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15977                         if (DEBUG_REMOVE) {
15978                             Slog.d(TAG, "    user " + userId + " => " + installed);
15979                         }
15980                         ps.setInstalled(installed, userId);
15981                     }
15982                 }
15983             }
15984             // can downgrade to reader
15985             if (writeSettings) {
15986                 // Save settings now
15987                 mSettings.writeLPr();
15988             }
15989         }
15990         if (outInfo != null) {
15991             // A user ID was deleted here. Go through all users and remove it
15992             // from KeyStore.
15993             removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15994         }
15995     }
15996
15997     static boolean locationIsPrivileged(File path) {
15998         try {
15999             final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16000                     .getCanonicalPath();
16001             return path.getCanonicalPath().startsWith(privilegedAppDir);
16002         } catch (IOException e) {
16003             Slog.e(TAG, "Unable to access code path " + path);
16004         }
16005         return false;
16006     }
16007
16008     /*
16009      * Tries to delete system package.
16010      */
16011     private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16012             PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16013             boolean writeSettings) {
16014         if (deletedPs.parentPackageName != null) {
16015             Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16016             return false;
16017         }
16018
16019         final boolean applyUserRestrictions
16020                 = (allUserHandles != null) && (outInfo.origUsers != null);
16021         final PackageSetting disabledPs;
16022         // Confirm if the system package has been updated
16023         // An updated system app can be deleted. This will also have to restore
16024         // the system pkg from system partition
16025         // reader
16026         synchronized (mPackages) {
16027             disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16028         }
16029
16030         if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16031                 + " disabledPs=" + disabledPs);
16032
16033         if (disabledPs == null) {
16034             Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16035             return false;
16036         } else if (DEBUG_REMOVE) {
16037             Slog.d(TAG, "Deleting system pkg from data partition");
16038         }
16039
16040         if (DEBUG_REMOVE) {
16041             if (applyUserRestrictions) {
16042                 Slog.d(TAG, "Remembering install states:");
16043                 for (int userId : allUserHandles) {
16044                     final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16045                     Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
16046                 }
16047             }
16048         }
16049
16050         // Delete the updated package
16051         outInfo.isRemovedPackageSystemUpdate = true;
16052         if (outInfo.removedChildPackages != null) {
16053             final int childCount = (deletedPs.childPackageNames != null)
16054                     ? deletedPs.childPackageNames.size() : 0;
16055             for (int i = 0; i < childCount; i++) {
16056                 String childPackageName = deletedPs.childPackageNames.get(i);
16057                 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16058                         .contains(childPackageName)) {
16059                     PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16060                             childPackageName);
16061                     if (childInfo != null) {
16062                         childInfo.isRemovedPackageSystemUpdate = true;
16063                     }
16064                 }
16065             }
16066         }
16067
16068         if (disabledPs.versionCode < deletedPs.versionCode) {
16069             // Delete data for downgrades
16070             flags &= ~PackageManager.DELETE_KEEP_DATA;
16071         } else {
16072             // Preserve data by setting flag
16073             flags |= PackageManager.DELETE_KEEP_DATA;
16074         }
16075
16076         boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16077                 outInfo, writeSettings, disabledPs.pkg);
16078         if (!ret) {
16079             return false;
16080         }
16081
16082         // writer
16083         synchronized (mPackages) {
16084             // Reinstate the old system package
16085             enableSystemPackageLPw(disabledPs.pkg);
16086             // Remove any native libraries from the upgraded package.
16087             removeNativeBinariesLI(deletedPs);
16088         }
16089
16090         // Install the system package
16091         if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16092         int parseFlags = mDefParseFlags
16093                 | PackageParser.PARSE_MUST_BE_APK
16094                 | PackageParser.PARSE_IS_SYSTEM
16095                 | PackageParser.PARSE_IS_SYSTEM_DIR;
16096         if (locationIsPrivileged(disabledPs.codePath)) {
16097             parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16098         }
16099
16100         final PackageParser.Package newPkg;
16101         try {
16102             newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
16103         } catch (PackageManagerException e) {
16104             Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16105                     + e.getMessage());
16106             return false;
16107         }
16108         try {
16109             // update shared libraries for the newly re-installed system package
16110             updateSharedLibrariesLPw(newPkg, null);
16111         } catch (PackageManagerException e) {
16112             Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16113         }
16114
16115         prepareAppDataAfterInstallLIF(newPkg);
16116
16117         // writer
16118         synchronized (mPackages) {
16119             PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16120
16121             // Propagate the permissions state as we do not want to drop on the floor
16122             // runtime permissions. The update permissions method below will take
16123             // care of removing obsolete permissions and grant install permissions.
16124             ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16125             updatePermissionsLPw(newPkg.packageName, newPkg,
16126                     UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16127
16128             if (applyUserRestrictions) {
16129                 if (DEBUG_REMOVE) {
16130                     Slog.d(TAG, "Propagating install state across reinstall");
16131                 }
16132                 for (int userId : allUserHandles) {
16133                     final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16134                     if (DEBUG_REMOVE) {
16135                         Slog.d(TAG, "    user " + userId + " => " + installed);
16136                     }
16137                     ps.setInstalled(installed, userId);
16138
16139                     mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16140                 }
16141                 // Regardless of writeSettings we need to ensure that this restriction
16142                 // state propagation is persisted
16143                 mSettings.writeAllUsersPackageRestrictionsLPr();
16144             }
16145             // can downgrade to reader here
16146             if (writeSettings) {
16147                 mSettings.writeLPr();
16148             }
16149         }
16150         return true;
16151     }
16152
16153     private boolean deleteInstalledPackageLIF(PackageSetting ps,
16154             boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16155             PackageRemovedInfo outInfo, boolean writeSettings,
16156             PackageParser.Package replacingPackage) {
16157         synchronized (mPackages) {
16158             if (outInfo != null) {
16159                 outInfo.uid = ps.appId;
16160             }
16161
16162             if (outInfo != null && outInfo.removedChildPackages != null) {
16163                 final int childCount = (ps.childPackageNames != null)
16164                         ? ps.childPackageNames.size() : 0;
16165                 for (int i = 0; i < childCount; i++) {
16166                     String childPackageName = ps.childPackageNames.get(i);
16167                     PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16168                     if (childPs == null) {
16169                         return false;
16170                     }
16171                     PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16172                             childPackageName);
16173                     if (childInfo != null) {
16174                         childInfo.uid = childPs.appId;
16175                     }
16176                 }
16177             }
16178         }
16179
16180         // Delete package data from internal structures and also remove data if flag is set
16181         removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16182
16183         // Delete the child packages data
16184         final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16185         for (int i = 0; i < childCount; i++) {
16186             PackageSetting childPs;
16187             synchronized (mPackages) {
16188                 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16189             }
16190             if (childPs != null) {
16191                 PackageRemovedInfo childOutInfo = (outInfo != null
16192                         && outInfo.removedChildPackages != null)
16193                         ? outInfo.removedChildPackages.get(childPs.name) : null;
16194                 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16195                         && (replacingPackage != null
16196                         && !replacingPackage.hasChildPackage(childPs.name))
16197                         ? flags & ~DELETE_KEEP_DATA : flags;
16198                 removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16199                         deleteFlags, writeSettings);
16200             }
16201         }
16202
16203         // Delete application code and resources only for parent packages
16204         if (ps.parentPackageName == null) {
16205             if (deleteCodeAndResources && (outInfo != null)) {
16206                 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16207                         ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16208                 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16209             }
16210         }
16211
16212         return true;
16213     }
16214
16215     @Override
16216     public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16217             int userId) {
16218         mContext.enforceCallingOrSelfPermission(
16219                 android.Manifest.permission.DELETE_PACKAGES, null);
16220         synchronized (mPackages) {
16221             PackageSetting ps = mSettings.mPackages.get(packageName);
16222             if (ps == null) {
16223                 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16224                 return false;
16225             }
16226             if (!ps.getInstalled(userId)) {
16227                 // Can't block uninstall for an app that is not installed or enabled.
16228                 Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16229                 return false;
16230             }
16231             ps.setBlockUninstall(blockUninstall, userId);
16232             mSettings.writePackageRestrictionsLPr(userId);
16233         }
16234         return true;
16235     }
16236
16237     @Override
16238     public boolean getBlockUninstallForUser(String packageName, int userId) {
16239         synchronized (mPackages) {
16240             PackageSetting ps = mSettings.mPackages.get(packageName);
16241             if (ps == null) {
16242                 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16243                 return false;
16244             }
16245             return ps.getBlockUninstall(userId);
16246         }
16247     }
16248
16249     @Override
16250     public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16251         int callingUid = Binder.getCallingUid();
16252         if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16253             throw new SecurityException(
16254                     "setRequiredForSystemUser can only be run by the system or root");
16255         }
16256         synchronized (mPackages) {
16257             PackageSetting ps = mSettings.mPackages.get(packageName);
16258             if (ps == null) {
16259                 Log.w(TAG, "Package doesn't exist: " + packageName);
16260                 return false;
16261             }
16262             if (systemUserApp) {
16263                 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16264             } else {
16265                 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16266             }
16267             mSettings.writeLPr();
16268         }
16269         return true;
16270     }
16271
16272     /*
16273      * This method handles package deletion in general
16274      */
16275     private boolean deletePackageLIF(String packageName, UserHandle user,
16276             boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16277             PackageRemovedInfo outInfo, boolean writeSettings,
16278             PackageParser.Package replacingPackage) {
16279         if (packageName == null) {
16280             Slog.w(TAG, "Attempt to delete null packageName.");
16281             return false;
16282         }
16283
16284         if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16285
16286         PackageSetting ps;
16287
16288         synchronized (mPackages) {
16289             ps = mSettings.mPackages.get(packageName);
16290             if (ps == null) {
16291                 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16292                 return false;
16293             }
16294
16295             if (ps.parentPackageName != null && (!isSystemApp(ps)
16296                     || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16297                 if (DEBUG_REMOVE) {
16298                     Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16299                             + ((user == null) ? UserHandle.USER_ALL : user));
16300                 }
16301                 final int removedUserId = (user != null) ? user.getIdentifier()
16302                         : UserHandle.USER_ALL;
16303                 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16304                     return false;
16305                 }
16306                 markPackageUninstalledForUserLPw(ps, user);
16307                 scheduleWritePackageRestrictionsLocked(user);
16308                 return true;
16309             }
16310         }
16311
16312         if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16313                 && user.getIdentifier() != UserHandle.USER_ALL)) {
16314             // The caller is asking that the package only be deleted for a single
16315             // user.  To do this, we just mark its uninstalled state and delete
16316             // its data. If this is a system app, we only allow this to happen if
16317             // they have set the special DELETE_SYSTEM_APP which requests different
16318             // semantics than normal for uninstalling system apps.
16319             markPackageUninstalledForUserLPw(ps, user);
16320
16321             if (!isSystemApp(ps)) {
16322                 // Do not uninstall the APK if an app should be cached
16323                 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16324                 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16325                     // Other user still have this package installed, so all
16326                     // we need to do is clear this user's data and save that
16327                     // it is uninstalled.
16328                     if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16329                     if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16330                         return false;
16331                     }
16332                     scheduleWritePackageRestrictionsLocked(user);
16333                     return true;
16334                 } else {
16335                     // We need to set it back to 'installed' so the uninstall
16336                     // broadcasts will be sent correctly.
16337                     if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16338                     ps.setInstalled(true, user.getIdentifier());
16339                 }
16340             } else {
16341                 // This is a system app, so we assume that the
16342                 // other users still have this package installed, so all
16343                 // we need to do is clear this user's data and save that
16344                 // it is uninstalled.
16345                 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16346                 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16347                     return false;
16348                 }
16349                 scheduleWritePackageRestrictionsLocked(user);
16350                 return true;
16351             }
16352         }
16353
16354         // If we are deleting a composite package for all users, keep track
16355         // of result for each child.
16356         if (ps.childPackageNames != null && outInfo != null) {
16357             synchronized (mPackages) {
16358                 final int childCount = ps.childPackageNames.size();
16359                 outInfo.removedChildPackages = new ArrayMap<>(childCount);
16360                 for (int i = 0; i < childCount; i++) {
16361                     String childPackageName = ps.childPackageNames.get(i);
16362                     PackageRemovedInfo childInfo = new PackageRemovedInfo();
16363                     childInfo.removedPackage = childPackageName;
16364                     outInfo.removedChildPackages.put(childPackageName, childInfo);
16365                     PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16366                     if (childPs != null) {
16367                         childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16368                     }
16369                 }
16370             }
16371         }
16372
16373         boolean ret = false;
16374         if (isSystemApp(ps)) {
16375             if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16376             // When an updated system application is deleted we delete the existing resources
16377             // as well and fall back to existing code in system partition
16378             ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16379         } else {
16380             if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16381             ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16382                     outInfo, writeSettings, replacingPackage);
16383         }
16384
16385         // Take a note whether we deleted the package for all users
16386         if (outInfo != null) {
16387             outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16388             if (outInfo.removedChildPackages != null) {
16389                 synchronized (mPackages) {
16390                     final int childCount = outInfo.removedChildPackages.size();
16391                     for (int i = 0; i < childCount; i++) {
16392                         PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16393                         if (childInfo != null) {
16394                             childInfo.removedForAllUsers = mPackages.get(
16395                                     childInfo.removedPackage) == null;
16396                         }
16397                     }
16398                 }
16399             }
16400             // If we uninstalled an update to a system app there may be some
16401             // child packages that appeared as they are declared in the system
16402             // app but were not declared in the update.
16403             if (isSystemApp(ps)) {
16404                 synchronized (mPackages) {
16405                     PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16406                     final int childCount = (updatedPs.childPackageNames != null)
16407                             ? updatedPs.childPackageNames.size() : 0;
16408                     for (int i = 0; i < childCount; i++) {
16409                         String childPackageName = updatedPs.childPackageNames.get(i);
16410                         if (outInfo.removedChildPackages == null
16411                                 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16412                             PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16413                             if (childPs == null) {
16414                                 continue;
16415                             }
16416                             PackageInstalledInfo installRes = new PackageInstalledInfo();
16417                             installRes.name = childPackageName;
16418                             installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16419                             installRes.pkg = mPackages.get(childPackageName);
16420                             installRes.uid = childPs.pkg.applicationInfo.uid;
16421                             if (outInfo.appearedChildPackages == null) {
16422                                 outInfo.appearedChildPackages = new ArrayMap<>();
16423                             }
16424                             outInfo.appearedChildPackages.put(childPackageName, installRes);
16425                         }
16426                     }
16427                 }
16428             }
16429         }
16430
16431         return ret;
16432     }
16433
16434     private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16435         final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16436                 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16437         for (int nextUserId : userIds) {
16438             if (DEBUG_REMOVE) {
16439                 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16440             }
16441             ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16442                     false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16443                     false /*hidden*/, false /*suspended*/, null, null, null,
16444                     false /*blockUninstall*/,
16445                     ps.readUserState(nextUserId).domainVerificationStatus, 0);
16446         }
16447     }
16448
16449     private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16450             PackageRemovedInfo outInfo) {
16451         final PackageParser.Package pkg;
16452         synchronized (mPackages) {
16453             pkg = mPackages.get(ps.name);
16454         }
16455
16456         final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16457                 : new int[] {userId};
16458         for (int nextUserId : userIds) {
16459             if (DEBUG_REMOVE) {
16460                 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16461                         + nextUserId);
16462             }
16463
16464             destroyAppDataLIF(pkg, userId,
16465                     StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16466             destroyAppProfilesLIF(pkg, userId);
16467             removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16468             schedulePackageCleaning(ps.name, nextUserId, false);
16469             synchronized (mPackages) {
16470                 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16471                     scheduleWritePackageRestrictionsLocked(nextUserId);
16472                 }
16473                 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16474             }
16475         }
16476
16477         if (outInfo != null) {
16478             outInfo.removedPackage = ps.name;
16479             outInfo.removedAppId = ps.appId;
16480             outInfo.removedUsers = userIds;
16481         }
16482
16483         return true;
16484     }
16485
16486     private final class ClearStorageConnection implements ServiceConnection {
16487         IMediaContainerService mContainerService;
16488
16489         @Override
16490         public void onServiceConnected(ComponentName name, IBinder service) {
16491             synchronized (this) {
16492                 mContainerService = IMediaContainerService.Stub.asInterface(service);
16493                 notifyAll();
16494             }
16495         }
16496
16497         @Override
16498         public void onServiceDisconnected(ComponentName name) {
16499         }
16500     }
16501
16502     private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16503         if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16504
16505         final boolean mounted;
16506         if (Environment.isExternalStorageEmulated()) {
16507             mounted = true;
16508         } else {
16509             final String status = Environment.getExternalStorageState();
16510
16511             mounted = status.equals(Environment.MEDIA_MOUNTED)
16512                     || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16513         }
16514
16515         if (!mounted) {
16516             return;
16517         }
16518
16519         final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16520         int[] users;
16521         if (userId == UserHandle.USER_ALL) {
16522             users = sUserManager.getUserIds();
16523         } else {
16524             users = new int[] { userId };
16525         }
16526         final ClearStorageConnection conn = new ClearStorageConnection();
16527         if (mContext.bindServiceAsUser(
16528                 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16529             try {
16530                 for (int curUser : users) {
16531                     long timeout = SystemClock.uptimeMillis() + 5000;
16532                     synchronized (conn) {
16533                         long now;
16534                         while (conn.mContainerService == null &&
16535                                 (now = SystemClock.uptimeMillis()) < timeout) {
16536                             try {
16537                                 conn.wait(timeout - now);
16538                             } catch (InterruptedException e) {
16539                             }
16540                         }
16541                     }
16542                     if (conn.mContainerService == null) {
16543                         return;
16544                     }
16545
16546                     final UserEnvironment userEnv = new UserEnvironment(curUser);
16547                     clearDirectory(conn.mContainerService,
16548                             userEnv.buildExternalStorageAppCacheDirs(packageName));
16549                     if (allData) {
16550                         clearDirectory(conn.mContainerService,
16551                                 userEnv.buildExternalStorageAppDataDirs(packageName));
16552                         clearDirectory(conn.mContainerService,
16553                                 userEnv.buildExternalStorageAppMediaDirs(packageName));
16554                     }
16555                 }
16556             } finally {
16557                 mContext.unbindService(conn);
16558             }
16559         }
16560     }
16561
16562     @Override
16563     public void clearApplicationProfileData(String packageName) {
16564         enforceSystemOrRoot("Only the system can clear all profile data");
16565
16566         final PackageParser.Package pkg;
16567         synchronized (mPackages) {
16568             pkg = mPackages.get(packageName);
16569         }
16570
16571         try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16572             synchronized (mInstallLock) {
16573                 clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16574                 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16575                         true /* removeBaseMarker */);
16576             }
16577         }
16578     }
16579
16580     @Override
16581     public void clearApplicationUserData(final String packageName,
16582             final IPackageDataObserver observer, final int userId) {
16583         mContext.enforceCallingOrSelfPermission(
16584                 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16585
16586         enforceCrossUserPermission(Binder.getCallingUid(), userId,
16587                 true /* requireFullPermission */, false /* checkShell */, "clear application data");
16588
16589         if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16590             throw new SecurityException("Cannot clear data for a protected package: "
16591                     + packageName);
16592         }
16593         // Queue up an async operation since the package deletion may take a little while.
16594         mHandler.post(new Runnable() {
16595             public void run() {
16596                 mHandler.removeCallbacks(this);
16597                 final boolean succeeded;
16598                 try (PackageFreezer freezer = freezePackage(packageName,
16599                         "clearApplicationUserData")) {
16600                     synchronized (mInstallLock) {
16601                         succeeded = clearApplicationUserDataLIF(packageName, userId);
16602                     }
16603                     clearExternalStorageDataSync(packageName, userId, true);
16604                 }
16605                 if (succeeded) {
16606                     // invoke DeviceStorageMonitor's update method to clear any notifications
16607                     DeviceStorageMonitorInternal dsm = LocalServices
16608                             .getService(DeviceStorageMonitorInternal.class);
16609                     if (dsm != null) {
16610                         dsm.checkMemory();
16611                     }
16612                 }
16613                 if(observer != null) {
16614                     try {
16615                         observer.onRemoveCompleted(packageName, succeeded);
16616                     } catch (RemoteException e) {
16617                         Log.i(TAG, "Observer no longer exists.");
16618                     }
16619                 } //end if observer
16620             } //end run
16621         });
16622     }
16623
16624     private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16625         if (packageName == null) {
16626             Slog.w(TAG, "Attempt to delete null packageName.");
16627             return false;
16628         }
16629
16630         // Try finding details about the requested package
16631         PackageParser.Package pkg;
16632         synchronized (mPackages) {
16633             pkg = mPackages.get(packageName);
16634             if (pkg == null) {
16635                 final PackageSetting ps = mSettings.mPackages.get(packageName);
16636                 if (ps != null) {
16637                     pkg = ps.pkg;
16638                 }
16639             }
16640
16641             if (pkg == null) {
16642                 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16643                 return false;
16644             }
16645
16646             PackageSetting ps = (PackageSetting) pkg.mExtras;
16647             resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16648         }
16649
16650         clearAppDataLIF(pkg, userId,
16651                 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16652
16653         final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16654         removeKeystoreDataIfNeeded(userId, appId);
16655
16656         UserManagerInternal umInternal = getUserManagerInternal();
16657         final int flags;
16658         if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16659             flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16660         } else if (umInternal.isUserRunning(userId)) {
16661             flags = StorageManager.FLAG_STORAGE_DE;
16662         } else {
16663             flags = 0;
16664         }
16665         prepareAppDataContentsLIF(pkg, userId, flags);
16666
16667         return true;
16668     }
16669
16670     /**
16671      * Reverts user permission state changes (permissions and flags) in
16672      * all packages for a given user.
16673      *
16674      * @param userId The device user for which to do a reset.
16675      */
16676     private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16677         final int packageCount = mPackages.size();
16678         for (int i = 0; i < packageCount; i++) {
16679             PackageParser.Package pkg = mPackages.valueAt(i);
16680             PackageSetting ps = (PackageSetting) pkg.mExtras;
16681             resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16682         }
16683     }
16684
16685     private void resetNetworkPolicies(int userId) {
16686         LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16687     }
16688
16689     /**
16690      * Reverts user permission state changes (permissions and flags).
16691      *
16692      * @param ps The package for which to reset.
16693      * @param userId The device user for which to do a reset.
16694      */
16695     private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16696             final PackageSetting ps, final int userId) {
16697         if (ps.pkg == null) {
16698             return;
16699         }
16700
16701         // These are flags that can change base on user actions.
16702         final int userSettableMask = FLAG_PERMISSION_USER_SET
16703                 | FLAG_PERMISSION_USER_FIXED
16704                 | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16705                 | FLAG_PERMISSION_REVIEW_REQUIRED;
16706
16707         final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16708                 | FLAG_PERMISSION_POLICY_FIXED;
16709
16710         boolean writeInstallPermissions = false;
16711         boolean writeRuntimePermissions = false;
16712
16713         final int permissionCount = ps.pkg.requestedPermissions.size();
16714         for (int i = 0; i < permissionCount; i++) {
16715             String permission = ps.pkg.requestedPermissions.get(i);
16716
16717             BasePermission bp = mSettings.mPermissions.get(permission);
16718             if (bp == null) {
16719                 continue;
16720             }
16721
16722             // If shared user we just reset the state to which only this app contributed.
16723             if (ps.sharedUser != null) {
16724                 boolean used = false;
16725                 final int packageCount = ps.sharedUser.packages.size();
16726                 for (int j = 0; j < packageCount; j++) {
16727                     PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16728                     if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16729                             && pkg.pkg.requestedPermissions.contains(permission)) {
16730                         used = true;
16731                         break;
16732                     }
16733                 }
16734                 if (used) {
16735                     continue;
16736                 }
16737             }
16738
16739             PermissionsState permissionsState = ps.getPermissionsState();
16740
16741             final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16742
16743             // Always clear the user settable flags.
16744             final boolean hasInstallState = permissionsState.getInstallPermissionState(
16745                     bp.name) != null;
16746             // If permission review is enabled and this is a legacy app, mark the
16747             // permission as requiring a review as this is the initial state.
16748             int flags = 0;
16749             if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
16750                     && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16751                 flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16752             }
16753             if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16754                 if (hasInstallState) {
16755                     writeInstallPermissions = true;
16756                 } else {
16757                     writeRuntimePermissions = true;
16758                 }
16759             }
16760
16761             // Below is only runtime permission handling.
16762             if (!bp.isRuntime()) {
16763                 continue;
16764             }
16765
16766             // Never clobber system or policy.
16767             if ((oldFlags & policyOrSystemFlags) != 0) {
16768                 continue;
16769             }
16770
16771             // If this permission was granted by default, make sure it is.
16772             if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16773                 if (permissionsState.grantRuntimePermission(bp, userId)
16774                         != PERMISSION_OPERATION_FAILURE) {
16775                     writeRuntimePermissions = true;
16776                 }
16777             // If permission review is enabled the permissions for a legacy apps
16778             // are represented as constantly granted runtime ones, so don't revoke.
16779             } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16780                 // Otherwise, reset the permission.
16781                 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16782                 switch (revokeResult) {
16783                     case PERMISSION_OPERATION_SUCCESS:
16784                     case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16785                         writeRuntimePermissions = true;
16786                         final int appId = ps.appId;
16787                         mHandler.post(new Runnable() {
16788                             @Override
16789                             public void run() {
16790                                 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16791                             }
16792                         });
16793                     } break;
16794                 }
16795             }
16796         }
16797
16798         // Synchronously write as we are taking permissions away.
16799         if (writeRuntimePermissions) {
16800             mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16801         }
16802
16803         // Synchronously write as we are taking permissions away.
16804         if (writeInstallPermissions) {
16805             mSettings.writeLPr();
16806         }
16807     }
16808
16809     /**
16810      * Remove entries from the keystore daemon. Will only remove it if the
16811      * {@code appId} is valid.
16812      */
16813     private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16814         if (appId < 0) {
16815             return;
16816         }
16817
16818         final KeyStore keyStore = KeyStore.getInstance();
16819         if (keyStore != null) {
16820             if (userId == UserHandle.USER_ALL) {
16821                 for (final int individual : sUserManager.getUserIds()) {
16822                     keyStore.clearUid(UserHandle.getUid(individual, appId));
16823                 }
16824             } else {
16825                 keyStore.clearUid(UserHandle.getUid(userId, appId));
16826             }
16827         } else {
16828             Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16829         }
16830     }
16831
16832     @Override
16833     public void deleteApplicationCacheFiles(final String packageName,
16834             final IPackageDataObserver observer) {
16835         final int userId = UserHandle.getCallingUserId();
16836         deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16837     }
16838
16839     @Override
16840     public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16841             final IPackageDataObserver observer) {
16842         mContext.enforceCallingOrSelfPermission(
16843                 android.Manifest.permission.DELETE_CACHE_FILES, null);
16844         enforceCrossUserPermission(Binder.getCallingUid(), userId,
16845                 /* requireFullPermission= */ true, /* checkShell= */ false,
16846                 "delete application cache files");
16847
16848         final PackageParser.Package pkg;
16849         synchronized (mPackages) {
16850             pkg = mPackages.get(packageName);
16851         }
16852
16853         // Queue up an async operation since the package deletion may take a little while.
16854         mHandler.post(new Runnable() {
16855             public void run() {
16856                 synchronized (mInstallLock) {
16857                     final int flags = StorageManager.FLAG_STORAGE_DE
16858                             | StorageManager.FLAG_STORAGE_CE;
16859                     // We're only clearing cache files, so we don't care if the
16860                     // app is unfrozen and still able to run
16861                     clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16862                     clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16863                 }
16864                 clearExternalStorageDataSync(packageName, userId, false);
16865                 if (observer != null) {
16866                     try {
16867                         observer.onRemoveCompleted(packageName, true);
16868                     } catch (RemoteException e) {
16869                         Log.i(TAG, "Observer no longer exists.");
16870                     }
16871                 }
16872             }
16873         });
16874     }
16875
16876     @Override
16877     public void getPackageSizeInfo(final String packageName, int userHandle,
16878             final IPackageStatsObserver observer) {
16879         mContext.enforceCallingOrSelfPermission(
16880                 android.Manifest.permission.GET_PACKAGE_SIZE, null);
16881         if (packageName == null) {
16882             throw new IllegalArgumentException("Attempt to get size of null packageName");
16883         }
16884
16885         PackageStats stats = new PackageStats(packageName, userHandle);
16886
16887         /*
16888          * Queue up an async operation since the package measurement may take a
16889          * little while.
16890          */
16891         Message msg = mHandler.obtainMessage(INIT_COPY);
16892         msg.obj = new MeasureParams(stats, observer);
16893         mHandler.sendMessage(msg);
16894     }
16895
16896     private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16897         final PackageSetting ps;
16898         synchronized (mPackages) {
16899             ps = mSettings.mPackages.get(packageName);
16900             if (ps == null) {
16901                 Slog.w(TAG, "Failed to find settings for " + packageName);
16902                 return false;
16903             }
16904         }
16905         try {
16906             mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16907                     StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16908                     ps.getCeDataInode(userId), ps.codePathString, stats);
16909         } catch (InstallerException e) {
16910             Slog.w(TAG, String.valueOf(e));
16911             return false;
16912         }
16913
16914         // For now, ignore code size of packages on system partition
16915         if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16916             stats.codeSize = 0;
16917         }
16918
16919         return true;
16920     }
16921
16922     private int getUidTargetSdkVersionLockedLPr(int uid) {
16923         Object obj = mSettings.getUserIdLPr(uid);
16924         if (obj instanceof SharedUserSetting) {
16925             final SharedUserSetting sus = (SharedUserSetting) obj;
16926             int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16927             final Iterator<PackageSetting> it = sus.packages.iterator();
16928             while (it.hasNext()) {
16929                 final PackageSetting ps = it.next();
16930                 if (ps.pkg != null) {
16931                     int v = ps.pkg.applicationInfo.targetSdkVersion;
16932                     if (v < vers) vers = v;
16933                 }
16934             }
16935             return vers;
16936         } else if (obj instanceof PackageSetting) {
16937             final PackageSetting ps = (PackageSetting) obj;
16938             if (ps.pkg != null) {
16939                 return ps.pkg.applicationInfo.targetSdkVersion;
16940             }
16941         }
16942         return Build.VERSION_CODES.CUR_DEVELOPMENT;
16943     }
16944
16945     @Override
16946     public void addPreferredActivity(IntentFilter filter, int match,
16947             ComponentName[] set, ComponentName activity, int userId) {
16948         addPreferredActivityInternal(filter, match, set, activity, true, userId,
16949                 "Adding preferred");
16950     }
16951
16952     private void addPreferredActivityInternal(IntentFilter filter, int match,
16953             ComponentName[] set, ComponentName activity, boolean always, int userId,
16954             String opname) {
16955         // writer
16956         int callingUid = Binder.getCallingUid();
16957         enforceCrossUserPermission(callingUid, userId,
16958                 true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16959         if (filter.countActions() == 0) {
16960             Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16961             return;
16962         }
16963         synchronized (mPackages) {
16964             if (mContext.checkCallingOrSelfPermission(
16965                     android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16966                     != PackageManager.PERMISSION_GRANTED) {
16967                 if (getUidTargetSdkVersionLockedLPr(callingUid)
16968                         < Build.VERSION_CODES.FROYO) {
16969                     Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16970                             + callingUid);
16971                     return;
16972                 }
16973                 mContext.enforceCallingOrSelfPermission(
16974                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16975             }
16976
16977             PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16978             Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16979                     + userId + ":");
16980             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16981             pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16982             scheduleWritePackageRestrictionsLocked(userId);
16983             postPreferredActivityChangedBroadcast(userId);
16984         }
16985     }
16986
16987     private void postPreferredActivityChangedBroadcast(int userId) {
16988         mHandler.post(() -> {
16989             final IActivityManager am = ActivityManagerNative.getDefault();
16990             if (am == null) {
16991                 return;
16992             }
16993
16994             final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
16995             intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
16996             try {
16997                 am.broadcastIntent(null, intent, null, null,
16998                         0, null, null, null, android.app.AppOpsManager.OP_NONE,
16999                         null, false, false, userId);
17000             } catch (RemoteException e) {
17001             }
17002         });
17003     }
17004
17005     @Override
17006     public void replacePreferredActivity(IntentFilter filter, int match,
17007             ComponentName[] set, ComponentName activity, int userId) {
17008         if (filter.countActions() != 1) {
17009             throw new IllegalArgumentException(
17010                     "replacePreferredActivity expects filter to have only 1 action.");
17011         }
17012         if (filter.countDataAuthorities() != 0
17013                 || filter.countDataPaths() != 0
17014                 || filter.countDataSchemes() > 1
17015                 || filter.countDataTypes() != 0) {
17016             throw new IllegalArgumentException(
17017                     "replacePreferredActivity expects filter to have no data authorities, " +
17018                     "paths, or types; and at most one scheme.");
17019         }
17020
17021         final int callingUid = Binder.getCallingUid();
17022         enforceCrossUserPermission(callingUid, userId,
17023                 true /* requireFullPermission */, false /* checkShell */,
17024                 "replace preferred activity");
17025         synchronized (mPackages) {
17026             if (mContext.checkCallingOrSelfPermission(
17027                     android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17028                     != PackageManager.PERMISSION_GRANTED) {
17029                 if (getUidTargetSdkVersionLockedLPr(callingUid)
17030                         < Build.VERSION_CODES.FROYO) {
17031                     Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17032                             + Binder.getCallingUid());
17033                     return;
17034                 }
17035                 mContext.enforceCallingOrSelfPermission(
17036                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17037             }
17038
17039             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17040             if (pir != null) {
17041                 // Get all of the existing entries that exactly match this filter.
17042                 ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17043                 if (existing != null && existing.size() == 1) {
17044                     PreferredActivity cur = existing.get(0);
17045                     if (DEBUG_PREFERRED) {
17046                         Slog.i(TAG, "Checking replace of preferred:");
17047                         filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17048                         if (!cur.mPref.mAlways) {
17049                             Slog.i(TAG, "  -- CUR; not mAlways!");
17050                         } else {
17051                             Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
17052                             Slog.i(TAG, "  -- CUR: mSet="
17053                                     + Arrays.toString(cur.mPref.mSetComponents));
17054                             Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
17055                             Slog.i(TAG, "  -- NEW: mMatch="
17056                                     + (match&IntentFilter.MATCH_CATEGORY_MASK));
17057                             Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
17058                             Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
17059                         }
17060                     }
17061                     if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17062                             && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17063                             && cur.mPref.sameSet(set)) {
17064                         // Setting the preferred activity to what it happens to be already
17065                         if (DEBUG_PREFERRED) {
17066                             Slog.i(TAG, "Replacing with same preferred activity "
17067                                     + cur.mPref.mShortComponent + " for user "
17068                                     + userId + ":");
17069                             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17070                         }
17071                         return;
17072                     }
17073                 }
17074
17075                 if (existing != null) {
17076                     if (DEBUG_PREFERRED) {
17077                         Slog.i(TAG, existing.size() + " existing preferred matches for:");
17078                         filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17079                     }
17080                     for (int i = 0; i < existing.size(); i++) {
17081                         PreferredActivity pa = existing.get(i);
17082                         if (DEBUG_PREFERRED) {
17083                             Slog.i(TAG, "Removing existing preferred activity "
17084                                     + pa.mPref.mComponent + ":");
17085                             pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17086                         }
17087                         pir.removeFilter(pa);
17088                     }
17089                 }
17090             }
17091             addPreferredActivityInternal(filter, match, set, activity, true, userId,
17092                     "Replacing preferred");
17093         }
17094     }
17095
17096     @Override
17097     public void clearPackagePreferredActivities(String packageName) {
17098         final int uid = Binder.getCallingUid();
17099         // writer
17100         synchronized (mPackages) {
17101             PackageParser.Package pkg = mPackages.get(packageName);
17102             if (pkg == null || pkg.applicationInfo.uid != uid) {
17103                 if (mContext.checkCallingOrSelfPermission(
17104                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17105                         != PackageManager.PERMISSION_GRANTED) {
17106                     if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17107                             < Build.VERSION_CODES.FROYO) {
17108                         Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17109                                 + Binder.getCallingUid());
17110                         return;
17111                     }
17112                     mContext.enforceCallingOrSelfPermission(
17113                             android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17114                 }
17115             }
17116
17117             int user = UserHandle.getCallingUserId();
17118             if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17119                 scheduleWritePackageRestrictionsLocked(user);
17120             }
17121         }
17122     }
17123
17124     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17125     boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17126         ArrayList<PreferredActivity> removed = null;
17127         boolean changed = false;
17128         for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17129             final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17130             PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17131             if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17132                 continue;
17133             }
17134             Iterator<PreferredActivity> it = pir.filterIterator();
17135             while (it.hasNext()) {
17136                 PreferredActivity pa = it.next();
17137                 // Mark entry for removal only if it matches the package name
17138                 // and the entry is of type "always".
17139                 if (packageName == null ||
17140                         (pa.mPref.mComponent.getPackageName().equals(packageName)
17141                                 && pa.mPref.mAlways)) {
17142                     if (removed == null) {
17143                         removed = new ArrayList<PreferredActivity>();
17144                     }
17145                     removed.add(pa);
17146                 }
17147             }
17148             if (removed != null) {
17149                 for (int j=0; j<removed.size(); j++) {
17150                     PreferredActivity pa = removed.get(j);
17151                     pir.removeFilter(pa);
17152                 }
17153                 changed = true;
17154             }
17155         }
17156         if (changed) {
17157             postPreferredActivityChangedBroadcast(userId);
17158         }
17159         return changed;
17160     }
17161
17162     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17163     private void clearIntentFilterVerificationsLPw(int userId) {
17164         final int packageCount = mPackages.size();
17165         for (int i = 0; i < packageCount; i++) {
17166             PackageParser.Package pkg = mPackages.valueAt(i);
17167             clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17168         }
17169     }
17170
17171     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17172     void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17173         if (userId == UserHandle.USER_ALL) {
17174             if (mSettings.removeIntentFilterVerificationLPw(packageName,
17175                     sUserManager.getUserIds())) {
17176                 for (int oneUserId : sUserManager.getUserIds()) {
17177                     scheduleWritePackageRestrictionsLocked(oneUserId);
17178                 }
17179             }
17180         } else {
17181             if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17182                 scheduleWritePackageRestrictionsLocked(userId);
17183             }
17184         }
17185     }
17186
17187     void clearDefaultBrowserIfNeeded(String packageName) {
17188         for (int oneUserId : sUserManager.getUserIds()) {
17189             String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17190             if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17191             if (packageName.equals(defaultBrowserPackageName)) {
17192                 setDefaultBrowserPackageName(null, oneUserId);
17193             }
17194         }
17195     }
17196
17197     @Override
17198     public void resetApplicationPreferences(int userId) {
17199         mContext.enforceCallingOrSelfPermission(
17200                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17201         final long identity = Binder.clearCallingIdentity();
17202         // writer
17203         try {
17204             synchronized (mPackages) {
17205                 clearPackagePreferredActivitiesLPw(null, userId);
17206                 mSettings.applyDefaultPreferredAppsLPw(this, userId);
17207                 // TODO: We have to reset the default SMS and Phone. This requires
17208                 // significant refactoring to keep all default apps in the package
17209                 // manager (cleaner but more work) or have the services provide
17210                 // callbacks to the package manager to request a default app reset.
17211                 applyFactoryDefaultBrowserLPw(userId);
17212                 clearIntentFilterVerificationsLPw(userId);
17213                 primeDomainVerificationsLPw(userId);
17214                 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17215                 scheduleWritePackageRestrictionsLocked(userId);
17216             }
17217             resetNetworkPolicies(userId);
17218         } finally {
17219             Binder.restoreCallingIdentity(identity);
17220         }
17221     }
17222
17223     @Override
17224     public int getPreferredActivities(List<IntentFilter> outFilters,
17225             List<ComponentName> outActivities, String packageName) {
17226
17227         int num = 0;
17228         final int userId = UserHandle.getCallingUserId();
17229         // reader
17230         synchronized (mPackages) {
17231             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17232             if (pir != null) {
17233                 final Iterator<PreferredActivity> it = pir.filterIterator();
17234                 while (it.hasNext()) {
17235                     final PreferredActivity pa = it.next();
17236                     if (packageName == null
17237                             || (pa.mPref.mComponent.getPackageName().equals(packageName)
17238                                     && pa.mPref.mAlways)) {
17239                         if (outFilters != null) {
17240                             outFilters.add(new IntentFilter(pa));
17241                         }
17242                         if (outActivities != null) {
17243                             outActivities.add(pa.mPref.mComponent);
17244                         }
17245                     }
17246                 }
17247             }
17248         }
17249
17250         return num;
17251     }
17252
17253     @Override
17254     public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17255             int userId) {
17256         int callingUid = Binder.getCallingUid();
17257         if (callingUid != Process.SYSTEM_UID) {
17258             throw new SecurityException(
17259                     "addPersistentPreferredActivity can only be run by the system");
17260         }
17261         if (filter.countActions() == 0) {
17262             Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17263             return;
17264         }
17265         synchronized (mPackages) {
17266             Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17267                     ":");
17268             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17269             mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17270                     new PersistentPreferredActivity(filter, activity));
17271             scheduleWritePackageRestrictionsLocked(userId);
17272             postPreferredActivityChangedBroadcast(userId);
17273         }
17274     }
17275
17276     @Override
17277     public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17278         int callingUid = Binder.getCallingUid();
17279         if (callingUid != Process.SYSTEM_UID) {
17280             throw new SecurityException(
17281                     "clearPackagePersistentPreferredActivities can only be run by the system");
17282         }
17283         ArrayList<PersistentPreferredActivity> removed = null;
17284         boolean changed = false;
17285         synchronized (mPackages) {
17286             for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17287                 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17288                 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17289                         .valueAt(i);
17290                 if (userId != thisUserId) {
17291                     continue;
17292                 }
17293                 Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17294                 while (it.hasNext()) {
17295                     PersistentPreferredActivity ppa = it.next();
17296                     // Mark entry for removal only if it matches the package name.
17297                     if (ppa.mComponent.getPackageName().equals(packageName)) {
17298                         if (removed == null) {
17299                             removed = new ArrayList<PersistentPreferredActivity>();
17300                         }
17301                         removed.add(ppa);
17302                     }
17303                 }
17304                 if (removed != null) {
17305                     for (int j=0; j<removed.size(); j++) {
17306                         PersistentPreferredActivity ppa = removed.get(j);
17307                         ppir.removeFilter(ppa);
17308                     }
17309                     changed = true;
17310                 }
17311             }
17312
17313             if (changed) {
17314                 scheduleWritePackageRestrictionsLocked(userId);
17315                 postPreferredActivityChangedBroadcast(userId);
17316             }
17317         }
17318     }
17319
17320     /**
17321      * Common machinery for picking apart a restored XML blob and passing
17322      * it to a caller-supplied functor to be applied to the running system.
17323      */
17324     private void restoreFromXml(XmlPullParser parser, int userId,
17325             String expectedStartTag, BlobXmlRestorer functor)
17326             throws IOException, XmlPullParserException {
17327         int type;
17328         while ((type = parser.next()) != XmlPullParser.START_TAG
17329                 && type != XmlPullParser.END_DOCUMENT) {
17330         }
17331         if (type != XmlPullParser.START_TAG) {
17332             // oops didn't find a start tag?!
17333             if (DEBUG_BACKUP) {
17334                 Slog.e(TAG, "Didn't find start tag during restore");
17335             }
17336             return;
17337         }
17338 Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17339         // this is supposed to be TAG_PREFERRED_BACKUP
17340         if (!expectedStartTag.equals(parser.getName())) {
17341             if (DEBUG_BACKUP) {
17342                 Slog.e(TAG, "Found unexpected tag " + parser.getName());
17343             }
17344             return;
17345         }
17346
17347         // skip interfering stuff, then we're aligned with the backing implementation
17348         while ((type = parser.next()) == XmlPullParser.TEXT) { }
17349 Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17350         functor.apply(parser, userId);
17351     }
17352
17353     private interface BlobXmlRestorer {
17354         public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17355     }
17356
17357     /**
17358      * Non-Binder method, support for the backup/restore mechanism: write the
17359      * full set of preferred activities in its canonical XML format.  Returns the
17360      * XML output as a byte array, or null if there is none.
17361      */
17362     @Override
17363     public byte[] getPreferredActivityBackup(int userId) {
17364         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17365             throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17366         }
17367
17368         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17369         try {
17370             final XmlSerializer serializer = new FastXmlSerializer();
17371             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17372             serializer.startDocument(null, true);
17373             serializer.startTag(null, TAG_PREFERRED_BACKUP);
17374
17375             synchronized (mPackages) {
17376                 mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17377             }
17378
17379             serializer.endTag(null, TAG_PREFERRED_BACKUP);
17380             serializer.endDocument();
17381             serializer.flush();
17382         } catch (Exception e) {
17383             if (DEBUG_BACKUP) {
17384                 Slog.e(TAG, "Unable to write preferred activities for backup", e);
17385             }
17386             return null;
17387         }
17388
17389         return dataStream.toByteArray();
17390     }
17391
17392     @Override
17393     public void restorePreferredActivities(byte[] backup, int userId) {
17394         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17395             throw new SecurityException("Only the system may call restorePreferredActivities()");
17396         }
17397
17398         try {
17399             final XmlPullParser parser = Xml.newPullParser();
17400             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17401             restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17402                     new BlobXmlRestorer() {
17403                         @Override
17404                         public void apply(XmlPullParser parser, int userId)
17405                                 throws XmlPullParserException, IOException {
17406                             synchronized (mPackages) {
17407                                 mSettings.readPreferredActivitiesLPw(parser, userId);
17408                             }
17409                         }
17410                     } );
17411         } catch (Exception e) {
17412             if (DEBUG_BACKUP) {
17413                 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17414             }
17415         }
17416     }
17417
17418     /**
17419      * Non-Binder method, support for the backup/restore mechanism: write the
17420      * default browser (etc) settings in its canonical XML format.  Returns the default
17421      * browser XML representation as a byte array, or null if there is none.
17422      */
17423     @Override
17424     public byte[] getDefaultAppsBackup(int userId) {
17425         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17426             throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17427         }
17428
17429         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17430         try {
17431             final XmlSerializer serializer = new FastXmlSerializer();
17432             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17433             serializer.startDocument(null, true);
17434             serializer.startTag(null, TAG_DEFAULT_APPS);
17435
17436             synchronized (mPackages) {
17437                 mSettings.writeDefaultAppsLPr(serializer, userId);
17438             }
17439
17440             serializer.endTag(null, TAG_DEFAULT_APPS);
17441             serializer.endDocument();
17442             serializer.flush();
17443         } catch (Exception e) {
17444             if (DEBUG_BACKUP) {
17445                 Slog.e(TAG, "Unable to write default apps for backup", e);
17446             }
17447             return null;
17448         }
17449
17450         return dataStream.toByteArray();
17451     }
17452
17453     @Override
17454     public void restoreDefaultApps(byte[] backup, int userId) {
17455         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17456             throw new SecurityException("Only the system may call restoreDefaultApps()");
17457         }
17458
17459         try {
17460             final XmlPullParser parser = Xml.newPullParser();
17461             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17462             restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17463                     new BlobXmlRestorer() {
17464                         @Override
17465                         public void apply(XmlPullParser parser, int userId)
17466                                 throws XmlPullParserException, IOException {
17467                             synchronized (mPackages) {
17468                                 mSettings.readDefaultAppsLPw(parser, userId);
17469                             }
17470                         }
17471                     } );
17472         } catch (Exception e) {
17473             if (DEBUG_BACKUP) {
17474                 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17475             }
17476         }
17477     }
17478
17479     @Override
17480     public byte[] getIntentFilterVerificationBackup(int userId) {
17481         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17482             throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17483         }
17484
17485         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17486         try {
17487             final XmlSerializer serializer = new FastXmlSerializer();
17488             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17489             serializer.startDocument(null, true);
17490             serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17491
17492             synchronized (mPackages) {
17493                 mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17494             }
17495
17496             serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17497             serializer.endDocument();
17498             serializer.flush();
17499         } catch (Exception e) {
17500             if (DEBUG_BACKUP) {
17501                 Slog.e(TAG, "Unable to write default apps for backup", e);
17502             }
17503             return null;
17504         }
17505
17506         return dataStream.toByteArray();
17507     }
17508
17509     @Override
17510     public void restoreIntentFilterVerification(byte[] backup, int userId) {
17511         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17512             throw new SecurityException("Only the system may call restorePreferredActivities()");
17513         }
17514
17515         try {
17516             final XmlPullParser parser = Xml.newPullParser();
17517             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17518             restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17519                     new BlobXmlRestorer() {
17520                         @Override
17521                         public void apply(XmlPullParser parser, int userId)
17522                                 throws XmlPullParserException, IOException {
17523                             synchronized (mPackages) {
17524                                 mSettings.readAllDomainVerificationsLPr(parser, userId);
17525                                 mSettings.writeLPr();
17526                             }
17527                         }
17528                     } );
17529         } catch (Exception e) {
17530             if (DEBUG_BACKUP) {
17531                 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17532             }
17533         }
17534     }
17535
17536     @Override
17537     public byte[] getPermissionGrantBackup(int userId) {
17538         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17539             throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17540         }
17541
17542         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17543         try {
17544             final XmlSerializer serializer = new FastXmlSerializer();
17545             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17546             serializer.startDocument(null, true);
17547             serializer.startTag(null, TAG_PERMISSION_BACKUP);
17548
17549             synchronized (mPackages) {
17550                 serializeRuntimePermissionGrantsLPr(serializer, userId);
17551             }
17552
17553             serializer.endTag(null, TAG_PERMISSION_BACKUP);
17554             serializer.endDocument();
17555             serializer.flush();
17556         } catch (Exception e) {
17557             if (DEBUG_BACKUP) {
17558                 Slog.e(TAG, "Unable to write default apps for backup", e);
17559             }
17560             return null;
17561         }
17562
17563         return dataStream.toByteArray();
17564     }
17565
17566     @Override
17567     public void restorePermissionGrants(byte[] backup, int userId) {
17568         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17569             throw new SecurityException("Only the system may call restorePermissionGrants()");
17570         }
17571
17572         try {
17573             final XmlPullParser parser = Xml.newPullParser();
17574             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17575             restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17576                     new BlobXmlRestorer() {
17577                         @Override
17578                         public void apply(XmlPullParser parser, int userId)
17579                                 throws XmlPullParserException, IOException {
17580                             synchronized (mPackages) {
17581                                 processRestoredPermissionGrantsLPr(parser, userId);
17582                             }
17583                         }
17584                     } );
17585         } catch (Exception e) {
17586             if (DEBUG_BACKUP) {
17587                 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17588             }
17589         }
17590     }
17591
17592     private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17593             throws IOException {
17594         serializer.startTag(null, TAG_ALL_GRANTS);
17595
17596         final int N = mSettings.mPackages.size();
17597         for (int i = 0; i < N; i++) {
17598             final PackageSetting ps = mSettings.mPackages.valueAt(i);
17599             boolean pkgGrantsKnown = false;
17600
17601             PermissionsState packagePerms = ps.getPermissionsState();
17602
17603             for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17604                 final int grantFlags = state.getFlags();
17605                 // only look at grants that are not system/policy fixed
17606                 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17607                     final boolean isGranted = state.isGranted();
17608                     // And only back up the user-twiddled state bits
17609                     if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17610                         final String packageName = mSettings.mPackages.keyAt(i);
17611                         if (!pkgGrantsKnown) {
17612                             serializer.startTag(null, TAG_GRANT);
17613                             serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17614                             pkgGrantsKnown = true;
17615                         }
17616
17617                         final boolean userSet =
17618                                 (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17619                         final boolean userFixed =
17620                                 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17621                         final boolean revoke =
17622                                 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17623
17624                         serializer.startTag(null, TAG_PERMISSION);
17625                         serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17626                         if (isGranted) {
17627                             serializer.attribute(null, ATTR_IS_GRANTED, "true");
17628                         }
17629                         if (userSet) {
17630                             serializer.attribute(null, ATTR_USER_SET, "true");
17631                         }
17632                         if (userFixed) {
17633                             serializer.attribute(null, ATTR_USER_FIXED, "true");
17634                         }
17635                         if (revoke) {
17636                             serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17637                         }
17638                         serializer.endTag(null, TAG_PERMISSION);
17639                     }
17640                 }
17641             }
17642
17643             if (pkgGrantsKnown) {
17644                 serializer.endTag(null, TAG_GRANT);
17645             }
17646         }
17647
17648         serializer.endTag(null, TAG_ALL_GRANTS);
17649     }
17650
17651     private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17652             throws XmlPullParserException, IOException {
17653         String pkgName = null;
17654         int outerDepth = parser.getDepth();
17655         int type;
17656         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17657                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17658             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17659                 continue;
17660             }
17661
17662             final String tagName = parser.getName();
17663             if (tagName.equals(TAG_GRANT)) {
17664                 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17665                 if (DEBUG_BACKUP) {
17666                     Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17667                 }
17668             } else if (tagName.equals(TAG_PERMISSION)) {
17669
17670                 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17671                 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17672
17673                 int newFlagSet = 0;
17674                 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17675                     newFlagSet |= FLAG_PERMISSION_USER_SET;
17676                 }
17677                 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17678                     newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17679                 }
17680                 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17681                     newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17682                 }
17683                 if (DEBUG_BACKUP) {
17684                     Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17685                             + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17686                 }
17687                 final PackageSetting ps = mSettings.mPackages.get(pkgName);
17688                 if (ps != null) {
17689                     // Already installed so we apply the grant immediately
17690                     if (DEBUG_BACKUP) {
17691                         Slog.v(TAG, "        + already installed; applying");
17692                     }
17693                     PermissionsState perms = ps.getPermissionsState();
17694                     BasePermission bp = mSettings.mPermissions.get(permName);
17695                     if (bp != null) {
17696                         if (isGranted) {
17697                             perms.grantRuntimePermission(bp, userId);
17698                         }
17699                         if (newFlagSet != 0) {
17700                             perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17701                         }
17702                     }
17703                 } else {
17704                     // Need to wait for post-restore install to apply the grant
17705                     if (DEBUG_BACKUP) {
17706                         Slog.v(TAG, "        - not yet installed; saving for later");
17707                     }
17708                     mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17709                             isGranted, newFlagSet, userId);
17710                 }
17711             } else {
17712                 PackageManagerService.reportSettingsProblem(Log.WARN,
17713                         "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17714                 XmlUtils.skipCurrentTag(parser);
17715             }
17716         }
17717
17718         scheduleWriteSettingsLocked();
17719         mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17720     }
17721
17722     @Override
17723     public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17724             int sourceUserId, int targetUserId, int flags) {
17725         mContext.enforceCallingOrSelfPermission(
17726                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17727         int callingUid = Binder.getCallingUid();
17728         enforceOwnerRights(ownerPackage, callingUid);
17729         enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17730         if (intentFilter.countActions() == 0) {
17731             Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17732             return;
17733         }
17734         synchronized (mPackages) {
17735             CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17736                     ownerPackage, targetUserId, flags);
17737             CrossProfileIntentResolver resolver =
17738                     mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17739             ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17740             // We have all those whose filter is equal. Now checking if the rest is equal as well.
17741             if (existing != null) {
17742                 int size = existing.size();
17743                 for (int i = 0; i < size; i++) {
17744                     if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17745                         return;
17746                     }
17747                 }
17748             }
17749             resolver.addFilter(newFilter);
17750             scheduleWritePackageRestrictionsLocked(sourceUserId);
17751         }
17752     }
17753
17754     @Override
17755     public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17756         mContext.enforceCallingOrSelfPermission(
17757                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17758         int callingUid = Binder.getCallingUid();
17759         enforceOwnerRights(ownerPackage, callingUid);
17760         enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17761         synchronized (mPackages) {
17762             CrossProfileIntentResolver resolver =
17763                     mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17764             ArraySet<CrossProfileIntentFilter> set =
17765                     new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17766             for (CrossProfileIntentFilter filter : set) {
17767                 if (filter.getOwnerPackage().equals(ownerPackage)) {
17768                     resolver.removeFilter(filter);
17769                 }
17770             }
17771             scheduleWritePackageRestrictionsLocked(sourceUserId);
17772         }
17773     }
17774
17775     // Enforcing that callingUid is owning pkg on userId
17776     private void enforceOwnerRights(String pkg, int callingUid) {
17777         // The system owns everything.
17778         if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17779             return;
17780         }
17781         int callingUserId = UserHandle.getUserId(callingUid);
17782         PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17783         if (pi == null) {
17784             throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17785                     + callingUserId);
17786         }
17787         if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17788             throw new SecurityException("Calling uid " + callingUid
17789                     + " does not own package " + pkg);
17790         }
17791     }
17792
17793     @Override
17794     public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17795         return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17796     }
17797
17798     private Intent getHomeIntent() {
17799         Intent intent = new Intent(Intent.ACTION_MAIN);
17800         intent.addCategory(Intent.CATEGORY_HOME);
17801         intent.addCategory(Intent.CATEGORY_DEFAULT);
17802         return intent;
17803     }
17804
17805     private IntentFilter getHomeFilter() {
17806         IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17807         filter.addCategory(Intent.CATEGORY_HOME);
17808         filter.addCategory(Intent.CATEGORY_DEFAULT);
17809         return filter;
17810     }
17811
17812     ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17813             int userId) {
17814         Intent intent  = getHomeIntent();
17815         List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17816                 PackageManager.GET_META_DATA, userId);
17817         ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17818                 true, false, false, userId);
17819
17820         allHomeCandidates.clear();
17821         if (list != null) {
17822             for (ResolveInfo ri : list) {
17823                 allHomeCandidates.add(ri);
17824             }
17825         }
17826         return (preferred == null || preferred.activityInfo == null)
17827                 ? null
17828                 : new ComponentName(preferred.activityInfo.packageName,
17829                         preferred.activityInfo.name);
17830     }
17831
17832     @Override
17833     public void setHomeActivity(ComponentName comp, int userId) {
17834         ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17835         getHomeActivitiesAsUser(homeActivities, userId);
17836
17837         boolean found = false;
17838
17839         final int size = homeActivities.size();
17840         final ComponentName[] set = new ComponentName[size];
17841         for (int i = 0; i < size; i++) {
17842             final ResolveInfo candidate = homeActivities.get(i);
17843             final ActivityInfo info = candidate.activityInfo;
17844             final ComponentName activityName = new ComponentName(info.packageName, info.name);
17845             set[i] = activityName;
17846             if (!found && activityName.equals(comp)) {
17847                 found = true;
17848             }
17849         }
17850         if (!found) {
17851             throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17852                     + userId);
17853         }
17854         replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17855                 set, comp, userId);
17856     }
17857
17858     private @Nullable String getSetupWizardPackageName() {
17859         final Intent intent = new Intent(Intent.ACTION_MAIN);
17860         intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17861
17862         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17863                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17864                         | MATCH_DISABLED_COMPONENTS,
17865                 UserHandle.myUserId());
17866         if (matches.size() == 1) {
17867             return matches.get(0).getComponentInfo().packageName;
17868         } else {
17869             Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17870                     + ": matches=" + matches);
17871             return null;
17872         }
17873     }
17874
17875     private @Nullable String getStorageManagerPackageName() {
17876         final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
17877
17878         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17879                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17880                         | MATCH_DISABLED_COMPONENTS,
17881                 UserHandle.myUserId());
17882         if (matches.size() == 1) {
17883             return matches.get(0).getComponentInfo().packageName;
17884         } else {
17885             Slog.e(TAG, "There should probably be exactly one storage manager; found "
17886                     + matches.size() + ": matches=" + matches);
17887             return null;
17888         }
17889     }
17890
17891     @Override
17892     public void setApplicationEnabledSetting(String appPackageName,
17893             int newState, int flags, int userId, String callingPackage) {
17894         if (!sUserManager.exists(userId)) return;
17895         if (callingPackage == null) {
17896             callingPackage = Integer.toString(Binder.getCallingUid());
17897         }
17898         setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17899     }
17900
17901     @Override
17902     public void setComponentEnabledSetting(ComponentName componentName,
17903             int newState, int flags, int userId) {
17904         if (!sUserManager.exists(userId)) return;
17905         setEnabledSetting(componentName.getPackageName(),
17906                 componentName.getClassName(), newState, flags, userId, null);
17907     }
17908
17909     private void setEnabledSetting(final String packageName, String className, int newState,
17910             final int flags, int userId, String callingPackage) {
17911         if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17912               || newState == COMPONENT_ENABLED_STATE_ENABLED
17913               || newState == COMPONENT_ENABLED_STATE_DISABLED
17914               || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17915               || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17916             throw new IllegalArgumentException("Invalid new component state: "
17917                     + newState);
17918         }
17919         PackageSetting pkgSetting;
17920         final int uid = Binder.getCallingUid();
17921         final int permission;
17922         if (uid == Process.SYSTEM_UID) {
17923             permission = PackageManager.PERMISSION_GRANTED;
17924         } else {
17925             permission = mContext.checkCallingOrSelfPermission(
17926                     android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17927         }
17928         enforceCrossUserPermission(uid, userId,
17929                 false /* requireFullPermission */, true /* checkShell */, "set enabled");
17930         final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17931         boolean sendNow = false;
17932         boolean isApp = (className == null);
17933         String componentName = isApp ? packageName : className;
17934         int packageUid = -1;
17935         ArrayList<String> components;
17936
17937         // writer
17938         synchronized (mPackages) {
17939             pkgSetting = mSettings.mPackages.get(packageName);
17940             if (pkgSetting == null) {
17941                 if (className == null) {
17942                     throw new IllegalArgumentException("Unknown package: " + packageName);
17943                 }
17944                 throw new IllegalArgumentException(
17945                         "Unknown component: " + packageName + "/" + className);
17946             }
17947         }
17948
17949         // Limit who can change which apps
17950         if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17951             // Don't allow apps that don't have permission to modify other apps
17952             if (!allowedByPermission) {
17953                 throw new SecurityException(
17954                         "Permission Denial: attempt to change component state from pid="
17955                         + Binder.getCallingPid()
17956                         + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17957             }
17958             // Don't allow changing protected packages.
17959             if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
17960                 throw new SecurityException("Cannot disable a protected package: " + packageName);
17961             }
17962         }
17963
17964         synchronized (mPackages) {
17965             if (uid == Process.SHELL_UID) {
17966                 // Shell can only change whole packages between ENABLED and DISABLED_USER states
17967                 int oldState = pkgSetting.getEnabled(userId);
17968                 if (className == null
17969                     &&
17970                     (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17971                      || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17972                      || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17973                     &&
17974                     (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17975                      || newState == COMPONENT_ENABLED_STATE_DEFAULT
17976                      || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17977                     // ok
17978                 } else {
17979                     throw new SecurityException(
17980                             "Shell cannot change component state for " + packageName + "/"
17981                             + className + " to " + newState);
17982                 }
17983             }
17984             if (className == null) {
17985                 // We're dealing with an application/package level state change
17986                 if (pkgSetting.getEnabled(userId) == newState) {
17987                     // Nothing to do
17988                     return;
17989                 }
17990                 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17991                     || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17992                     // Don't care about who enables an app.
17993                     callingPackage = null;
17994                 }
17995                 pkgSetting.setEnabled(newState, userId, callingPackage);
17996                 // pkgSetting.pkg.mSetEnabled = newState;
17997             } else {
17998                 // We're dealing with a component level state change
17999                 // First, verify that this is a valid class name.
18000                 PackageParser.Package pkg = pkgSetting.pkg;
18001                 if (pkg == null || !pkg.hasComponentClassName(className)) {
18002                     if (pkg != null &&
18003                             pkg.applicationInfo.targetSdkVersion >=
18004                                     Build.VERSION_CODES.JELLY_BEAN) {
18005                         throw new IllegalArgumentException("Component class " + className
18006                                 + " does not exist in " + packageName);
18007                     } else {
18008                         Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18009                                 + className + " does not exist in " + packageName);
18010                     }
18011                 }
18012                 switch (newState) {
18013                 case COMPONENT_ENABLED_STATE_ENABLED:
18014                     if (!pkgSetting.enableComponentLPw(className, userId)) {
18015                         return;
18016                     }
18017                     break;
18018                 case COMPONENT_ENABLED_STATE_DISABLED:
18019                     if (!pkgSetting.disableComponentLPw(className, userId)) {
18020                         return;
18021                     }
18022                     break;
18023                 case COMPONENT_ENABLED_STATE_DEFAULT:
18024                     if (!pkgSetting.restoreComponentLPw(className, userId)) {
18025                         return;
18026                     }
18027                     break;
18028                 default:
18029                     Slog.e(TAG, "Invalid new component state: " + newState);
18030                     return;
18031                 }
18032             }
18033             scheduleWritePackageRestrictionsLocked(userId);
18034             components = mPendingBroadcasts.get(userId, packageName);
18035             final boolean newPackage = components == null;
18036             if (newPackage) {
18037                 components = new ArrayList<String>();
18038             }
18039             if (!components.contains(componentName)) {
18040                 components.add(componentName);
18041             }
18042             if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18043                 sendNow = true;
18044                 // Purge entry from pending broadcast list if another one exists already
18045                 // since we are sending one right away.
18046                 mPendingBroadcasts.remove(userId, packageName);
18047             } else {
18048                 if (newPackage) {
18049                     mPendingBroadcasts.put(userId, packageName, components);
18050                 }
18051                 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18052                     // Schedule a message
18053                     mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18054                 }
18055             }
18056         }
18057
18058         long callingId = Binder.clearCallingIdentity();
18059         try {
18060             if (sendNow) {
18061                 packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18062                 sendPackageChangedBroadcast(packageName,
18063                         (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18064             }
18065         } finally {
18066             Binder.restoreCallingIdentity(callingId);
18067         }
18068     }
18069
18070     @Override
18071     public void flushPackageRestrictionsAsUser(int userId) {
18072         if (!sUserManager.exists(userId)) {
18073             return;
18074         }
18075         enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18076                 false /* checkShell */, "flushPackageRestrictions");
18077         synchronized (mPackages) {
18078             mSettings.writePackageRestrictionsLPr(userId);
18079             mDirtyUsers.remove(userId);
18080             if (mDirtyUsers.isEmpty()) {
18081                 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18082             }
18083         }
18084     }
18085
18086     private void sendPackageChangedBroadcast(String packageName,
18087             boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18088         if (DEBUG_INSTALL)
18089             Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18090                     + componentNames);
18091         Bundle extras = new Bundle(4);
18092         extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18093         String nameList[] = new String[componentNames.size()];
18094         componentNames.toArray(nameList);
18095         extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18096         extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18097         extras.putInt(Intent.EXTRA_UID, packageUid);
18098         // If this is not reporting a change of the overall package, then only send it
18099         // to registered receivers.  We don't want to launch a swath of apps for every
18100         // little component state change.
18101         final int flags = !componentNames.contains(packageName)
18102                 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18103         sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18104                 new int[] {UserHandle.getUserId(packageUid)});
18105     }
18106
18107     @Override
18108     public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18109         if (!sUserManager.exists(userId)) return;
18110         final int uid = Binder.getCallingUid();
18111         final int permission = mContext.checkCallingOrSelfPermission(
18112                 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18113         final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18114         enforceCrossUserPermission(uid, userId,
18115                 true /* requireFullPermission */, true /* checkShell */, "stop package");
18116         // writer
18117         synchronized (mPackages) {
18118             if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18119                     allowedByPermission, uid, userId)) {
18120                 scheduleWritePackageRestrictionsLocked(userId);
18121             }
18122         }
18123     }
18124
18125     @Override
18126     public String getInstallerPackageName(String packageName) {
18127         // reader
18128         synchronized (mPackages) {
18129             return mSettings.getInstallerPackageNameLPr(packageName);
18130         }
18131     }
18132
18133     public boolean isOrphaned(String packageName) {
18134         // reader
18135         synchronized (mPackages) {
18136             return mSettings.isOrphaned(packageName);
18137         }
18138     }
18139
18140     @Override
18141     public int getApplicationEnabledSetting(String packageName, int userId) {
18142         if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18143         int uid = Binder.getCallingUid();
18144         enforceCrossUserPermission(uid, userId,
18145                 false /* requireFullPermission */, false /* checkShell */, "get enabled");
18146         // reader
18147         synchronized (mPackages) {
18148             return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18149         }
18150     }
18151
18152     @Override
18153     public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18154         if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18155         int uid = Binder.getCallingUid();
18156         enforceCrossUserPermission(uid, userId,
18157                 false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18158         // reader
18159         synchronized (mPackages) {
18160             return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18161         }
18162     }
18163
18164     @Override
18165     public void enterSafeMode() {
18166         enforceSystemOrRoot("Only the system can request entering safe mode");
18167
18168         if (!mSystemReady) {
18169             mSafeMode = true;
18170         }
18171     }
18172
18173     @Override
18174     public void systemReady() {
18175         mSystemReady = true;
18176
18177         // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18178         // disabled after already being started.
18179         CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18180                 mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18181
18182         // Read the compatibilty setting when the system is ready.
18183         boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18184                 mContext.getContentResolver(),
18185                 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18186         PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18187         if (DEBUG_SETTINGS) {
18188             Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18189         }
18190
18191         int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18192
18193         synchronized (mPackages) {
18194             // Verify that all of the preferred activity components actually
18195             // exist.  It is possible for applications to be updated and at
18196             // that point remove a previously declared activity component that
18197             // had been set as a preferred activity.  We try to clean this up
18198             // the next time we encounter that preferred activity, but it is
18199             // possible for the user flow to never be able to return to that
18200             // situation so here we do a sanity check to make sure we haven't
18201             // left any junk around.
18202             ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18203             for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18204                 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18205                 removed.clear();
18206                 for (PreferredActivity pa : pir.filterSet()) {
18207                     if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18208                         removed.add(pa);
18209                     }
18210                 }
18211                 if (removed.size() > 0) {
18212                     for (int r=0; r<removed.size(); r++) {
18213                         PreferredActivity pa = removed.get(r);
18214                         Slog.w(TAG, "Removing dangling preferred activity: "
18215                                 + pa.mPref.mComponent);
18216                         pir.removeFilter(pa);
18217                     }
18218                     mSettings.writePackageRestrictionsLPr(
18219                             mSettings.mPreferredActivities.keyAt(i));
18220                 }
18221             }
18222
18223             for (int userId : UserManagerService.getInstance().getUserIds()) {
18224                 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18225                     grantPermissionsUserIds = ArrayUtils.appendInt(
18226                             grantPermissionsUserIds, userId);
18227                 }
18228             }
18229         }
18230         sUserManager.systemReady();
18231
18232         // If we upgraded grant all default permissions before kicking off.
18233         for (int userId : grantPermissionsUserIds) {
18234             mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18235         }
18236
18237         // If we did not grant default permissions, we preload from this the
18238         // default permission exceptions lazily to ensure we don't hit the
18239         // disk on a new user creation.
18240         if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18241             mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18242         }
18243
18244         // Kick off any messages waiting for system ready
18245         if (mPostSystemReadyMessages != null) {
18246             for (Message msg : mPostSystemReadyMessages) {
18247                 msg.sendToTarget();
18248             }
18249             mPostSystemReadyMessages = null;
18250         }
18251
18252         // Watch for external volumes that come and go over time
18253         final StorageManager storage = mContext.getSystemService(StorageManager.class);
18254         storage.registerListener(mStorageListener);
18255
18256         mInstallerService.systemReady();
18257         mPackageDexOptimizer.systemReady();
18258
18259         MountServiceInternal mountServiceInternal = LocalServices.getService(
18260                 MountServiceInternal.class);
18261         mountServiceInternal.addExternalStoragePolicy(
18262                 new MountServiceInternal.ExternalStorageMountPolicy() {
18263             @Override
18264             public int getMountMode(int uid, String packageName) {
18265                 if (Process.isIsolated(uid)) {
18266                     return Zygote.MOUNT_EXTERNAL_NONE;
18267                 }
18268                 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18269                     return Zygote.MOUNT_EXTERNAL_DEFAULT;
18270                 }
18271                 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18272                     return Zygote.MOUNT_EXTERNAL_DEFAULT;
18273                 }
18274                 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18275                     return Zygote.MOUNT_EXTERNAL_READ;
18276                 }
18277                 return Zygote.MOUNT_EXTERNAL_WRITE;
18278             }
18279
18280             @Override
18281             public boolean hasExternalStorage(int uid, String packageName) {
18282                 return true;
18283             }
18284         });
18285
18286         // Now that we're mostly running, clean up stale users and apps
18287         reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18288         reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18289     }
18290
18291     @Override
18292     public boolean isSafeMode() {
18293         return mSafeMode;
18294     }
18295
18296     @Override
18297     public boolean hasSystemUidErrors() {
18298         return mHasSystemUidErrors;
18299     }
18300
18301     static String arrayToString(int[] array) {
18302         StringBuffer buf = new StringBuffer(128);
18303         buf.append('[');
18304         if (array != null) {
18305             for (int i=0; i<array.length; i++) {
18306                 if (i > 0) buf.append(", ");
18307                 buf.append(array[i]);
18308             }
18309         }
18310         buf.append(']');
18311         return buf.toString();
18312     }
18313
18314     static class DumpState {
18315         public static final int DUMP_LIBS = 1 << 0;
18316         public static final int DUMP_FEATURES = 1 << 1;
18317         public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18318         public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18319         public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18320         public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18321         public static final int DUMP_PERMISSIONS = 1 << 6;
18322         public static final int DUMP_PACKAGES = 1 << 7;
18323         public static final int DUMP_SHARED_USERS = 1 << 8;
18324         public static final int DUMP_MESSAGES = 1 << 9;
18325         public static final int DUMP_PROVIDERS = 1 << 10;
18326         public static final int DUMP_VERIFIERS = 1 << 11;
18327         public static final int DUMP_PREFERRED = 1 << 12;
18328         public static final int DUMP_PREFERRED_XML = 1 << 13;
18329         public static final int DUMP_KEYSETS = 1 << 14;
18330         public static final int DUMP_VERSION = 1 << 15;
18331         public static final int DUMP_INSTALLS = 1 << 16;
18332         public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18333         public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18334         public static final int DUMP_FROZEN = 1 << 19;
18335         public static final int DUMP_DEXOPT = 1 << 20;
18336         public static final int DUMP_COMPILER_STATS = 1 << 21;
18337
18338         public static final int OPTION_SHOW_FILTERS = 1 << 0;
18339
18340         private int mTypes;
18341
18342         private int mOptions;
18343
18344         private boolean mTitlePrinted;
18345
18346         private SharedUserSetting mSharedUser;
18347
18348         public boolean isDumping(int type) {
18349             if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18350                 return true;
18351             }
18352
18353             return (mTypes & type) != 0;
18354         }
18355
18356         public void setDump(int type) {
18357             mTypes |= type;
18358         }
18359
18360         public boolean isOptionEnabled(int option) {
18361             return (mOptions & option) != 0;
18362         }
18363
18364         public void setOptionEnabled(int option) {
18365             mOptions |= option;
18366         }
18367
18368         public boolean onTitlePrinted() {
18369             final boolean printed = mTitlePrinted;
18370             mTitlePrinted = true;
18371             return printed;
18372         }
18373
18374         public boolean getTitlePrinted() {
18375             return mTitlePrinted;
18376         }
18377
18378         public void setTitlePrinted(boolean enabled) {
18379             mTitlePrinted = enabled;
18380         }
18381
18382         public SharedUserSetting getSharedUser() {
18383             return mSharedUser;
18384         }
18385
18386         public void setSharedUser(SharedUserSetting user) {
18387             mSharedUser = user;
18388         }
18389     }
18390
18391     @Override
18392     public void onShellCommand(FileDescriptor in, FileDescriptor out,
18393             FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18394         (new PackageManagerShellCommand(this)).exec(
18395                 this, in, out, err, args, resultReceiver);
18396     }
18397
18398     @Override
18399     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18400         if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18401                 != PackageManager.PERMISSION_GRANTED) {
18402             pw.println("Permission Denial: can't dump ActivityManager from from pid="
18403                     + Binder.getCallingPid()
18404                     + ", uid=" + Binder.getCallingUid()
18405                     + " without permission "
18406                     + android.Manifest.permission.DUMP);
18407             return;
18408         }
18409
18410         DumpState dumpState = new DumpState();
18411         boolean fullPreferred = false;
18412         boolean checkin = false;
18413
18414         String packageName = null;
18415         ArraySet<String> permissionNames = null;
18416
18417         int opti = 0;
18418         while (opti < args.length) {
18419             String opt = args[opti];
18420             if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18421                 break;
18422             }
18423             opti++;
18424
18425             if ("-a".equals(opt)) {
18426                 // Right now we only know how to print all.
18427             } else if ("-h".equals(opt)) {
18428                 pw.println("Package manager dump options:");
18429                 pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18430                 pw.println("    --checkin: dump for a checkin");
18431                 pw.println("    -f: print details of intent filters");
18432                 pw.println("    -h: print this help");
18433                 pw.println("  cmd may be one of:");
18434                 pw.println("    l[ibraries]: list known shared libraries");
18435                 pw.println("    f[eatures]: list device features");
18436                 pw.println("    k[eysets]: print known keysets");
18437                 pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18438                 pw.println("    perm[issions]: dump permissions");
18439                 pw.println("    permission [name ...]: dump declaration and use of given permission");
18440                 pw.println("    pref[erred]: print preferred package settings");
18441                 pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18442                 pw.println("    prov[iders]: dump content providers");
18443                 pw.println("    p[ackages]: dump installed packages");
18444                 pw.println("    s[hared-users]: dump shared user IDs");
18445                 pw.println("    m[essages]: print collected runtime messages");
18446                 pw.println("    v[erifiers]: print package verifier info");
18447                 pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18448                 pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18449                 pw.println("    version: print database version info");
18450                 pw.println("    write: write current settings now");
18451                 pw.println("    installs: details about install sessions");
18452                 pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18453                 pw.println("    dexopt: dump dexopt state");
18454                 pw.println("    compiler-stats: dump compiler statistics");
18455                 pw.println("    <package.name>: info about given package");
18456                 return;
18457             } else if ("--checkin".equals(opt)) {
18458                 checkin = true;
18459             } else if ("-f".equals(opt)) {
18460                 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18461             } else {
18462                 pw.println("Unknown argument: " + opt + "; use -h for help");
18463             }
18464         }
18465
18466         // Is the caller requesting to dump a particular piece of data?
18467         if (opti < args.length) {
18468             String cmd = args[opti];
18469             opti++;
18470             // Is this a package name?
18471             if ("android".equals(cmd) || cmd.contains(".")) {
18472                 packageName = cmd;
18473                 // When dumping a single package, we always dump all of its
18474                 // filter information since the amount of data will be reasonable.
18475                 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18476             } else if ("check-permission".equals(cmd)) {
18477                 if (opti >= args.length) {
18478                     pw.println("Error: check-permission missing permission argument");
18479                     return;
18480                 }
18481                 String perm = args[opti];
18482                 opti++;
18483                 if (opti >= args.length) {
18484                     pw.println("Error: check-permission missing package argument");
18485                     return;
18486                 }
18487                 String pkg = args[opti];
18488                 opti++;
18489                 int user = UserHandle.getUserId(Binder.getCallingUid());
18490                 if (opti < args.length) {
18491                     try {
18492                         user = Integer.parseInt(args[opti]);
18493                     } catch (NumberFormatException e) {
18494                         pw.println("Error: check-permission user argument is not a number: "
18495                                 + args[opti]);
18496                         return;
18497                     }
18498                 }
18499                 pw.println(checkPermission(perm, pkg, user));
18500                 return;
18501             } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18502                 dumpState.setDump(DumpState.DUMP_LIBS);
18503             } else if ("f".equals(cmd) || "features".equals(cmd)) {
18504                 dumpState.setDump(DumpState.DUMP_FEATURES);
18505             } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18506                 if (opti >= args.length) {
18507                     dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18508                             | DumpState.DUMP_SERVICE_RESOLVERS
18509                             | DumpState.DUMP_RECEIVER_RESOLVERS
18510                             | DumpState.DUMP_CONTENT_RESOLVERS);
18511                 } else {
18512                     while (opti < args.length) {
18513                         String name = args[opti];
18514                         if ("a".equals(name) || "activity".equals(name)) {
18515                             dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18516                         } else if ("s".equals(name) || "service".equals(name)) {
18517                             dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18518                         } else if ("r".equals(name) || "receiver".equals(name)) {
18519                             dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18520                         } else if ("c".equals(name) || "content".equals(name)) {
18521                             dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18522                         } else {
18523                             pw.println("Error: unknown resolver table type: " + name);
18524                             return;
18525                         }
18526                         opti++;
18527                     }
18528                 }
18529             } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18530                 dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18531             } else if ("permission".equals(cmd)) {
18532                 if (opti >= args.length) {
18533                     pw.println("Error: permission requires permission name");
18534                     return;
18535                 }
18536                 permissionNames = new ArraySet<>();
18537                 while (opti < args.length) {
18538                     permissionNames.add(args[opti]);
18539                     opti++;
18540                 }
18541                 dumpState.setDump(DumpState.DUMP_PERMISSIONS
18542                         | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18543             } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18544                 dumpState.setDump(DumpState.DUMP_PREFERRED);
18545             } else if ("preferred-xml".equals(cmd)) {
18546                 dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18547                 if (opti < args.length && "--full".equals(args[opti])) {
18548                     fullPreferred = true;
18549                     opti++;
18550                 }
18551             } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18552                 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18553             } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18554                 dumpState.setDump(DumpState.DUMP_PACKAGES);
18555             } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18556                 dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18557             } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18558                 dumpState.setDump(DumpState.DUMP_PROVIDERS);
18559             } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18560                 dumpState.setDump(DumpState.DUMP_MESSAGES);
18561             } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18562                 dumpState.setDump(DumpState.DUMP_VERIFIERS);
18563             } else if ("i".equals(cmd) || "ifv".equals(cmd)
18564                     || "intent-filter-verifiers".equals(cmd)) {
18565                 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18566             } else if ("version".equals(cmd)) {
18567                 dumpState.setDump(DumpState.DUMP_VERSION);
18568             } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18569                 dumpState.setDump(DumpState.DUMP_KEYSETS);
18570             } else if ("installs".equals(cmd)) {
18571                 dumpState.setDump(DumpState.DUMP_INSTALLS);
18572             } else if ("frozen".equals(cmd)) {
18573                 dumpState.setDump(DumpState.DUMP_FROZEN);
18574             } else if ("dexopt".equals(cmd)) {
18575                 dumpState.setDump(DumpState.DUMP_DEXOPT);
18576             } else if ("compiler-stats".equals(cmd)) {
18577                 dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18578             } else if ("write".equals(cmd)) {
18579                 synchronized (mPackages) {
18580                     mSettings.writeLPr();
18581                     pw.println("Settings written.");
18582                     return;
18583                 }
18584             }
18585         }
18586
18587         if (checkin) {
18588             pw.println("vers,1");
18589         }
18590
18591         // reader
18592         synchronized (mPackages) {
18593             if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18594                 if (!checkin) {
18595                     if (dumpState.onTitlePrinted())
18596                         pw.println();
18597                     pw.println("Database versions:");
18598                     mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18599                 }
18600             }
18601
18602             if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18603                 if (!checkin) {
18604                     if (dumpState.onTitlePrinted())
18605                         pw.println();
18606                     pw.println("Verifiers:");
18607                     pw.print("  Required: ");
18608                     pw.print(mRequiredVerifierPackage);
18609                     pw.print(" (uid=");
18610                     pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18611                             UserHandle.USER_SYSTEM));
18612                     pw.println(")");
18613                 } else if (mRequiredVerifierPackage != null) {
18614                     pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18615                     pw.print(",");
18616                     pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18617                             UserHandle.USER_SYSTEM));
18618                 }
18619             }
18620
18621             if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18622                     packageName == null) {
18623                 if (mIntentFilterVerifierComponent != null) {
18624                     String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18625                     if (!checkin) {
18626                         if (dumpState.onTitlePrinted())
18627                             pw.println();
18628                         pw.println("Intent Filter Verifier:");
18629                         pw.print("  Using: ");
18630                         pw.print(verifierPackageName);
18631                         pw.print(" (uid=");
18632                         pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18633                                 UserHandle.USER_SYSTEM));
18634                         pw.println(")");
18635                     } else if (verifierPackageName != null) {
18636                         pw.print("ifv,"); pw.print(verifierPackageName);
18637                         pw.print(",");
18638                         pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18639                                 UserHandle.USER_SYSTEM));
18640                     }
18641                 } else {
18642                     pw.println();
18643                     pw.println("No Intent Filter Verifier available!");
18644                 }
18645             }
18646
18647             if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18648                 boolean printedHeader = false;
18649                 final Iterator<String> it = mSharedLibraries.keySet().iterator();
18650                 while (it.hasNext()) {
18651                     String name = it.next();
18652                     SharedLibraryEntry ent = mSharedLibraries.get(name);
18653                     if (!checkin) {
18654                         if (!printedHeader) {
18655                             if (dumpState.onTitlePrinted())
18656                                 pw.println();
18657                             pw.println("Libraries:");
18658                             printedHeader = true;
18659                         }
18660                         pw.print("  ");
18661                     } else {
18662                         pw.print("lib,");
18663                     }
18664                     pw.print(name);
18665                     if (!checkin) {
18666                         pw.print(" -> ");
18667                     }
18668                     if (ent.path != null) {
18669                         if (!checkin) {
18670                             pw.print("(jar) ");
18671                             pw.print(ent.path);
18672                         } else {
18673                             pw.print(",jar,");
18674                             pw.print(ent.path);
18675                         }
18676                     } else {
18677                         if (!checkin) {
18678                             pw.print("(apk) ");
18679                             pw.print(ent.apk);
18680                         } else {
18681                             pw.print(",apk,");
18682                             pw.print(ent.apk);
18683                         }
18684                     }
18685                     pw.println();
18686                 }
18687             }
18688
18689             if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18690                 if (dumpState.onTitlePrinted())
18691                     pw.println();
18692                 if (!checkin) {
18693                     pw.println("Features:");
18694                 }
18695
18696                 for (FeatureInfo feat : mAvailableFeatures.values()) {
18697                     if (checkin) {
18698                         pw.print("feat,");
18699                         pw.print(feat.name);
18700                         pw.print(",");
18701                         pw.println(feat.version);
18702                     } else {
18703                         pw.print("  ");
18704                         pw.print(feat.name);
18705                         if (feat.version > 0) {
18706                             pw.print(" version=");
18707                             pw.print(feat.version);
18708                         }
18709                         pw.println();
18710                     }
18711                 }
18712             }
18713
18714             if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18715                 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18716                         : "Activity Resolver Table:", "  ", packageName,
18717                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18718                     dumpState.setTitlePrinted(true);
18719                 }
18720             }
18721             if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18722                 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18723                         : "Receiver Resolver Table:", "  ", packageName,
18724                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18725                     dumpState.setTitlePrinted(true);
18726                 }
18727             }
18728             if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18729                 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18730                         : "Service Resolver Table:", "  ", packageName,
18731                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18732                     dumpState.setTitlePrinted(true);
18733                 }
18734             }
18735             if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18736                 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18737                         : "Provider Resolver Table:", "  ", packageName,
18738                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18739                     dumpState.setTitlePrinted(true);
18740                 }
18741             }
18742
18743             if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18744                 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18745                     PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18746                     int user = mSettings.mPreferredActivities.keyAt(i);
18747                     if (pir.dump(pw,
18748                             dumpState.getTitlePrinted()
18749                                 ? "\nPreferred Activities User " + user + ":"
18750                                 : "Preferred Activities User " + user + ":", "  ",
18751                             packageName, true, false)) {
18752                         dumpState.setTitlePrinted(true);
18753                     }
18754                 }
18755             }
18756
18757             if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18758                 pw.flush();
18759                 FileOutputStream fout = new FileOutputStream(fd);
18760                 BufferedOutputStream str = new BufferedOutputStream(fout);
18761                 XmlSerializer serializer = new FastXmlSerializer();
18762                 try {
18763                     serializer.setOutput(str, StandardCharsets.UTF_8.name());
18764                     serializer.startDocument(null, true);
18765                     serializer.setFeature(
18766                             "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18767                     mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18768                     serializer.endDocument();
18769                     serializer.flush();
18770                 } catch (IllegalArgumentException e) {
18771                     pw.println("Failed writing: " + e);
18772                 } catch (IllegalStateException e) {
18773                     pw.println("Failed writing: " + e);
18774                 } catch (IOException e) {
18775                     pw.println("Failed writing: " + e);
18776                 }
18777             }
18778
18779             if (!checkin
18780                     && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18781                     && packageName == null) {
18782                 pw.println();
18783                 int count = mSettings.mPackages.size();
18784                 if (count == 0) {
18785                     pw.println("No applications!");
18786                     pw.println();
18787                 } else {
18788                     final String prefix = "  ";
18789                     Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18790                     if (allPackageSettings.size() == 0) {
18791                         pw.println("No domain preferred apps!");
18792                         pw.println();
18793                     } else {
18794                         pw.println("App verification status:");
18795                         pw.println();
18796                         count = 0;
18797                         for (PackageSetting ps : allPackageSettings) {
18798                             IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18799                             if (ivi == null || ivi.getPackageName() == null) continue;
18800                             pw.println(prefix + "Package: " + ivi.getPackageName());
18801                             pw.println(prefix + "Domains: " + ivi.getDomainsString());
18802                             pw.println(prefix + "Status:  " + ivi.getStatusString());
18803                             pw.println();
18804                             count++;
18805                         }
18806                         if (count == 0) {
18807                             pw.println(prefix + "No app verification established.");
18808                             pw.println();
18809                         }
18810                         for (int userId : sUserManager.getUserIds()) {
18811                             pw.println("App linkages for user " + userId + ":");
18812                             pw.println();
18813                             count = 0;
18814                             for (PackageSetting ps : allPackageSettings) {
18815                                 final long status = ps.getDomainVerificationStatusForUser(userId);
18816                                 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18817                                     continue;
18818                                 }
18819                                 pw.println(prefix + "Package: " + ps.name);
18820                                 pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18821                                 String statusStr = IntentFilterVerificationInfo.
18822                                         getStatusStringFromValue(status);
18823                                 pw.println(prefix + "Status:  " + statusStr);
18824                                 pw.println();
18825                                 count++;
18826                             }
18827                             if (count == 0) {
18828                                 pw.println(prefix + "No configured app linkages.");
18829                                 pw.println();
18830                             }
18831                         }
18832                     }
18833                 }
18834             }
18835
18836             if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18837                 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18838                 if (packageName == null && permissionNames == null) {
18839                     for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18840                         if (iperm == 0) {
18841                             if (dumpState.onTitlePrinted())
18842                                 pw.println();
18843                             pw.println("AppOp Permissions:");
18844                         }
18845                         pw.print("  AppOp Permission ");
18846                         pw.print(mAppOpPermissionPackages.keyAt(iperm));
18847                         pw.println(":");
18848                         ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18849                         for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18850                             pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18851                         }
18852                     }
18853                 }
18854             }
18855
18856             if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18857                 boolean printedSomething = false;
18858                 for (PackageParser.Provider p : mProviders.mProviders.values()) {
18859                     if (packageName != null && !packageName.equals(p.info.packageName)) {
18860                         continue;
18861                     }
18862                     if (!printedSomething) {
18863                         if (dumpState.onTitlePrinted())
18864                             pw.println();
18865                         pw.println("Registered ContentProviders:");
18866                         printedSomething = true;
18867                     }
18868                     pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18869                     pw.print("    "); pw.println(p.toString());
18870                 }
18871                 printedSomething = false;
18872                 for (Map.Entry<String, PackageParser.Provider> entry :
18873                         mProvidersByAuthority.entrySet()) {
18874                     PackageParser.Provider p = entry.getValue();
18875                     if (packageName != null && !packageName.equals(p.info.packageName)) {
18876                         continue;
18877                     }
18878                     if (!printedSomething) {
18879                         if (dumpState.onTitlePrinted())
18880                             pw.println();
18881                         pw.println("ContentProvider Authorities:");
18882                         printedSomething = true;
18883                     }
18884                     pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18885                     pw.print("    "); pw.println(p.toString());
18886                     if (p.info != null && p.info.applicationInfo != null) {
18887                         final String appInfo = p.info.applicationInfo.toString();
18888                         pw.print("      applicationInfo="); pw.println(appInfo);
18889                     }
18890                 }
18891             }
18892
18893             if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18894                 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18895             }
18896
18897             if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18898                 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18899             }
18900
18901             if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18902                 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18903             }
18904
18905             if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18906                 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18907             }
18908
18909             if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18910                 // XXX should handle packageName != null by dumping only install data that
18911                 // the given package is involved with.
18912                 if (dumpState.onTitlePrinted()) pw.println();
18913                 mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18914             }
18915
18916             if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18917                 // XXX should handle packageName != null by dumping only install data that
18918                 // the given package is involved with.
18919                 if (dumpState.onTitlePrinted()) pw.println();
18920
18921                 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18922                 ipw.println();
18923                 ipw.println("Frozen packages:");
18924                 ipw.increaseIndent();
18925                 if (mFrozenPackages.size() == 0) {
18926                     ipw.println("(none)");
18927                 } else {
18928                     for (int i = 0; i < mFrozenPackages.size(); i++) {
18929                         ipw.println(mFrozenPackages.valueAt(i));
18930                     }
18931                 }
18932                 ipw.decreaseIndent();
18933             }
18934
18935             if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18936                 if (dumpState.onTitlePrinted()) pw.println();
18937                 dumpDexoptStateLPr(pw, packageName);
18938             }
18939
18940             if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
18941                 if (dumpState.onTitlePrinted()) pw.println();
18942                 dumpCompilerStatsLPr(pw, packageName);
18943             }
18944
18945             if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18946                 if (dumpState.onTitlePrinted()) pw.println();
18947                 mSettings.dumpReadMessagesLPr(pw, dumpState);
18948
18949                 pw.println();
18950                 pw.println("Package warning messages:");
18951                 BufferedReader in = null;
18952                 String line = null;
18953                 try {
18954                     in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18955                     while ((line = in.readLine()) != null) {
18956                         if (line.contains("ignored: updated version")) continue;
18957                         pw.println(line);
18958                     }
18959                 } catch (IOException ignored) {
18960                 } finally {
18961                     IoUtils.closeQuietly(in);
18962                 }
18963             }
18964
18965             if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18966                 BufferedReader in = null;
18967                 String line = null;
18968                 try {
18969                     in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18970                     while ((line = in.readLine()) != null) {
18971                         if (line.contains("ignored: updated version")) continue;
18972                         pw.print("msg,");
18973                         pw.println(line);
18974                     }
18975                 } catch (IOException ignored) {
18976                 } finally {
18977                     IoUtils.closeQuietly(in);
18978                 }
18979             }
18980         }
18981     }
18982
18983     private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18984         final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18985         ipw.println();
18986         ipw.println("Dexopt state:");
18987         ipw.increaseIndent();
18988         Collection<PackageParser.Package> packages = null;
18989         if (packageName != null) {
18990             PackageParser.Package targetPackage = mPackages.get(packageName);
18991             if (targetPackage != null) {
18992                 packages = Collections.singletonList(targetPackage);
18993             } else {
18994                 ipw.println("Unable to find package: " + packageName);
18995                 return;
18996             }
18997         } else {
18998             packages = mPackages.values();
18999         }
19000
19001         for (PackageParser.Package pkg : packages) {
19002             ipw.println("[" + pkg.packageName + "]");
19003             ipw.increaseIndent();
19004             mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19005             ipw.decreaseIndent();
19006         }
19007     }
19008
19009     private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19010         final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19011         ipw.println();
19012         ipw.println("Compiler stats:");
19013         ipw.increaseIndent();
19014         Collection<PackageParser.Package> packages = null;
19015         if (packageName != null) {
19016             PackageParser.Package targetPackage = mPackages.get(packageName);
19017             if (targetPackage != null) {
19018                 packages = Collections.singletonList(targetPackage);
19019             } else {
19020                 ipw.println("Unable to find package: " + packageName);
19021                 return;
19022             }
19023         } else {
19024             packages = mPackages.values();
19025         }
19026
19027         for (PackageParser.Package pkg : packages) {
19028             ipw.println("[" + pkg.packageName + "]");
19029             ipw.increaseIndent();
19030
19031             CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19032             if (stats == null) {
19033                 ipw.println("(No recorded stats)");
19034             } else {
19035                 stats.dump(ipw);
19036             }
19037             ipw.decreaseIndent();
19038         }
19039     }
19040
19041     private String dumpDomainString(String packageName) {
19042         List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19043                 .getList();
19044         List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19045
19046         ArraySet<String> result = new ArraySet<>();
19047         if (iviList.size() > 0) {
19048             for (IntentFilterVerificationInfo ivi : iviList) {
19049                 for (String host : ivi.getDomains()) {
19050                     result.add(host);
19051                 }
19052             }
19053         }
19054         if (filters != null && filters.size() > 0) {
19055             for (IntentFilter filter : filters) {
19056                 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19057                         && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19058                                 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19059                     result.addAll(filter.getHostsList());
19060                 }
19061             }
19062         }
19063
19064         StringBuilder sb = new StringBuilder(result.size() * 16);
19065         for (String domain : result) {
19066             if (sb.length() > 0) sb.append(" ");
19067             sb.append(domain);
19068         }
19069         return sb.toString();
19070     }
19071
19072     // ------- apps on sdcard specific code -------
19073     static final boolean DEBUG_SD_INSTALL = false;
19074
19075     private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19076
19077     private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19078
19079     private boolean mMediaMounted = false;
19080
19081     static String getEncryptKey() {
19082         try {
19083             String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19084                     SD_ENCRYPTION_KEYSTORE_NAME);
19085             if (sdEncKey == null) {
19086                 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19087                         SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19088                 if (sdEncKey == null) {
19089                     Slog.e(TAG, "Failed to create encryption keys");
19090                     return null;
19091                 }
19092             }
19093             return sdEncKey;
19094         } catch (NoSuchAlgorithmException nsae) {
19095             Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19096             return null;
19097         } catch (IOException ioe) {
19098             Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19099             return null;
19100         }
19101     }
19102
19103     /*
19104      * Update media status on PackageManager.
19105      */
19106     @Override
19107     public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19108         int callingUid = Binder.getCallingUid();
19109         if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19110             throw new SecurityException("Media status can only be updated by the system");
19111         }
19112         // reader; this apparently protects mMediaMounted, but should probably
19113         // be a different lock in that case.
19114         synchronized (mPackages) {
19115             Log.i(TAG, "Updating external media status from "
19116                     + (mMediaMounted ? "mounted" : "unmounted") + " to "
19117                     + (mediaStatus ? "mounted" : "unmounted"));
19118             if (DEBUG_SD_INSTALL)
19119                 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19120                         + ", mMediaMounted=" + mMediaMounted);
19121             if (mediaStatus == mMediaMounted) {
19122                 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19123                         : 0, -1);
19124                 mHandler.sendMessage(msg);
19125                 return;
19126             }
19127             mMediaMounted = mediaStatus;
19128         }
19129         // Queue up an async operation since the package installation may take a
19130         // little while.
19131         mHandler.post(new Runnable() {
19132             public void run() {
19133                 updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19134             }
19135         });
19136     }
19137
19138     /**
19139      * Called by MountService when the initial ASECs to scan are available.
19140      * Should block until all the ASEC containers are finished being scanned.
19141      */
19142     public void scanAvailableAsecs() {
19143         updateExternalMediaStatusInner(true, false, false);
19144     }
19145
19146     /*
19147      * Collect information of applications on external media, map them against
19148      * existing containers and update information based on current mount status.
19149      * Please note that we always have to report status if reportStatus has been
19150      * set to true especially when unloading packages.
19151      */
19152     private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19153             boolean externalStorage) {
19154         ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19155         int[] uidArr = EmptyArray.INT;
19156
19157         final String[] list = PackageHelper.getSecureContainerList();
19158         if (ArrayUtils.isEmpty(list)) {
19159             Log.i(TAG, "No secure containers found");
19160         } else {
19161             // Process list of secure containers and categorize them
19162             // as active or stale based on their package internal state.
19163
19164             // reader
19165             synchronized (mPackages) {
19166                 for (String cid : list) {
19167                     // Leave stages untouched for now; installer service owns them
19168                     if (PackageInstallerService.isStageName(cid)) continue;
19169
19170                     if (DEBUG_SD_INSTALL)
19171                         Log.i(TAG, "Processing container " + cid);
19172                     String pkgName = getAsecPackageName(cid);
19173                     if (pkgName == null) {
19174                         Slog.i(TAG, "Found stale container " + cid + " with no package name");
19175                         continue;
19176                     }
19177                     if (DEBUG_SD_INSTALL)
19178                         Log.i(TAG, "Looking for pkg : " + pkgName);
19179
19180                     final PackageSetting ps = mSettings.mPackages.get(pkgName);
19181                     if (ps == null) {
19182                         Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19183                         continue;
19184                     }
19185
19186                     /*
19187                      * Skip packages that are not external if we're unmounting
19188                      * external storage.
19189                      */
19190                     if (externalStorage && !isMounted && !isExternal(ps)) {
19191                         continue;
19192                     }
19193
19194                     final AsecInstallArgs args = new AsecInstallArgs(cid,
19195                             getAppDexInstructionSets(ps), ps.isForwardLocked());
19196                     // The package status is changed only if the code path
19197                     // matches between settings and the container id.
19198                     if (ps.codePathString != null
19199                             && ps.codePathString.startsWith(args.getCodePath())) {
19200                         if (DEBUG_SD_INSTALL) {
19201                             Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19202                                     + " at code path: " + ps.codePathString);
19203                         }
19204
19205                         // We do have a valid package installed on sdcard
19206                         processCids.put(args, ps.codePathString);
19207                         final int uid = ps.appId;
19208                         if (uid != -1) {
19209                             uidArr = ArrayUtils.appendInt(uidArr, uid);
19210                         }
19211                     } else {
19212                         Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19213                                 + ps.codePathString);
19214                     }
19215                 }
19216             }
19217
19218             Arrays.sort(uidArr);
19219         }
19220
19221         // Process packages with valid entries.
19222         if (isMounted) {
19223             if (DEBUG_SD_INSTALL)
19224                 Log.i(TAG, "Loading packages");
19225             loadMediaPackages(processCids, uidArr, externalStorage);
19226             startCleaningPackages();
19227             mInstallerService.onSecureContainersAvailable();
19228         } else {
19229             if (DEBUG_SD_INSTALL)
19230                 Log.i(TAG, "Unloading packages");
19231             unloadMediaPackages(processCids, uidArr, reportStatus);
19232         }
19233     }
19234
19235     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19236             ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19237         final int size = infos.size();
19238         final String[] packageNames = new String[size];
19239         final int[] packageUids = new int[size];
19240         for (int i = 0; i < size; i++) {
19241             final ApplicationInfo info = infos.get(i);
19242             packageNames[i] = info.packageName;
19243             packageUids[i] = info.uid;
19244         }
19245         sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19246                 finishedReceiver);
19247     }
19248
19249     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19250             ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19251         sendResourcesChangedBroadcast(mediaStatus, replacing,
19252                 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19253     }
19254
19255     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19256             String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19257         int size = pkgList.length;
19258         if (size > 0) {
19259             // Send broadcasts here
19260             Bundle extras = new Bundle();
19261             extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19262             if (uidArr != null) {
19263                 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19264             }
19265             if (replacing) {
19266                 extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19267             }
19268             String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19269                     : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19270             sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19271         }
19272     }
19273
19274    /*
19275      * Look at potentially valid container ids from processCids If package
19276      * information doesn't match the one on record or package scanning fails,
19277      * the cid is added to list of removeCids. We currently don't delete stale
19278      * containers.
19279      */
19280     private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19281             boolean externalStorage) {
19282         ArrayList<String> pkgList = new ArrayList<String>();
19283         Set<AsecInstallArgs> keys = processCids.keySet();
19284
19285         for (AsecInstallArgs args : keys) {
19286             String codePath = processCids.get(args);
19287             if (DEBUG_SD_INSTALL)
19288                 Log.i(TAG, "Loading container : " + args.cid);
19289             int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19290             try {
19291                 // Make sure there are no container errors first.
19292                 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19293                     Slog.e(TAG, "Failed to mount cid : " + args.cid
19294                             + " when installing from sdcard");
19295                     continue;
19296                 }
19297                 // Check code path here.
19298                 if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19299                     Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19300                             + " does not match one in settings " + codePath);
19301                     continue;
19302                 }
19303                 // Parse package
19304                 int parseFlags = mDefParseFlags;
19305                 if (args.isExternalAsec()) {
19306                     parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19307                 }
19308                 if (args.isFwdLocked()) {
19309                     parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19310                 }
19311
19312                 synchronized (mInstallLock) {
19313                     PackageParser.Package pkg = null;
19314                     try {
19315                         // Sadly we don't know the package name yet to freeze it
19316                         pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19317                                 SCAN_IGNORE_FROZEN, 0, null);
19318                     } catch (PackageManagerException e) {
19319                         Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19320                     }
19321                     // Scan the package
19322                     if (pkg != null) {
19323                         /*
19324                          * TODO why is the lock being held? doPostInstall is
19325                          * called in other places without the lock. This needs
19326                          * to be straightened out.
19327                          */
19328                         // writer
19329                         synchronized (mPackages) {
19330                             retCode = PackageManager.INSTALL_SUCCEEDED;
19331                             pkgList.add(pkg.packageName);
19332                             // Post process args
19333                             args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19334                                     pkg.applicationInfo.uid);
19335                         }
19336                     } else {
19337                         Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19338                     }
19339                 }
19340
19341             } finally {
19342                 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19343                     Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19344                 }
19345             }
19346         }
19347         // writer
19348         synchronized (mPackages) {
19349             // If the platform SDK has changed since the last time we booted,
19350             // we need to re-grant app permission to catch any new ones that
19351             // appear. This is really a hack, and means that apps can in some
19352             // cases get permissions that the user didn't initially explicitly
19353             // allow... it would be nice to have some better way to handle
19354             // this situation.
19355             final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19356                     : mSettings.getInternalVersion();
19357             final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19358                     : StorageManager.UUID_PRIVATE_INTERNAL;
19359
19360             int updateFlags = UPDATE_PERMISSIONS_ALL;
19361             if (ver.sdkVersion != mSdkVersion) {
19362                 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19363                         + mSdkVersion + "; regranting permissions for external");
19364                 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19365             }
19366             updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19367
19368             // Yay, everything is now upgraded
19369             ver.forceCurrent();
19370
19371             // can downgrade to reader
19372             // Persist settings
19373             mSettings.writeLPr();
19374         }
19375         // Send a broadcast to let everyone know we are done processing
19376         if (pkgList.size() > 0) {
19377             sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19378         }
19379     }
19380
19381    /*
19382      * Utility method to unload a list of specified containers
19383      */
19384     private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19385         // Just unmount all valid containers.
19386         for (AsecInstallArgs arg : cidArgs) {
19387             synchronized (mInstallLock) {
19388                 arg.doPostDeleteLI(false);
19389            }
19390        }
19391    }
19392
19393     /*
19394      * Unload packages mounted on external media. This involves deleting package
19395      * data from internal structures, sending broadcasts about disabled packages,
19396      * gc'ing to free up references, unmounting all secure containers
19397      * corresponding to packages on external media, and posting a
19398      * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19399      * that we always have to post this message if status has been requested no
19400      * matter what.
19401      */
19402     private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19403             final boolean reportStatus) {
19404         if (DEBUG_SD_INSTALL)
19405             Log.i(TAG, "unloading media packages");
19406         ArrayList<String> pkgList = new ArrayList<String>();
19407         ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19408         final Set<AsecInstallArgs> keys = processCids.keySet();
19409         for (AsecInstallArgs args : keys) {
19410             String pkgName = args.getPackageName();
19411             if (DEBUG_SD_INSTALL)
19412                 Log.i(TAG, "Trying to unload pkg : " + pkgName);
19413             // Delete package internally
19414             PackageRemovedInfo outInfo = new PackageRemovedInfo();
19415             synchronized (mInstallLock) {
19416                 final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19417                 final boolean res;
19418                 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19419                         "unloadMediaPackages")) {
19420                     res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19421                             null);
19422                 }
19423                 if (res) {
19424                     pkgList.add(pkgName);
19425                 } else {
19426                     Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19427                     failedList.add(args);
19428                 }
19429             }
19430         }
19431
19432         // reader
19433         synchronized (mPackages) {
19434             // We didn't update the settings after removing each package;
19435             // write them now for all packages.
19436             mSettings.writeLPr();
19437         }
19438
19439         // We have to absolutely send UPDATED_MEDIA_STATUS only
19440         // after confirming that all the receivers processed the ordered
19441         // broadcast when packages get disabled, force a gc to clean things up.
19442         // and unload all the containers.
19443         if (pkgList.size() > 0) {
19444             sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19445                     new IIntentReceiver.Stub() {
19446                 public void performReceive(Intent intent, int resultCode, String data,
19447                         Bundle extras, boolean ordered, boolean sticky,
19448                         int sendingUser) throws RemoteException {
19449                     Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19450                             reportStatus ? 1 : 0, 1, keys);
19451                     mHandler.sendMessage(msg);
19452                 }
19453             });
19454         } else {
19455             Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19456                     keys);
19457             mHandler.sendMessage(msg);
19458         }
19459     }
19460
19461     private void loadPrivatePackages(final VolumeInfo vol) {
19462         mHandler.post(new Runnable() {
19463             @Override
19464             public void run() {
19465                 loadPrivatePackagesInner(vol);
19466             }
19467         });
19468     }
19469
19470     private void loadPrivatePackagesInner(VolumeInfo vol) {
19471         final String volumeUuid = vol.fsUuid;
19472         if (TextUtils.isEmpty(volumeUuid)) {
19473             Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19474             return;
19475         }
19476
19477         final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19478         final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19479         final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19480
19481         final VersionInfo ver;
19482         final List<PackageSetting> packages;
19483         synchronized (mPackages) {
19484             ver = mSettings.findOrCreateVersion(volumeUuid);
19485             packages = mSettings.getVolumePackagesLPr(volumeUuid);
19486         }
19487
19488         for (PackageSetting ps : packages) {
19489             freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19490             synchronized (mInstallLock) {
19491                 final PackageParser.Package pkg;
19492                 try {
19493                     pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19494                     loaded.add(pkg.applicationInfo);
19495
19496                 } catch (PackageManagerException e) {
19497                     Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19498                 }
19499
19500                 if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19501                     clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19502                             StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19503                                     | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19504                 }
19505             }
19506         }
19507
19508         // Reconcile app data for all started/unlocked users
19509         final StorageManager sm = mContext.getSystemService(StorageManager.class);
19510         final UserManager um = mContext.getSystemService(UserManager.class);
19511         UserManagerInternal umInternal = getUserManagerInternal();
19512         for (UserInfo user : um.getUsers()) {
19513             final int flags;
19514             if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19515                 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19516             } else if (umInternal.isUserRunning(user.id)) {
19517                 flags = StorageManager.FLAG_STORAGE_DE;
19518             } else {
19519                 continue;
19520             }
19521
19522             try {
19523                 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19524                 synchronized (mInstallLock) {
19525                     reconcileAppsDataLI(volumeUuid, user.id, flags);
19526                 }
19527             } catch (IllegalStateException e) {
19528                 // Device was probably ejected, and we'll process that event momentarily
19529                 Slog.w(TAG, "Failed to prepare storage: " + e);
19530             }
19531         }
19532
19533         synchronized (mPackages) {
19534             int updateFlags = UPDATE_PERMISSIONS_ALL;
19535             if (ver.sdkVersion != mSdkVersion) {
19536                 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19537                         + mSdkVersion + "; regranting permissions for " + volumeUuid);
19538                 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19539             }
19540             updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19541
19542             // Yay, everything is now upgraded
19543             ver.forceCurrent();
19544
19545             mSettings.writeLPr();
19546         }
19547
19548         for (PackageFreezer freezer : freezers) {
19549             freezer.close();
19550         }
19551
19552         if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19553         sendResourcesChangedBroadcast(true, false, loaded, null);
19554     }
19555
19556     private void unloadPrivatePackages(final VolumeInfo vol) {
19557         mHandler.post(new Runnable() {
19558             @Override
19559             public void run() {
19560                 unloadPrivatePackagesInner(vol);
19561             }
19562         });
19563     }
19564
19565     private void unloadPrivatePackagesInner(VolumeInfo vol) {
19566         final String volumeUuid = vol.fsUuid;
19567         if (TextUtils.isEmpty(volumeUuid)) {
19568             Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19569             return;
19570         }
19571
19572         final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19573         synchronized (mInstallLock) {
19574         synchronized (mPackages) {
19575             final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19576             for (PackageSetting ps : packages) {
19577                 if (ps.pkg == null) continue;
19578
19579                 final ApplicationInfo info = ps.pkg.applicationInfo;
19580                 final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19581                 final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19582
19583                 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19584                         "unloadPrivatePackagesInner")) {
19585                     if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19586                             false, null)) {
19587                         unloaded.add(info);
19588                     } else {
19589                         Slog.w(TAG, "Failed to unload " + ps.codePath);
19590                     }
19591                 }
19592
19593                 // Try very hard to release any references to this package
19594                 // so we don't risk the system server being killed due to
19595                 // open FDs
19596                 AttributeCache.instance().removePackage(ps.name);
19597             }
19598
19599             mSettings.writeLPr();
19600         }
19601         }
19602
19603         if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19604         sendResourcesChangedBroadcast(false, false, unloaded, null);
19605
19606         // Try very hard to release any references to this path so we don't risk
19607         // the system server being killed due to open FDs
19608         ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19609
19610         for (int i = 0; i < 3; i++) {
19611             System.gc();
19612             System.runFinalization();
19613         }
19614     }
19615
19616     /**
19617      * Prepare storage areas for given user on all mounted devices.
19618      */
19619     void prepareUserData(int userId, int userSerial, int flags) {
19620         synchronized (mInstallLock) {
19621             final StorageManager storage = mContext.getSystemService(StorageManager.class);
19622             for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19623                 final String volumeUuid = vol.getFsUuid();
19624                 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19625             }
19626         }
19627     }
19628
19629     private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19630             boolean allowRecover) {
19631         // Prepare storage and verify that serial numbers are consistent; if
19632         // there's a mismatch we need to destroy to avoid leaking data
19633         final StorageManager storage = mContext.getSystemService(StorageManager.class);
19634         try {
19635             storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19636
19637             if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19638                 UserManagerService.enforceSerialNumber(
19639                         Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19640                 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19641                     UserManagerService.enforceSerialNumber(
19642                             Environment.getDataSystemDeDirectory(userId), userSerial);
19643                 }
19644             }
19645             if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19646                 UserManagerService.enforceSerialNumber(
19647                         Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19648                 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19649                     UserManagerService.enforceSerialNumber(
19650                             Environment.getDataSystemCeDirectory(userId), userSerial);
19651                 }
19652             }
19653
19654             synchronized (mInstallLock) {
19655                 mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19656             }
19657         } catch (Exception e) {
19658             logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19659                     + " because we failed to prepare: " + e);
19660             destroyUserDataLI(volumeUuid, userId,
19661                     StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19662
19663             if (allowRecover) {
19664                 // Try one last time; if we fail again we're really in trouble
19665                 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19666             }
19667         }
19668     }
19669
19670     /**
19671      * Destroy storage areas for given user on all mounted devices.
19672      */
19673     void destroyUserData(int userId, int flags) {
19674         synchronized (mInstallLock) {
19675             final StorageManager storage = mContext.getSystemService(StorageManager.class);
19676             for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19677                 final String volumeUuid = vol.getFsUuid();
19678                 destroyUserDataLI(volumeUuid, userId, flags);
19679             }
19680         }
19681     }
19682
19683     private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19684         final StorageManager storage = mContext.getSystemService(StorageManager.class);
19685         try {
19686             // Clean up app data, profile data, and media data
19687             mInstaller.destroyUserData(volumeUuid, userId, flags);
19688
19689             // Clean up system data
19690             if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19691                 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19692                     FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19693                     FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19694                 }
19695                 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19696                     FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19697                 }
19698             }
19699
19700             // Data with special labels is now gone, so finish the job
19701             storage.destroyUserStorage(volumeUuid, userId, flags);
19702
19703         } catch (Exception e) {
19704             logCriticalInfo(Log.WARN,
19705                     "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19706         }
19707     }
19708
19709     /**
19710      * Examine all users present on given mounted volume, and destroy data
19711      * belonging to users that are no longer valid, or whose user ID has been
19712      * recycled.
19713      */
19714     private void reconcileUsers(String volumeUuid) {
19715         final List<File> files = new ArrayList<>();
19716         Collections.addAll(files, FileUtils
19717                 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19718         Collections.addAll(files, FileUtils
19719                 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19720         Collections.addAll(files, FileUtils
19721                 .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19722         Collections.addAll(files, FileUtils
19723                 .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19724         for (File file : files) {
19725             if (!file.isDirectory()) continue;
19726
19727             final int userId;
19728             final UserInfo info;
19729             try {
19730                 userId = Integer.parseInt(file.getName());
19731                 info = sUserManager.getUserInfo(userId);
19732             } catch (NumberFormatException e) {
19733                 Slog.w(TAG, "Invalid user directory " + file);
19734                 continue;
19735             }
19736
19737             boolean destroyUser = false;
19738             if (info == null) {
19739                 logCriticalInfo(Log.WARN, "Destroying user directory " + file
19740                         + " because no matching user was found");
19741                 destroyUser = true;
19742             } else if (!mOnlyCore) {
19743                 try {
19744                     UserManagerService.enforceSerialNumber(file, info.serialNumber);
19745                 } catch (IOException e) {
19746                     logCriticalInfo(Log.WARN, "Destroying user directory " + file
19747                             + " because we failed to enforce serial number: " + e);
19748                     destroyUser = true;
19749                 }
19750             }
19751
19752             if (destroyUser) {
19753                 synchronized (mInstallLock) {
19754                     destroyUserDataLI(volumeUuid, userId,
19755                             StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19756                 }
19757             }
19758         }
19759     }
19760
19761     private void assertPackageKnown(String volumeUuid, String packageName)
19762             throws PackageManagerException {
19763         synchronized (mPackages) {
19764             // Normalize package name to handle renamed packages
19765             packageName = normalizePackageNameLPr(packageName);
19766
19767             final PackageSetting ps = mSettings.mPackages.get(packageName);
19768             if (ps == null) {
19769                 throw new PackageManagerException("Package " + packageName + " is unknown");
19770             } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19771                 throw new PackageManagerException(
19772                         "Package " + packageName + " found on unknown volume " + volumeUuid
19773                                 + "; expected volume " + ps.volumeUuid);
19774             }
19775         }
19776     }
19777
19778     private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19779             throws PackageManagerException {
19780         synchronized (mPackages) {
19781             // Normalize package name to handle renamed packages
19782             packageName = normalizePackageNameLPr(packageName);
19783
19784             final PackageSetting ps = mSettings.mPackages.get(packageName);
19785             if (ps == null) {
19786                 throw new PackageManagerException("Package " + packageName + " is unknown");
19787             } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19788                 throw new PackageManagerException(
19789                         "Package " + packageName + " found on unknown volume " + volumeUuid
19790                                 + "; expected volume " + ps.volumeUuid);
19791             } else if (!ps.getInstalled(userId)) {
19792                 throw new PackageManagerException(
19793                         "Package " + packageName + " not installed for user " + userId);
19794             }
19795         }
19796     }
19797
19798     /**
19799      * Examine all apps present on given mounted volume, and destroy apps that
19800      * aren't expected, either due to uninstallation or reinstallation on
19801      * another volume.
19802      */
19803     private void reconcileApps(String volumeUuid) {
19804         final File[] files = FileUtils
19805                 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19806         for (File file : files) {
19807             final boolean isPackage = (isApkFile(file) || file.isDirectory())
19808                     && !PackageInstallerService.isStageName(file.getName());
19809             if (!isPackage) {
19810                 // Ignore entries which are not packages
19811                 continue;
19812             }
19813
19814             try {
19815                 final PackageLite pkg = PackageParser.parsePackageLite(file,
19816                         PackageParser.PARSE_MUST_BE_APK);
19817                 assertPackageKnown(volumeUuid, pkg.packageName);
19818
19819             } catch (PackageParserException | PackageManagerException e) {
19820                 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19821                 synchronized (mInstallLock) {
19822                     removeCodePathLI(file);
19823                 }
19824             }
19825         }
19826     }
19827
19828     /**
19829      * Reconcile all app data for the given user.
19830      * <p>
19831      * Verifies that directories exist and that ownership and labeling is
19832      * correct for all installed apps on all mounted volumes.
19833      */
19834     void reconcileAppsData(int userId, int flags) {
19835         final StorageManager storage = mContext.getSystemService(StorageManager.class);
19836         for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19837             final String volumeUuid = vol.getFsUuid();
19838             synchronized (mInstallLock) {
19839                 reconcileAppsDataLI(volumeUuid, userId, flags);
19840             }
19841         }
19842     }
19843
19844     /**
19845      * Reconcile all app data on given mounted volume.
19846      * <p>
19847      * Destroys app data that isn't expected, either due to uninstallation or
19848      * reinstallation on another volume.
19849      * <p>
19850      * Verifies that directories exist and that ownership and labeling is
19851      * correct for all installed apps.
19852      */
19853     private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19854         Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19855                 + Integer.toHexString(flags));
19856
19857         final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19858         final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19859
19860         // First look for stale data that doesn't belong, and check if things
19861         // have changed since we did our last restorecon
19862         if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19863             if (StorageManager.isFileEncryptedNativeOrEmulated()
19864                     && !StorageManager.isUserKeyUnlocked(userId)) {
19865                 throw new RuntimeException(
19866                         "Yikes, someone asked us to reconcile CE storage while " + userId
19867                                 + " was still locked; this would have caused massive data loss!");
19868             }
19869
19870             final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19871             for (File file : files) {
19872                 final String packageName = file.getName();
19873                 try {
19874                     assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19875                 } catch (PackageManagerException e) {
19876                     logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19877                     try {
19878                         mInstaller.destroyAppData(volumeUuid, packageName, userId,
19879                                 StorageManager.FLAG_STORAGE_CE, 0);
19880                     } catch (InstallerException e2) {
19881                         logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19882                     }
19883                 }
19884             }
19885         }
19886         if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19887             final File[] files = FileUtils.listFilesOrEmpty(deDir);
19888             for (File file : files) {
19889                 final String packageName = file.getName();
19890                 try {
19891                     assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19892                 } catch (PackageManagerException e) {
19893                     logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19894                     try {
19895                         mInstaller.destroyAppData(volumeUuid, packageName, userId,
19896                                 StorageManager.FLAG_STORAGE_DE, 0);
19897                     } catch (InstallerException e2) {
19898                         logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19899                     }
19900                 }
19901             }
19902         }
19903
19904         // Ensure that data directories are ready to roll for all packages
19905         // installed for this volume and user
19906         final List<PackageSetting> packages;
19907         synchronized (mPackages) {
19908             packages = mSettings.getVolumePackagesLPr(volumeUuid);
19909         }
19910         int preparedCount = 0;
19911         for (PackageSetting ps : packages) {
19912             final String packageName = ps.name;
19913             if (ps.pkg == null) {
19914                 Slog.w(TAG, "Odd, missing scanned package " + packageName);
19915                 // TODO: might be due to legacy ASEC apps; we should circle back
19916                 // and reconcile again once they're scanned
19917                 continue;
19918             }
19919
19920             if (ps.getInstalled(userId)) {
19921                 prepareAppDataLIF(ps.pkg, userId, flags);
19922
19923                 if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19924                     // We may have just shuffled around app data directories, so
19925                     // prepare them one more time
19926                     prepareAppDataLIF(ps.pkg, userId, flags);
19927                 }
19928
19929                 preparedCount++;
19930             }
19931         }
19932
19933         Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
19934     }
19935
19936     /**
19937      * Prepare app data for the given app just after it was installed or
19938      * upgraded. This method carefully only touches users that it's installed
19939      * for, and it forces a restorecon to handle any seinfo changes.
19940      * <p>
19941      * Verifies that directories exist and that ownership and labeling is
19942      * correct for all installed apps. If there is an ownership mismatch, it
19943      * will try recovering system apps by wiping data; third-party app data is
19944      * left intact.
19945      * <p>
19946      * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19947      */
19948     private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19949         final PackageSetting ps;
19950         synchronized (mPackages) {
19951             ps = mSettings.mPackages.get(pkg.packageName);
19952             mSettings.writeKernelMappingLPr(ps);
19953         }
19954
19955         final UserManager um = mContext.getSystemService(UserManager.class);
19956         UserManagerInternal umInternal = getUserManagerInternal();
19957         for (UserInfo user : um.getUsers()) {
19958             final int flags;
19959             if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19960                 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19961             } else if (umInternal.isUserRunning(user.id)) {
19962                 flags = StorageManager.FLAG_STORAGE_DE;
19963             } else {
19964                 continue;
19965             }
19966
19967             if (ps.getInstalled(user.id)) {
19968                 // TODO: when user data is locked, mark that we're still dirty
19969                 prepareAppDataLIF(pkg, user.id, flags);
19970             }
19971         }
19972     }
19973
19974     /**
19975      * Prepare app data for the given app.
19976      * <p>
19977      * Verifies that directories exist and that ownership and labeling is
19978      * correct for all installed apps. If there is an ownership mismatch, this
19979      * will try recovering system apps by wiping data; third-party app data is
19980      * left intact.
19981      */
19982     private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
19983         if (pkg == null) {
19984             Slog.wtf(TAG, "Package was null!", new Throwable());
19985             return;
19986         }
19987         prepareAppDataLeafLIF(pkg, userId, flags);
19988         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19989         for (int i = 0; i < childCount; i++) {
19990             prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
19991         }
19992     }
19993
19994     private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19995         if (DEBUG_APP_DATA) {
19996             Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19997                     + Integer.toHexString(flags));
19998         }
19999
20000         final String volumeUuid = pkg.volumeUuid;
20001         final String packageName = pkg.packageName;
20002         final ApplicationInfo app = pkg.applicationInfo;
20003         final int appId = UserHandle.getAppId(app.uid);
20004
20005         Preconditions.checkNotNull(app.seinfo);
20006
20007         try {
20008             mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20009                     appId, app.seinfo, app.targetSdkVersion);
20010         } catch (InstallerException e) {
20011             if (app.isSystemApp()) {
20012                 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20013                         + ", but trying to recover: " + e);
20014                 destroyAppDataLeafLIF(pkg, userId, flags);
20015                 try {
20016                     mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20017                             appId, app.seinfo, app.targetSdkVersion);
20018                     logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20019                 } catch (InstallerException e2) {
20020                     logCriticalInfo(Log.DEBUG, "Recovery failed!");
20021                 }
20022             } else {
20023                 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20024             }
20025         }
20026
20027         if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20028             try {
20029                 // CE storage is unlocked right now, so read out the inode and
20030                 // remember for use later when it's locked
20031                 // TODO: mark this structure as dirty so we persist it!
20032                 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
20033                         StorageManager.FLAG_STORAGE_CE);
20034                 synchronized (mPackages) {
20035                     final PackageSetting ps = mSettings.mPackages.get(packageName);
20036                     if (ps != null) {
20037                         ps.setCeDataInode(ceDataInode, userId);
20038                     }
20039                 }
20040             } catch (InstallerException e) {
20041                 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
20042             }
20043         }
20044
20045         prepareAppDataContentsLeafLIF(pkg, userId, flags);
20046     }
20047
20048     private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20049         if (pkg == null) {
20050             Slog.wtf(TAG, "Package was null!", new Throwable());
20051             return;
20052         }
20053         prepareAppDataContentsLeafLIF(pkg, userId, flags);
20054         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20055         for (int i = 0; i < childCount; i++) {
20056             prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20057         }
20058     }
20059
20060     private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20061         final String volumeUuid = pkg.volumeUuid;
20062         final String packageName = pkg.packageName;
20063         final ApplicationInfo app = pkg.applicationInfo;
20064
20065         if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20066             // Create a native library symlink only if we have native libraries
20067             // and if the native libraries are 32 bit libraries. We do not provide
20068             // this symlink for 64 bit libraries.
20069             if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20070                 final String nativeLibPath = app.nativeLibraryDir;
20071                 try {
20072                     mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20073                             nativeLibPath, userId);
20074                 } catch (InstallerException e) {
20075                     Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20076                 }
20077             }
20078         }
20079     }
20080
20081     /**
20082      * For system apps on non-FBE devices, this method migrates any existing
20083      * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20084      * requested by the app.
20085      */
20086     private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20087         if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20088                 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20089             final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20090                     ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20091             try {
20092                 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20093                         storageTarget);
20094             } catch (InstallerException e) {
20095                 logCriticalInfo(Log.WARN,
20096                         "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20097             }
20098             return true;
20099         } else {
20100             return false;
20101         }
20102     }
20103
20104     public PackageFreezer freezePackage(String packageName, String killReason) {
20105         return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20106     }
20107
20108     public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20109         return new PackageFreezer(packageName, userId, killReason);
20110     }
20111
20112     public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20113             String killReason) {
20114         return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20115     }
20116
20117     public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20118             String killReason) {
20119         if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20120             return new PackageFreezer();
20121         } else {
20122             return freezePackage(packageName, userId, killReason);
20123         }
20124     }
20125
20126     public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20127             String killReason) {
20128         return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20129     }
20130
20131     public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20132             String killReason) {
20133         if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20134             return new PackageFreezer();
20135         } else {
20136             return freezePackage(packageName, userId, killReason);
20137         }
20138     }
20139
20140     /**
20141      * Class that freezes and kills the given package upon creation, and
20142      * unfreezes it upon closing. This is typically used when doing surgery on
20143      * app code/data to prevent the app from running while you're working.
20144      */
20145     private class PackageFreezer implements AutoCloseable {
20146         private final String mPackageName;
20147         private final PackageFreezer[] mChildren;
20148
20149         private final boolean mWeFroze;
20150
20151         private final AtomicBoolean mClosed = new AtomicBoolean();
20152         private final CloseGuard mCloseGuard = CloseGuard.get();
20153
20154         /**
20155          * Create and return a stub freezer that doesn't actually do anything,
20156          * typically used when someone requested
20157          * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20158          * {@link PackageManager#DELETE_DONT_KILL_APP}.
20159          */
20160         public PackageFreezer() {
20161             mPackageName = null;
20162             mChildren = null;
20163             mWeFroze = false;
20164             mCloseGuard.open("close");
20165         }
20166
20167         public PackageFreezer(String packageName, int userId, String killReason) {
20168             synchronized (mPackages) {
20169                 mPackageName = packageName;
20170                 mWeFroze = mFrozenPackages.add(mPackageName);
20171
20172                 final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20173                 if (ps != null) {
20174                     killApplication(ps.name, ps.appId, userId, killReason);
20175                 }
20176
20177                 final PackageParser.Package p = mPackages.get(packageName);
20178                 if (p != null && p.childPackages != null) {
20179                     final int N = p.childPackages.size();
20180                     mChildren = new PackageFreezer[N];
20181                     for (int i = 0; i < N; i++) {
20182                         mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20183                                 userId, killReason);
20184                     }
20185                 } else {
20186                     mChildren = null;
20187                 }
20188             }
20189             mCloseGuard.open("close");
20190         }
20191
20192         @Override
20193         protected void finalize() throws Throwable {
20194             try {
20195                 mCloseGuard.warnIfOpen();
20196                 close();
20197             } finally {
20198                 super.finalize();
20199             }
20200         }
20201
20202         @Override
20203         public void close() {
20204             mCloseGuard.close();
20205             if (mClosed.compareAndSet(false, true)) {
20206                 synchronized (mPackages) {
20207                     if (mWeFroze) {
20208                         mFrozenPackages.remove(mPackageName);
20209                     }
20210
20211                     if (mChildren != null) {
20212                         for (PackageFreezer freezer : mChildren) {
20213                             freezer.close();
20214                         }
20215                     }
20216                 }
20217             }
20218         }
20219     }
20220
20221     /**
20222      * Verify that given package is currently frozen.
20223      */
20224     private void checkPackageFrozen(String packageName) {
20225         synchronized (mPackages) {
20226             if (!mFrozenPackages.contains(packageName)) {
20227                 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20228             }
20229         }
20230     }
20231
20232     @Override
20233     public int movePackage(final String packageName, final String volumeUuid) {
20234         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20235
20236         final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20237         final int moveId = mNextMoveId.getAndIncrement();
20238         mHandler.post(new Runnable() {
20239             @Override
20240             public void run() {
20241                 try {
20242                     movePackageInternal(packageName, volumeUuid, moveId, user);
20243                 } catch (PackageManagerException e) {
20244                     Slog.w(TAG, "Failed to move " + packageName, e);
20245                     mMoveCallbacks.notifyStatusChanged(moveId,
20246                             PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20247                 }
20248             }
20249         });
20250         return moveId;
20251     }
20252
20253     private void movePackageInternal(final String packageName, final String volumeUuid,
20254             final int moveId, UserHandle user) throws PackageManagerException {
20255         final StorageManager storage = mContext.getSystemService(StorageManager.class);
20256         final PackageManager pm = mContext.getPackageManager();
20257
20258         final boolean currentAsec;
20259         final String currentVolumeUuid;
20260         final File codeFile;
20261         final String installerPackageName;
20262         final String packageAbiOverride;
20263         final int appId;
20264         final String seinfo;
20265         final String label;
20266         final int targetSdkVersion;
20267         final PackageFreezer freezer;
20268         final int[] installedUserIds;
20269
20270         // reader
20271         synchronized (mPackages) {
20272             final PackageParser.Package pkg = mPackages.get(packageName);
20273             final PackageSetting ps = mSettings.mPackages.get(packageName);
20274             if (pkg == null || ps == null) {
20275                 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20276             }
20277
20278             if (pkg.applicationInfo.isSystemApp()) {
20279                 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20280                         "Cannot move system application");
20281             }
20282
20283             if (pkg.applicationInfo.isExternalAsec()) {
20284                 currentAsec = true;
20285                 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20286             } else if (pkg.applicationInfo.isForwardLocked()) {
20287                 currentAsec = true;
20288                 currentVolumeUuid = "forward_locked";
20289             } else {
20290                 currentAsec = false;
20291                 currentVolumeUuid = ps.volumeUuid;
20292
20293                 final File probe = new File(pkg.codePath);
20294                 final File probeOat = new File(probe, "oat");
20295                 if (!probe.isDirectory() || !probeOat.isDirectory()) {
20296                     throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20297                             "Move only supported for modern cluster style installs");
20298                 }
20299             }
20300
20301             if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20302                 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20303                         "Package already moved to " + volumeUuid);
20304             }
20305             if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20306                 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20307                         "Device admin cannot be moved");
20308             }
20309
20310             if (mFrozenPackages.contains(packageName)) {
20311                 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20312                         "Failed to move already frozen package");
20313             }
20314
20315             codeFile = new File(pkg.codePath);
20316             installerPackageName = ps.installerPackageName;
20317             packageAbiOverride = ps.cpuAbiOverrideString;
20318             appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20319             seinfo = pkg.applicationInfo.seinfo;
20320             label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20321             targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20322             freezer = freezePackage(packageName, "movePackageInternal");
20323             installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20324         }
20325
20326         final Bundle extras = new Bundle();
20327         extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20328         extras.putString(Intent.EXTRA_TITLE, label);
20329         mMoveCallbacks.notifyCreated(moveId, extras);
20330
20331         int installFlags;
20332         final boolean moveCompleteApp;
20333         final File measurePath;
20334
20335         if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20336             installFlags = INSTALL_INTERNAL;
20337             moveCompleteApp = !currentAsec;
20338             measurePath = Environment.getDataAppDirectory(volumeUuid);
20339         } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20340             installFlags = INSTALL_EXTERNAL;
20341             moveCompleteApp = false;
20342             measurePath = storage.getPrimaryPhysicalVolume().getPath();
20343         } else {
20344             final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20345             if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20346                     || !volume.isMountedWritable()) {
20347                 freezer.close();
20348                 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20349                         "Move location not mounted private volume");
20350             }
20351
20352             Preconditions.checkState(!currentAsec);
20353
20354             installFlags = INSTALL_INTERNAL;
20355             moveCompleteApp = true;
20356             measurePath = Environment.getDataAppDirectory(volumeUuid);
20357         }
20358
20359         final PackageStats stats = new PackageStats(null, -1);
20360         synchronized (mInstaller) {
20361             for (int userId : installedUserIds) {
20362                 if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20363                     freezer.close();
20364                     throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20365                             "Failed to measure package size");
20366                 }
20367             }
20368         }
20369
20370         if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20371                 + stats.dataSize);
20372
20373         final long startFreeBytes = measurePath.getFreeSpace();
20374         final long sizeBytes;
20375         if (moveCompleteApp) {
20376             sizeBytes = stats.codeSize + stats.dataSize;
20377         } else {
20378             sizeBytes = stats.codeSize;
20379         }
20380
20381         if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20382             freezer.close();
20383             throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20384                     "Not enough free space to move");
20385         }
20386
20387         mMoveCallbacks.notifyStatusChanged(moveId, 10);
20388
20389         final CountDownLatch installedLatch = new CountDownLatch(1);
20390         final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20391             @Override
20392             public void onUserActionRequired(Intent intent) throws RemoteException {
20393                 throw new IllegalStateException();
20394             }
20395
20396             @Override
20397             public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20398                     Bundle extras) throws RemoteException {
20399                 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20400                         + PackageManager.installStatusToString(returnCode, msg));
20401
20402                 installedLatch.countDown();
20403                 freezer.close();
20404
20405                 final int status = PackageManager.installStatusToPublicStatus(returnCode);
20406                 switch (status) {
20407                     case PackageInstaller.STATUS_SUCCESS:
20408                         mMoveCallbacks.notifyStatusChanged(moveId,
20409                                 PackageManager.MOVE_SUCCEEDED);
20410                         break;
20411                     case PackageInstaller.STATUS_FAILURE_STORAGE:
20412                         mMoveCallbacks.notifyStatusChanged(moveId,
20413                                 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20414                         break;
20415                     default:
20416                         mMoveCallbacks.notifyStatusChanged(moveId,
20417                                 PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20418                         break;
20419                 }
20420             }
20421         };
20422
20423         final MoveInfo move;
20424         if (moveCompleteApp) {
20425             // Kick off a thread to report progress estimates
20426             new Thread() {
20427                 @Override
20428                 public void run() {
20429                     while (true) {
20430                         try {
20431                             if (installedLatch.await(1, TimeUnit.SECONDS)) {
20432                                 break;
20433                             }
20434                         } catch (InterruptedException ignored) {
20435                         }
20436
20437                         final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20438                         final int progress = 10 + (int) MathUtils.constrain(
20439                                 ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20440                         mMoveCallbacks.notifyStatusChanged(moveId, progress);
20441                     }
20442                 }
20443             }.start();
20444
20445             final String dataAppName = codeFile.getName();
20446             move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20447                     dataAppName, appId, seinfo, targetSdkVersion);
20448         } else {
20449             move = null;
20450         }
20451
20452         installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20453
20454         final Message msg = mHandler.obtainMessage(INIT_COPY);
20455         final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20456         final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20457                 installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20458                 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20459         params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20460         msg.obj = params;
20461
20462         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20463                 System.identityHashCode(msg.obj));
20464         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20465                 System.identityHashCode(msg.obj));
20466
20467         mHandler.sendMessage(msg);
20468     }
20469
20470     @Override
20471     public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20472         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20473
20474         final int realMoveId = mNextMoveId.getAndIncrement();
20475         final Bundle extras = new Bundle();
20476         extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20477         mMoveCallbacks.notifyCreated(realMoveId, extras);
20478
20479         final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20480             @Override
20481             public void onCreated(int moveId, Bundle extras) {
20482                 // Ignored
20483             }
20484
20485             @Override
20486             public void onStatusChanged(int moveId, int status, long estMillis) {
20487                 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20488             }
20489         };
20490
20491         final StorageManager storage = mContext.getSystemService(StorageManager.class);
20492         storage.setPrimaryStorageUuid(volumeUuid, callback);
20493         return realMoveId;
20494     }
20495
20496     @Override
20497     public int getMoveStatus(int moveId) {
20498         mContext.enforceCallingOrSelfPermission(
20499                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20500         return mMoveCallbacks.mLastStatus.get(moveId);
20501     }
20502
20503     @Override
20504     public void registerMoveCallback(IPackageMoveObserver callback) {
20505         mContext.enforceCallingOrSelfPermission(
20506                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20507         mMoveCallbacks.register(callback);
20508     }
20509
20510     @Override
20511     public void unregisterMoveCallback(IPackageMoveObserver callback) {
20512         mContext.enforceCallingOrSelfPermission(
20513                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20514         mMoveCallbacks.unregister(callback);
20515     }
20516
20517     @Override
20518     public boolean setInstallLocation(int loc) {
20519         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20520                 null);
20521         if (getInstallLocation() == loc) {
20522             return true;
20523         }
20524         if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20525                 || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20526             android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20527                     android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20528             return true;
20529         }
20530         return false;
20531    }
20532
20533     @Override
20534     public int getInstallLocation() {
20535         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20536                 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20537                 PackageHelper.APP_INSTALL_AUTO);
20538     }
20539
20540     /** Called by UserManagerService */
20541     void cleanUpUser(UserManagerService userManager, int userHandle) {
20542         synchronized (mPackages) {
20543             mDirtyUsers.remove(userHandle);
20544             mUserNeedsBadging.delete(userHandle);
20545             mSettings.removeUserLPw(userHandle);
20546             mPendingBroadcasts.remove(userHandle);
20547             mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20548             removeUnusedPackagesLPw(userManager, userHandle);
20549         }
20550     }
20551
20552     /**
20553      * We're removing userHandle and would like to remove any downloaded packages
20554      * that are no longer in use by any other user.
20555      * @param userHandle the user being removed
20556      */
20557     private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20558         final boolean DEBUG_CLEAN_APKS = false;
20559         int [] users = userManager.getUserIds();
20560         Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20561         while (psit.hasNext()) {
20562             PackageSetting ps = psit.next();
20563             if (ps.pkg == null) {
20564                 continue;
20565             }
20566             final String packageName = ps.pkg.packageName;
20567             // Skip over if system app
20568             if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20569                 continue;
20570             }
20571             if (DEBUG_CLEAN_APKS) {
20572                 Slog.i(TAG, "Checking package " + packageName);
20573             }
20574             boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20575             if (keep) {
20576                 if (DEBUG_CLEAN_APKS) {
20577                     Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20578                 }
20579             } else {
20580                 for (int i = 0; i < users.length; i++) {
20581                     if (users[i] != userHandle && ps.getInstalled(users[i])) {
20582                         keep = true;
20583                         if (DEBUG_CLEAN_APKS) {
20584                             Slog.i(TAG, "  Keeping package " + packageName + " for user "
20585                                     + users[i]);
20586                         }
20587                         break;
20588                     }
20589                 }
20590             }
20591             if (!keep) {
20592                 if (DEBUG_CLEAN_APKS) {
20593                     Slog.i(TAG, "  Removing package " + packageName);
20594                 }
20595                 mHandler.post(new Runnable() {
20596                     public void run() {
20597                         deletePackageX(packageName, userHandle, 0);
20598                     } //end run
20599                 });
20600             }
20601         }
20602     }
20603
20604     /** Called by UserManagerService */
20605     void createNewUser(int userId) {
20606         synchronized (mInstallLock) {
20607             mSettings.createNewUserLI(this, mInstaller, userId);
20608         }
20609         synchronized (mPackages) {
20610             scheduleWritePackageRestrictionsLocked(userId);
20611             scheduleWritePackageListLocked(userId);
20612             applyFactoryDefaultBrowserLPw(userId);
20613             primeDomainVerificationsLPw(userId);
20614         }
20615     }
20616
20617     void onNewUserCreated(final int userId) {
20618         mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20619         // If permission review for legacy apps is required, we represent
20620         // dagerous permissions for such apps as always granted runtime
20621         // permissions to keep per user flag state whether review is needed.
20622         // Hence, if a new user is added we have to propagate dangerous
20623         // permission grants for these legacy apps.
20624         if (mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) {
20625             updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20626                     | UPDATE_PERMISSIONS_REPLACE_ALL);
20627         }
20628     }
20629
20630     @Override
20631     public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20632         mContext.enforceCallingOrSelfPermission(
20633                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20634                 "Only package verification agents can read the verifier device identity");
20635
20636         synchronized (mPackages) {
20637             return mSettings.getVerifierDeviceIdentityLPw();
20638         }
20639     }
20640
20641     @Override
20642     public void setPermissionEnforced(String permission, boolean enforced) {
20643         // TODO: Now that we no longer change GID for storage, this should to away.
20644         mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20645                 "setPermissionEnforced");
20646         if (READ_EXTERNAL_STORAGE.equals(permission)) {
20647             synchronized (mPackages) {
20648                 if (mSettings.mReadExternalStorageEnforced == null
20649                         || mSettings.mReadExternalStorageEnforced != enforced) {
20650                     mSettings.mReadExternalStorageEnforced = enforced;
20651                     mSettings.writeLPr();
20652                 }
20653             }
20654             // kill any non-foreground processes so we restart them and
20655             // grant/revoke the GID.
20656             final IActivityManager am = ActivityManagerNative.getDefault();
20657             if (am != null) {
20658                 final long token = Binder.clearCallingIdentity();
20659                 try {
20660                     am.killProcessesBelowForeground("setPermissionEnforcement");
20661                 } catch (RemoteException e) {
20662                 } finally {
20663                     Binder.restoreCallingIdentity(token);
20664                 }
20665             }
20666         } else {
20667             throw new IllegalArgumentException("No selective enforcement for " + permission);
20668         }
20669     }
20670
20671     @Override
20672     @Deprecated
20673     public boolean isPermissionEnforced(String permission) {
20674         return true;
20675     }
20676
20677     @Override
20678     public boolean isStorageLow() {
20679         final long token = Binder.clearCallingIdentity();
20680         try {
20681             final DeviceStorageMonitorInternal
20682                     dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20683             if (dsm != null) {
20684                 return dsm.isMemoryLow();
20685             } else {
20686                 return false;
20687             }
20688         } finally {
20689             Binder.restoreCallingIdentity(token);
20690         }
20691     }
20692
20693     @Override
20694     public IPackageInstaller getPackageInstaller() {
20695         return mInstallerService;
20696     }
20697
20698     private boolean userNeedsBadging(int userId) {
20699         int index = mUserNeedsBadging.indexOfKey(userId);
20700         if (index < 0) {
20701             final UserInfo userInfo;
20702             final long token = Binder.clearCallingIdentity();
20703             try {
20704                 userInfo = sUserManager.getUserInfo(userId);
20705             } finally {
20706                 Binder.restoreCallingIdentity(token);
20707             }
20708             final boolean b;
20709             if (userInfo != null && userInfo.isManagedProfile()) {
20710                 b = true;
20711             } else {
20712                 b = false;
20713             }
20714             mUserNeedsBadging.put(userId, b);
20715             return b;
20716         }
20717         return mUserNeedsBadging.valueAt(index);
20718     }
20719
20720     @Override
20721     public KeySet getKeySetByAlias(String packageName, String alias) {
20722         if (packageName == null || alias == null) {
20723             return null;
20724         }
20725         synchronized(mPackages) {
20726             final PackageParser.Package pkg = mPackages.get(packageName);
20727             if (pkg == null) {
20728                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20729                 throw new IllegalArgumentException("Unknown package: " + packageName);
20730             }
20731             KeySetManagerService ksms = mSettings.mKeySetManagerService;
20732             return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20733         }
20734     }
20735
20736     @Override
20737     public KeySet getSigningKeySet(String packageName) {
20738         if (packageName == null) {
20739             return null;
20740         }
20741         synchronized(mPackages) {
20742             final PackageParser.Package pkg = mPackages.get(packageName);
20743             if (pkg == null) {
20744                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20745                 throw new IllegalArgumentException("Unknown package: " + packageName);
20746             }
20747             if (pkg.applicationInfo.uid != Binder.getCallingUid()
20748                     && Process.SYSTEM_UID != Binder.getCallingUid()) {
20749                 throw new SecurityException("May not access signing KeySet of other apps.");
20750             }
20751             KeySetManagerService ksms = mSettings.mKeySetManagerService;
20752             return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20753         }
20754     }
20755
20756     @Override
20757     public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20758         if (packageName == null || ks == null) {
20759             return false;
20760         }
20761         synchronized(mPackages) {
20762             final PackageParser.Package pkg = mPackages.get(packageName);
20763             if (pkg == null) {
20764                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20765                 throw new IllegalArgumentException("Unknown package: " + packageName);
20766             }
20767             IBinder ksh = ks.getToken();
20768             if (ksh instanceof KeySetHandle) {
20769                 KeySetManagerService ksms = mSettings.mKeySetManagerService;
20770                 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20771             }
20772             return false;
20773         }
20774     }
20775
20776     @Override
20777     public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20778         if (packageName == null || ks == null) {
20779             return false;
20780         }
20781         synchronized(mPackages) {
20782             final PackageParser.Package pkg = mPackages.get(packageName);
20783             if (pkg == null) {
20784                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20785                 throw new IllegalArgumentException("Unknown package: " + packageName);
20786             }
20787             IBinder ksh = ks.getToken();
20788             if (ksh instanceof KeySetHandle) {
20789                 KeySetManagerService ksms = mSettings.mKeySetManagerService;
20790                 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20791             }
20792             return false;
20793         }
20794     }
20795
20796     private void deletePackageIfUnusedLPr(final String packageName) {
20797         PackageSetting ps = mSettings.mPackages.get(packageName);
20798         if (ps == null) {
20799             return;
20800         }
20801         if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20802             // TODO Implement atomic delete if package is unused
20803             // It is currently possible that the package will be deleted even if it is installed
20804             // after this method returns.
20805             mHandler.post(new Runnable() {
20806                 public void run() {
20807                     deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20808                 }
20809             });
20810         }
20811     }
20812
20813     /**
20814      * Check and throw if the given before/after packages would be considered a
20815      * downgrade.
20816      */
20817     private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20818             throws PackageManagerException {
20819         if (after.versionCode < before.mVersionCode) {
20820             throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20821                     "Update version code " + after.versionCode + " is older than current "
20822                     + before.mVersionCode);
20823         } else if (after.versionCode == before.mVersionCode) {
20824             if (after.baseRevisionCode < before.baseRevisionCode) {
20825                 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20826                         "Update base revision code " + after.baseRevisionCode
20827                         + " is older than current " + before.baseRevisionCode);
20828             }
20829
20830             if (!ArrayUtils.isEmpty(after.splitNames)) {
20831                 for (int i = 0; i < after.splitNames.length; i++) {
20832                     final String splitName = after.splitNames[i];
20833                     final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20834                     if (j != -1) {
20835                         if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20836                             throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20837                                     "Update split " + splitName + " revision code "
20838                                     + after.splitRevisionCodes[i] + " is older than current "
20839                                     + before.splitRevisionCodes[j]);
20840                         }
20841                     }
20842                 }
20843             }
20844         }
20845     }
20846
20847     private static class MoveCallbacks extends Handler {
20848         private static final int MSG_CREATED = 1;
20849         private static final int MSG_STATUS_CHANGED = 2;
20850
20851         private final RemoteCallbackList<IPackageMoveObserver>
20852                 mCallbacks = new RemoteCallbackList<>();
20853
20854         private final SparseIntArray mLastStatus = new SparseIntArray();
20855
20856         public MoveCallbacks(Looper looper) {
20857             super(looper);
20858         }
20859
20860         public void register(IPackageMoveObserver callback) {
20861             mCallbacks.register(callback);
20862         }
20863
20864         public void unregister(IPackageMoveObserver callback) {
20865             mCallbacks.unregister(callback);
20866         }
20867
20868         @Override
20869         public void handleMessage(Message msg) {
20870             final SomeArgs args = (SomeArgs) msg.obj;
20871             final int n = mCallbacks.beginBroadcast();
20872             for (int i = 0; i < n; i++) {
20873                 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20874                 try {
20875                     invokeCallback(callback, msg.what, args);
20876                 } catch (RemoteException ignored) {
20877                 }
20878             }
20879             mCallbacks.finishBroadcast();
20880             args.recycle();
20881         }
20882
20883         private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20884                 throws RemoteException {
20885             switch (what) {
20886                 case MSG_CREATED: {
20887                     callback.onCreated(args.argi1, (Bundle) args.arg2);
20888                     break;
20889                 }
20890                 case MSG_STATUS_CHANGED: {
20891                     callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20892                     break;
20893                 }
20894             }
20895         }
20896
20897         private void notifyCreated(int moveId, Bundle extras) {
20898             Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20899
20900             final SomeArgs args = SomeArgs.obtain();
20901             args.argi1 = moveId;
20902             args.arg2 = extras;
20903             obtainMessage(MSG_CREATED, args).sendToTarget();
20904         }
20905
20906         private void notifyStatusChanged(int moveId, int status) {
20907             notifyStatusChanged(moveId, status, -1);
20908         }
20909
20910         private void notifyStatusChanged(int moveId, int status, long estMillis) {
20911             Slog.v(TAG, "Move " + moveId + " status " + status);
20912
20913             final SomeArgs args = SomeArgs.obtain();
20914             args.argi1 = moveId;
20915             args.argi2 = status;
20916             args.arg3 = estMillis;
20917             obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20918
20919             synchronized (mLastStatus) {
20920                 mLastStatus.put(moveId, status);
20921             }
20922         }
20923     }
20924
20925     private final static class OnPermissionChangeListeners extends Handler {
20926         private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20927
20928         private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20929                 new RemoteCallbackList<>();
20930
20931         public OnPermissionChangeListeners(Looper looper) {
20932             super(looper);
20933         }
20934
20935         @Override
20936         public void handleMessage(Message msg) {
20937             switch (msg.what) {
20938                 case MSG_ON_PERMISSIONS_CHANGED: {
20939                     final int uid = msg.arg1;
20940                     handleOnPermissionsChanged(uid);
20941                 } break;
20942             }
20943         }
20944
20945         public void addListenerLocked(IOnPermissionsChangeListener listener) {
20946             mPermissionListeners.register(listener);
20947
20948         }
20949
20950         public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20951             mPermissionListeners.unregister(listener);
20952         }
20953
20954         public void onPermissionsChanged(int uid) {
20955             if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20956                 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20957             }
20958         }
20959
20960         private void handleOnPermissionsChanged(int uid) {
20961             final int count = mPermissionListeners.beginBroadcast();
20962             try {
20963                 for (int i = 0; i < count; i++) {
20964                     IOnPermissionsChangeListener callback = mPermissionListeners
20965                             .getBroadcastItem(i);
20966                     try {
20967                         callback.onPermissionsChanged(uid);
20968                     } catch (RemoteException e) {
20969                         Log.e(TAG, "Permission listener is dead", e);
20970                     }
20971                 }
20972             } finally {
20973                 mPermissionListeners.finishBroadcast();
20974             }
20975         }
20976     }
20977
20978     private class PackageManagerInternalImpl extends PackageManagerInternal {
20979         @Override
20980         public void setLocationPackagesProvider(PackagesProvider provider) {
20981             synchronized (mPackages) {
20982                 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20983             }
20984         }
20985
20986         @Override
20987         public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20988             synchronized (mPackages) {
20989                 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20990             }
20991         }
20992
20993         @Override
20994         public void setSmsAppPackagesProvider(PackagesProvider provider) {
20995             synchronized (mPackages) {
20996                 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20997             }
20998         }
20999
21000         @Override
21001         public void setDialerAppPackagesProvider(PackagesProvider provider) {
21002             synchronized (mPackages) {
21003                 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21004             }
21005         }
21006
21007         @Override
21008         public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21009             synchronized (mPackages) {
21010                 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21011             }
21012         }
21013
21014         @Override
21015         public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21016             synchronized (mPackages) {
21017                 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21018             }
21019         }
21020
21021         @Override
21022         public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21023             synchronized (mPackages) {
21024                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21025                         packageName, userId);
21026             }
21027         }
21028
21029         @Override
21030         public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21031             synchronized (mPackages) {
21032                 mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21033                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21034                         packageName, userId);
21035             }
21036         }
21037
21038         @Override
21039         public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21040             synchronized (mPackages) {
21041                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21042                         packageName, userId);
21043             }
21044         }
21045
21046         @Override
21047         public void setKeepUninstalledPackages(final List<String> packageList) {
21048             Preconditions.checkNotNull(packageList);
21049             List<String> removedFromList = null;
21050             synchronized (mPackages) {
21051                 if (mKeepUninstalledPackages != null) {
21052                     final int packagesCount = mKeepUninstalledPackages.size();
21053                     for (int i = 0; i < packagesCount; i++) {
21054                         String oldPackage = mKeepUninstalledPackages.get(i);
21055                         if (packageList != null && packageList.contains(oldPackage)) {
21056                             continue;
21057                         }
21058                         if (removedFromList == null) {
21059                             removedFromList = new ArrayList<>();
21060                         }
21061                         removedFromList.add(oldPackage);
21062                     }
21063                 }
21064                 mKeepUninstalledPackages = new ArrayList<>(packageList);
21065                 if (removedFromList != null) {
21066                     final int removedCount = removedFromList.size();
21067                     for (int i = 0; i < removedCount; i++) {
21068                         deletePackageIfUnusedLPr(removedFromList.get(i));
21069                     }
21070                 }
21071             }
21072         }
21073
21074         @Override
21075         public boolean isPermissionsReviewRequired(String packageName, int userId) {
21076             synchronized (mPackages) {
21077                 // If we do not support permission review, done.
21078                 if (!mPermissionReviewRequired && !Build.PERMISSIONS_REVIEW_REQUIRED) {
21079                     return false;
21080                 }
21081
21082                 PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21083                 if (packageSetting == null) {
21084                     return false;
21085                 }
21086
21087                 // Permission review applies only to apps not supporting the new permission model.
21088                 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21089                     return false;
21090                 }
21091
21092                 // Legacy apps have the permission and get user consent on launch.
21093                 PermissionsState permissionsState = packageSetting.getPermissionsState();
21094                 return permissionsState.isPermissionReviewRequired(userId);
21095             }
21096         }
21097
21098         @Override
21099         public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21100             return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21101         }
21102
21103         @Override
21104         public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21105                 int userId) {
21106             return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21107         }
21108
21109         @Override
21110         public void setDeviceAndProfileOwnerPackages(
21111                 int deviceOwnerUserId, String deviceOwnerPackage,
21112                 SparseArray<String> profileOwnerPackages) {
21113             mProtectedPackages.setDeviceAndProfileOwnerPackages(
21114                     deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21115         }
21116
21117         @Override
21118         public boolean isPackageDataProtected(int userId, String packageName) {
21119             return mProtectedPackages.isPackageDataProtected(userId, packageName);
21120         }
21121
21122         @Override
21123         public boolean wasPackageEverLaunched(String packageName, int userId) {
21124             synchronized (mPackages) {
21125                 return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21126             }
21127         }
21128
21129         @Override
21130         public String getNameForUid(int uid) {
21131             return PackageManagerService.this.getNameForUid(uid);
21132         }
21133     }
21134
21135     @Override
21136     public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21137         enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21138         synchronized (mPackages) {
21139             final long identity = Binder.clearCallingIdentity();
21140             try {
21141                 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21142                         packageNames, userId);
21143             } finally {
21144                 Binder.restoreCallingIdentity(identity);
21145             }
21146         }
21147     }
21148
21149     private static void enforceSystemOrPhoneCaller(String tag) {
21150         int callingUid = Binder.getCallingUid();
21151         if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21152             throw new SecurityException(
21153                     "Cannot call " + tag + " from UID " + callingUid);
21154         }
21155     }
21156
21157     boolean isHistoricalPackageUsageAvailable() {
21158         return mPackageUsage.isHistoricalPackageUsageAvailable();
21159     }
21160
21161     /**
21162      * Return a <b>copy</b> of the collection of packages known to the package manager.
21163      * @return A copy of the values of mPackages.
21164      */
21165     Collection<PackageParser.Package> getPackages() {
21166         synchronized (mPackages) {
21167             return new ArrayList<>(mPackages.values());
21168         }
21169     }
21170
21171     /**
21172      * Logs process start information (including base APK hash) to the security log.
21173      * @hide
21174      */
21175     public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21176             String apkFile, int pid) {
21177         if (!SecurityLog.isLoggingEnabled()) {
21178             return;
21179         }
21180         Bundle data = new Bundle();
21181         data.putLong("startTimestamp", System.currentTimeMillis());
21182         data.putString("processName", processName);
21183         data.putInt("uid", uid);
21184         data.putString("seinfo", seinfo);
21185         data.putString("apkFile", apkFile);
21186         data.putInt("pid", pid);
21187         Message msg = mProcessLoggingHandler.obtainMessage(
21188                 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21189         msg.setData(data);
21190         mProcessLoggingHandler.sendMessage(msg);
21191     }
21192
21193     public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21194         return mCompilerStats.getPackageStats(pkgName);
21195     }
21196
21197     public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21198         return getOrCreateCompilerPackageStats(pkg.packageName);
21199     }
21200
21201     public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21202         return mCompilerStats.getOrCreatePackageStats(pkgName);
21203     }
21204
21205     public void deleteCompilerPackageStats(String pkgName) {
21206         mCompilerStats.deletePackageStats(pkgName);
21207     }
21208 }