OSDN Git Service

DO NOT MERGE. No direct Uri grants from system. am: 021747a076 -s ours am: 4d9098284...
[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. Also
1650             // for legacy apps in permission review mode we clear the permission
1651             // review flag which is used to emulate runtime permissions for
1652             // legacy apps.
1653             if (grantPermissions) {
1654                 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1655             }
1656
1657             final boolean update = res.removedInfo != null
1658                     && res.removedInfo.removedPackage != null;
1659
1660             // If this is the first time we have child packages for a disabled privileged
1661             // app that had no children, we grant requested runtime permissions to the new
1662             // children if the parent on the system image had them already granted.
1663             if (res.pkg.parentPackage != null) {
1664                 synchronized (mPackages) {
1665                     grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1666                 }
1667             }
1668
1669             synchronized (mPackages) {
1670                 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1671             }
1672
1673             final String packageName = res.pkg.applicationInfo.packageName;
1674             Bundle extras = new Bundle(1);
1675             extras.putInt(Intent.EXTRA_UID, res.uid);
1676
1677             // Determine the set of users who are adding this package for
1678             // the first time vs. those who are seeing an update.
1679             int[] firstUsers = EMPTY_INT_ARRAY;
1680             int[] updateUsers = EMPTY_INT_ARRAY;
1681             if (res.origUsers == null || res.origUsers.length == 0) {
1682                 firstUsers = res.newUsers;
1683             } else {
1684                 for (int newUser : res.newUsers) {
1685                     boolean isNew = true;
1686                     for (int origUser : res.origUsers) {
1687                         if (origUser == newUser) {
1688                             isNew = false;
1689                             break;
1690                         }
1691                     }
1692                     if (isNew) {
1693                         firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1694                     } else {
1695                         updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1696                     }
1697                 }
1698             }
1699
1700             // Send installed broadcasts if the install/update is not ephemeral
1701             if (!isEphemeral(res.pkg)) {
1702                 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1703
1704                 // Send added for users that see the package for the first time
1705                 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1706                         extras, 0 /*flags*/, null /*targetPackage*/,
1707                         null /*finishedReceiver*/, firstUsers);
1708
1709                 // Send added for users that don't see the package for the first time
1710                 if (update) {
1711                     extras.putBoolean(Intent.EXTRA_REPLACING, true);
1712                 }
1713                 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1714                         extras, 0 /*flags*/, null /*targetPackage*/,
1715                         null /*finishedReceiver*/, updateUsers);
1716
1717                 // Send replaced for users that don't see the package for the first time
1718                 if (update) {
1719                     sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1720                             packageName, extras, 0 /*flags*/,
1721                             null /*targetPackage*/, null /*finishedReceiver*/,
1722                             updateUsers);
1723                     sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1724                             null /*package*/, null /*extras*/, 0 /*flags*/,
1725                             packageName /*targetPackage*/,
1726                             null /*finishedReceiver*/, updateUsers);
1727                 } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1728                     // First-install and we did a restore, so we're responsible for the
1729                     // first-launch broadcast.
1730                     if (DEBUG_BACKUP) {
1731                         Slog.i(TAG, "Post-restore of " + packageName
1732                                 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1733                     }
1734                     sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1735                 }
1736
1737                 // Send broadcast package appeared if forward locked/external for all users
1738                 // treat asec-hosted packages like removable media on upgrade
1739                 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1740                     if (DEBUG_INSTALL) {
1741                         Slog.i(TAG, "upgrading pkg " + res.pkg
1742                                 + " is ASEC-hosted -> AVAILABLE");
1743                     }
1744                     final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1745                     ArrayList<String> pkgList = new ArrayList<>(1);
1746                     pkgList.add(packageName);
1747                     sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1748                 }
1749             }
1750
1751             // Work that needs to happen on first install within each user
1752             if (firstUsers != null && firstUsers.length > 0) {
1753                 synchronized (mPackages) {
1754                     for (int userId : firstUsers) {
1755                         // If this app is a browser and it's newly-installed for some
1756                         // users, clear any default-browser state in those users. The
1757                         // app's nature doesn't depend on the user, so we can just check
1758                         // its browser nature in any user and generalize.
1759                         if (packageIsBrowser(packageName, userId)) {
1760                             mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1761                         }
1762
1763                         // We may also need to apply pending (restored) runtime
1764                         // permission grants within these users.
1765                         mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1766                     }
1767                 }
1768             }
1769
1770             // Log current value of "unknown sources" setting
1771             EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1772                     getUnknownSourcesSettings());
1773
1774             // Force a gc to clear up things
1775             Runtime.getRuntime().gc();
1776
1777             // Remove the replaced package's older resources safely now
1778             // We delete after a gc for applications  on sdcard.
1779             if (res.removedInfo != null && res.removedInfo.args != null) {
1780                 synchronized (mInstallLock) {
1781                     res.removedInfo.args.doPostDeleteLI(true);
1782                 }
1783             }
1784         }
1785
1786         // If someone is watching installs - notify them
1787         if (installObserver != null) {
1788             try {
1789                 Bundle extras = extrasForInstallResult(res);
1790                 installObserver.onPackageInstalled(res.name, res.returnCode,
1791                         res.returnMsg, extras);
1792             } catch (RemoteException e) {
1793                 Slog.i(TAG, "Observer no longer exists.");
1794             }
1795         }
1796     }
1797
1798     private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1799             PackageParser.Package pkg) {
1800         if (pkg.parentPackage == null) {
1801             return;
1802         }
1803         if (pkg.requestedPermissions == null) {
1804             return;
1805         }
1806         final PackageSetting disabledSysParentPs = mSettings
1807                 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1808         if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1809                 || !disabledSysParentPs.isPrivileged()
1810                 || (disabledSysParentPs.childPackageNames != null
1811                         && !disabledSysParentPs.childPackageNames.isEmpty())) {
1812             return;
1813         }
1814         final int[] allUserIds = sUserManager.getUserIds();
1815         final int permCount = pkg.requestedPermissions.size();
1816         for (int i = 0; i < permCount; i++) {
1817             String permission = pkg.requestedPermissions.get(i);
1818             BasePermission bp = mSettings.mPermissions.get(permission);
1819             if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1820                 continue;
1821             }
1822             for (int userId : allUserIds) {
1823                 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1824                         permission, userId)) {
1825                     grantRuntimePermission(pkg.packageName, permission, userId);
1826                 }
1827             }
1828         }
1829     }
1830
1831     private StorageEventListener mStorageListener = new StorageEventListener() {
1832         @Override
1833         public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1834             if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1835                 if (vol.state == VolumeInfo.STATE_MOUNTED) {
1836                     final String volumeUuid = vol.getFsUuid();
1837
1838                     // Clean up any users or apps that were removed or recreated
1839                     // while this volume was missing
1840                     reconcileUsers(volumeUuid);
1841                     reconcileApps(volumeUuid);
1842
1843                     // Clean up any install sessions that expired or were
1844                     // cancelled while this volume was missing
1845                     mInstallerService.onPrivateVolumeMounted(volumeUuid);
1846
1847                     loadPrivatePackages(vol);
1848
1849                 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1850                     unloadPrivatePackages(vol);
1851                 }
1852             }
1853
1854             if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1855                 if (vol.state == VolumeInfo.STATE_MOUNTED) {
1856                     updateExternalMediaStatus(true, false);
1857                 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1858                     updateExternalMediaStatus(false, false);
1859                 }
1860             }
1861         }
1862
1863         @Override
1864         public void onVolumeForgotten(String fsUuid) {
1865             if (TextUtils.isEmpty(fsUuid)) {
1866                 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1867                 return;
1868             }
1869
1870             // Remove any apps installed on the forgotten volume
1871             synchronized (mPackages) {
1872                 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1873                 for (PackageSetting ps : packages) {
1874                     Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1875                     deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1876                             UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1877                 }
1878
1879                 mSettings.onVolumeForgotten(fsUuid);
1880                 mSettings.writeLPr();
1881             }
1882         }
1883     };
1884
1885     private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1886             String[] grantedPermissions) {
1887         for (int userId : userIds) {
1888             grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1889         }
1890     }
1891
1892     private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1893             String[] grantedPermissions) {
1894         SettingBase sb = (SettingBase) pkg.mExtras;
1895         if (sb == null) {
1896             return;
1897         }
1898
1899         PermissionsState permissionsState = sb.getPermissionsState();
1900
1901         final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1902                 | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1903
1904         final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
1905                 >= Build.VERSION_CODES.M;
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                 if (supportsRuntimePermissions) {
1917                     // Installer cannot change immutable permissions.
1918                     if ((flags & immutableFlags) == 0) {
1919                         grantRuntimePermission(pkg.packageName, permission, userId);
1920                     }
1921                 } else if (mPermissionReviewRequired) {
1922                     // In permission review mode we clear the review flag when we
1923                     // are asked to install the app with all permissions granted.
1924                     if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
1925                         updatePermissionFlags(permission, pkg.packageName,
1926                                 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0 /*value*/, userId);
1927                     }
1928                 }
1929             }
1930         }
1931     }
1932
1933     Bundle extrasForInstallResult(PackageInstalledInfo res) {
1934         Bundle extras = null;
1935         switch (res.returnCode) {
1936             case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1937                 extras = new Bundle();
1938                 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1939                         res.origPermission);
1940                 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1941                         res.origPackage);
1942                 break;
1943             }
1944             case PackageManager.INSTALL_SUCCEEDED: {
1945                 extras = new Bundle();
1946                 extras.putBoolean(Intent.EXTRA_REPLACING,
1947                         res.removedInfo != null && res.removedInfo.removedPackage != null);
1948                 break;
1949             }
1950         }
1951         return extras;
1952     }
1953
1954     void scheduleWriteSettingsLocked() {
1955         if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1956             mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1957         }
1958     }
1959
1960     void scheduleWritePackageListLocked(int userId) {
1961         if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1962             Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1963             msg.arg1 = userId;
1964             mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1965         }
1966     }
1967
1968     void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1969         final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1970         scheduleWritePackageRestrictionsLocked(userId);
1971     }
1972
1973     void scheduleWritePackageRestrictionsLocked(int userId) {
1974         final int[] userIds = (userId == UserHandle.USER_ALL)
1975                 ? sUserManager.getUserIds() : new int[]{userId};
1976         for (int nextUserId : userIds) {
1977             if (!sUserManager.exists(nextUserId)) return;
1978             mDirtyUsers.add(nextUserId);
1979             if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1980                 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1981             }
1982         }
1983     }
1984
1985     public static PackageManagerService main(Context context, Installer installer,
1986             boolean factoryTest, boolean onlyCore) {
1987         // Self-check for initial settings.
1988         PackageManagerServiceCompilerMapping.checkProperties();
1989
1990         PackageManagerService m = new PackageManagerService(context, installer,
1991                 factoryTest, onlyCore);
1992         m.enableSystemUserPackages();
1993         ServiceManager.addService("package", m);
1994         return m;
1995     }
1996
1997     private void enableSystemUserPackages() {
1998         if (!UserManager.isSplitSystemUser()) {
1999             return;
2000         }
2001         // For system user, enable apps based on the following conditions:
2002         // - app is whitelisted or belong to one of these groups:
2003         //   -- system app which has no launcher icons
2004         //   -- system app which has INTERACT_ACROSS_USERS permission
2005         //   -- system IME app
2006         // - app is not in the blacklist
2007         AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2008         Set<String> enableApps = new ArraySet<>();
2009         enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2010                 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2011                 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2012         ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2013         enableApps.addAll(wlApps);
2014         enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2015                 /* systemAppsOnly */ false, UserHandle.SYSTEM));
2016         ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2017         enableApps.removeAll(blApps);
2018         Log.i(TAG, "Applications installed for system user: " + enableApps);
2019         List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2020                 UserHandle.SYSTEM);
2021         final int allAppsSize = allAps.size();
2022         synchronized (mPackages) {
2023             for (int i = 0; i < allAppsSize; i++) {
2024                 String pName = allAps.get(i);
2025                 PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2026                 // Should not happen, but we shouldn't be failing if it does
2027                 if (pkgSetting == null) {
2028                     continue;
2029                 }
2030                 boolean install = enableApps.contains(pName);
2031                 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2032                     Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2033                             + " for system user");
2034                     pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2035                 }
2036             }
2037         }
2038     }
2039
2040     private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2041         DisplayManager displayManager = (DisplayManager) context.getSystemService(
2042                 Context.DISPLAY_SERVICE);
2043         displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2044     }
2045
2046     /**
2047      * Requests that files preopted on a secondary system partition be copied to the data partition
2048      * if possible.  Note that the actual copying of the files is accomplished by init for security
2049      * reasons. This simply requests that the copy takes place and awaits confirmation of its
2050      * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2051      */
2052     private static void requestCopyPreoptedFiles() {
2053         final int WAIT_TIME_MS = 100;
2054         final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2055         if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2056             SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2057             // We will wait for up to 100 seconds.
2058             final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2059             while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2060                 try {
2061                     Thread.sleep(WAIT_TIME_MS);
2062                 } catch (InterruptedException e) {
2063                     // Do nothing
2064                 }
2065                 if (SystemClock.uptimeMillis() > timeEnd) {
2066                     SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2067                     Slog.wtf(TAG, "cppreopt did not finish!");
2068                     break;
2069                 }
2070             }
2071         }
2072     }
2073
2074     public PackageManagerService(Context context, Installer installer,
2075             boolean factoryTest, boolean onlyCore) {
2076         EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2077                 SystemClock.uptimeMillis());
2078
2079         if (mSdkVersion <= 0) {
2080             Slog.w(TAG, "**** ro.build.version.sdk not set!");
2081         }
2082
2083         mContext = context;
2084
2085         mPermissionReviewRequired = context.getResources().getBoolean(
2086                 R.bool.config_permissionReviewRequired);
2087
2088         mFactoryTest = factoryTest;
2089         mOnlyCore = onlyCore;
2090         mMetrics = new DisplayMetrics();
2091         mSettings = new Settings(mPackages);
2092         mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2093                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2094         mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2095                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2096         mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2097                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2098         mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2099                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2100         mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2101                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2102         mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2103                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2104
2105         String separateProcesses = SystemProperties.get("debug.separate_processes");
2106         if (separateProcesses != null && separateProcesses.length() > 0) {
2107             if ("*".equals(separateProcesses)) {
2108                 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2109                 mSeparateProcesses = null;
2110                 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2111             } else {
2112                 mDefParseFlags = 0;
2113                 mSeparateProcesses = separateProcesses.split(",");
2114                 Slog.w(TAG, "Running with debug.separate_processes: "
2115                         + separateProcesses);
2116             }
2117         } else {
2118             mDefParseFlags = 0;
2119             mSeparateProcesses = null;
2120         }
2121
2122         mInstaller = installer;
2123         mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2124                 "*dexopt*");
2125         mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2126
2127         mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2128                 FgThread.get().getLooper());
2129
2130         getDefaultDisplayMetrics(context, mMetrics);
2131
2132         SystemConfig systemConfig = SystemConfig.getInstance();
2133         mGlobalGids = systemConfig.getGlobalGids();
2134         mSystemPermissions = systemConfig.getSystemPermissions();
2135         mAvailableFeatures = systemConfig.getAvailableFeatures();
2136
2137         mProtectedPackages = new ProtectedPackages(mContext);
2138
2139         synchronized (mInstallLock) {
2140         // writer
2141         synchronized (mPackages) {
2142             mHandlerThread = new ServiceThread(TAG,
2143                     Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2144             mHandlerThread.start();
2145             mHandler = new PackageHandler(mHandlerThread.getLooper());
2146             mProcessLoggingHandler = new ProcessLoggingHandler();
2147             Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2148
2149             mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2150
2151             File dataDir = Environment.getDataDirectory();
2152             mAppInstallDir = new File(dataDir, "app");
2153             mAppLib32InstallDir = new File(dataDir, "app-lib");
2154             mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2155             mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2156             mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2157
2158             sUserManager = new UserManagerService(context, this, mPackages);
2159
2160             // Propagate permission configuration in to package manager.
2161             ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2162                     = systemConfig.getPermissions();
2163             for (int i=0; i<permConfig.size(); i++) {
2164                 SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2165                 BasePermission bp = mSettings.mPermissions.get(perm.name);
2166                 if (bp == null) {
2167                     bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2168                     mSettings.mPermissions.put(perm.name, bp);
2169                 }
2170                 if (perm.gids != null) {
2171                     bp.setGids(perm.gids, perm.perUser);
2172                 }
2173             }
2174
2175             ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2176             for (int i=0; i<libConfig.size(); i++) {
2177                 mSharedLibraries.put(libConfig.keyAt(i),
2178                         new SharedLibraryEntry(libConfig.valueAt(i), null));
2179             }
2180
2181             mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2182
2183             mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2184
2185             // Clean up orphaned packages for which the code path doesn't exist
2186             // and they are an update to a system app - caused by bug/32321269
2187             final int packageSettingCount = mSettings.mPackages.size();
2188             for (int i = packageSettingCount - 1; i >= 0; i--) {
2189                 PackageSetting ps = mSettings.mPackages.valueAt(i);
2190                 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2191                         && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2192                     mSettings.mPackages.removeAt(i);
2193                     mSettings.enableSystemPackageLPw(ps.name);
2194                 }
2195             }
2196
2197             if (mFirstBoot) {
2198                 requestCopyPreoptedFiles();
2199             }
2200
2201             String customResolverActivity = Resources.getSystem().getString(
2202                     R.string.config_customResolverActivity);
2203             if (TextUtils.isEmpty(customResolverActivity)) {
2204                 customResolverActivity = null;
2205             } else {
2206                 mCustomResolverComponentName = ComponentName.unflattenFromString(
2207                         customResolverActivity);
2208             }
2209
2210             long startTime = SystemClock.uptimeMillis();
2211
2212             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2213                     startTime);
2214
2215             // Set flag to monitor and not change apk file paths when
2216             // scanning install directories.
2217             final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2218
2219             final String bootClassPath = System.getenv("BOOTCLASSPATH");
2220             final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2221
2222             if (bootClassPath == null) {
2223                 Slog.w(TAG, "No BOOTCLASSPATH found!");
2224             }
2225
2226             if (systemServerClassPath == null) {
2227                 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2228             }
2229
2230             final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2231             final String[] dexCodeInstructionSets =
2232                     getDexCodeInstructionSets(
2233                             allInstructionSets.toArray(new String[allInstructionSets.size()]));
2234
2235             /**
2236              * Ensure all external libraries have had dexopt run on them.
2237              */
2238             if (mSharedLibraries.size() > 0) {
2239                 // NOTE: For now, we're compiling these system "shared libraries"
2240                 // (and framework jars) into all available architectures. It's possible
2241                 // to compile them only when we come across an app that uses them (there's
2242                 // already logic for that in scanPackageLI) but that adds some complexity.
2243                 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2244                     for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2245                         final String lib = libEntry.path;
2246                         if (lib == null) {
2247                             continue;
2248                         }
2249
2250                         try {
2251                             // Shared libraries do not have profiles so we perform a full
2252                             // AOT compilation (if needed).
2253                             int dexoptNeeded = DexFile.getDexOptNeeded(
2254                                     lib, dexCodeInstructionSet,
2255                                     getCompilerFilterForReason(REASON_SHARED_APK),
2256                                     false /* newProfile */);
2257                             if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2258                                 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2259                                         dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2260                                         getCompilerFilterForReason(REASON_SHARED_APK),
2261                                         StorageManager.UUID_PRIVATE_INTERNAL,
2262                                         SKIP_SHARED_LIBRARY_CHECK);
2263                             }
2264                         } catch (FileNotFoundException e) {
2265                             Slog.w(TAG, "Library not found: " + lib);
2266                         } catch (IOException | InstallerException e) {
2267                             Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2268                                     + e.getMessage());
2269                         }
2270                     }
2271                 }
2272             }
2273
2274             File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2275
2276             final VersionInfo ver = mSettings.getInternalVersion();
2277             mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2278
2279             // when upgrading from pre-M, promote system app permissions from install to runtime
2280             mPromoteSystemApps =
2281                     mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2282
2283             // When upgrading from pre-N, we need to handle package extraction like first boot,
2284             // as there is no profiling data available.
2285             mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2286
2287             mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2288
2289             // save off the names of pre-existing system packages prior to scanning; we don't
2290             // want to automatically grant runtime permissions for new system apps
2291             if (mPromoteSystemApps) {
2292                 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2293                 while (pkgSettingIter.hasNext()) {
2294                     PackageSetting ps = pkgSettingIter.next();
2295                     if (isSystemApp(ps)) {
2296                         mExistingSystemPackages.add(ps.name);
2297                     }
2298                 }
2299             }
2300
2301             // Collect vendor overlay packages. (Do this before scanning any apps.)
2302             // For security and version matching reason, only consider
2303             // overlay packages if they reside in the right directory.
2304             String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2305             if (!overlayThemeDir.isEmpty()) {
2306                 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2307                         | PackageParser.PARSE_IS_SYSTEM
2308                         | PackageParser.PARSE_IS_SYSTEM_DIR
2309                         | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2310             }
2311             scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2312                     | PackageParser.PARSE_IS_SYSTEM
2313                     | PackageParser.PARSE_IS_SYSTEM_DIR
2314                     | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2315
2316             // Find base frameworks (resource packages without code).
2317             scanDirTracedLI(frameworkDir, mDefParseFlags
2318                     | PackageParser.PARSE_IS_SYSTEM
2319                     | PackageParser.PARSE_IS_SYSTEM_DIR
2320                     | PackageParser.PARSE_IS_PRIVILEGED,
2321                     scanFlags | SCAN_NO_DEX, 0);
2322
2323             // Collected privileged system packages.
2324             final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2325             scanDirTracedLI(privilegedAppDir, mDefParseFlags
2326                     | PackageParser.PARSE_IS_SYSTEM
2327                     | PackageParser.PARSE_IS_SYSTEM_DIR
2328                     | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2329
2330             // Collect ordinary system packages.
2331             final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2332             scanDirTracedLI(systemAppDir, mDefParseFlags
2333                     | PackageParser.PARSE_IS_SYSTEM
2334                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2335
2336             // Collect all vendor packages.
2337             File vendorAppDir = new File("/vendor/app");
2338             try {
2339                 vendorAppDir = vendorAppDir.getCanonicalFile();
2340             } catch (IOException e) {
2341                 // failed to look up canonical path, continue with original one
2342             }
2343             scanDirTracedLI(vendorAppDir, mDefParseFlags
2344                     | PackageParser.PARSE_IS_SYSTEM
2345                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2346
2347             // Collect all OEM packages.
2348             final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2349             scanDirTracedLI(oemAppDir, mDefParseFlags
2350                     | PackageParser.PARSE_IS_SYSTEM
2351                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2352
2353             // Prune any system packages that no longer exist.
2354             final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2355             if (!mOnlyCore) {
2356                 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2357                 while (psit.hasNext()) {
2358                     PackageSetting ps = psit.next();
2359
2360                     /*
2361                      * If this is not a system app, it can't be a
2362                      * disable system app.
2363                      */
2364                     if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2365                         continue;
2366                     }
2367
2368                     /*
2369                      * If the package is scanned, it's not erased.
2370                      */
2371                     final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2372                     if (scannedPkg != null) {
2373                         /*
2374                          * If the system app is both scanned and in the
2375                          * disabled packages list, then it must have been
2376                          * added via OTA. Remove it from the currently
2377                          * scanned package so the previously user-installed
2378                          * application can be scanned.
2379                          */
2380                         if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2381                             logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2382                                     + ps.name + "; removing system app.  Last known codePath="
2383                                     + ps.codePathString + ", installStatus=" + ps.installStatus
2384                                     + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2385                                     + scannedPkg.mVersionCode);
2386                             removePackageLI(scannedPkg, true);
2387                             mExpectingBetter.put(ps.name, ps.codePath);
2388                         }
2389
2390                         continue;
2391                     }
2392
2393                     if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2394                         psit.remove();
2395                         logCriticalInfo(Log.WARN, "System package " + ps.name
2396                                 + " no longer exists; it's data will be wiped");
2397                         // Actual deletion of code and data will be handled by later
2398                         // reconciliation step
2399                     } else {
2400                         final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2401                         if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2402                             possiblyDeletedUpdatedSystemApps.add(ps.name);
2403                         }
2404                     }
2405                 }
2406             }
2407
2408             //look for any incomplete package installations
2409             ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2410             for (int i = 0; i < deletePkgsList.size(); i++) {
2411                 // Actual deletion of code and data will be handled by later
2412                 // reconciliation step
2413                 final String packageName = deletePkgsList.get(i).name;
2414                 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2415                 synchronized (mPackages) {
2416                     mSettings.removePackageLPw(packageName);
2417                 }
2418             }
2419
2420             //delete tmp files
2421             deleteTempPackageFiles();
2422
2423             // Remove any shared userIDs that have no associated packages
2424             mSettings.pruneSharedUsersLPw();
2425
2426             if (!mOnlyCore) {
2427                 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2428                         SystemClock.uptimeMillis());
2429                 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2430
2431                 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2432                         | PackageParser.PARSE_FORWARD_LOCK,
2433                         scanFlags | SCAN_REQUIRE_KNOWN, 0);
2434
2435                 scanDirLI(mEphemeralInstallDir, mDefParseFlags
2436                         | PackageParser.PARSE_IS_EPHEMERAL,
2437                         scanFlags | SCAN_REQUIRE_KNOWN, 0);
2438
2439                 /**
2440                  * Remove disable package settings for any updated system
2441                  * apps that were removed via an OTA. If they're not a
2442                  * previously-updated app, remove them completely.
2443                  * Otherwise, just revoke their system-level permissions.
2444                  */
2445                 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2446                     PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2447                     mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2448
2449                     String msg;
2450                     if (deletedPkg == null) {
2451                         msg = "Updated system package " + deletedAppName
2452                                 + " no longer exists; it's data will be wiped";
2453                         // Actual deletion of code and data will be handled by later
2454                         // reconciliation step
2455                     } else {
2456                         msg = "Updated system app + " + deletedAppName
2457                                 + " no longer present; removing system privileges for "
2458                                 + deletedAppName;
2459
2460                         deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2461
2462                         PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2463                         deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2464                     }
2465                     logCriticalInfo(Log.WARN, msg);
2466                 }
2467
2468                 /**
2469                  * Make sure all system apps that we expected to appear on
2470                  * the userdata partition actually showed up. If they never
2471                  * appeared, crawl back and revive the system version.
2472                  */
2473                 for (int i = 0; i < mExpectingBetter.size(); i++) {
2474                     final String packageName = mExpectingBetter.keyAt(i);
2475                     if (!mPackages.containsKey(packageName)) {
2476                         final File scanFile = mExpectingBetter.valueAt(i);
2477
2478                         logCriticalInfo(Log.WARN, "Expected better " + packageName
2479                                 + " but never showed up; reverting to system");
2480
2481                         int reparseFlags = mDefParseFlags;
2482                         if (FileUtils.contains(privilegedAppDir, scanFile)) {
2483                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2484                                     | PackageParser.PARSE_IS_SYSTEM_DIR
2485                                     | PackageParser.PARSE_IS_PRIVILEGED;
2486                         } else if (FileUtils.contains(systemAppDir, scanFile)) {
2487                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2488                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
2489                         } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2490                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2491                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
2492                         } else if (FileUtils.contains(oemAppDir, scanFile)) {
2493                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2494                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
2495                         } else {
2496                             Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2497                             continue;
2498                         }
2499
2500                         mSettings.enableSystemPackageLPw(packageName);
2501
2502                         try {
2503                             scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2504                         } catch (PackageManagerException e) {
2505                             Slog.e(TAG, "Failed to parse original system package: "
2506                                     + e.getMessage());
2507                         }
2508                     }
2509                 }
2510             }
2511             mExpectingBetter.clear();
2512
2513             // Resolve the storage manager.
2514             mStorageManagerPackage = getStorageManagerPackageName();
2515
2516             // Resolve protected action filters. Only the setup wizard is allowed to
2517             // have a high priority filter for these actions.
2518             mSetupWizardPackage = getSetupWizardPackageName();
2519             if (mProtectedFilters.size() > 0) {
2520                 if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2521                     Slog.i(TAG, "No setup wizard;"
2522                         + " All protected intents capped to priority 0");
2523                 }
2524                 for (ActivityIntentInfo filter : mProtectedFilters) {
2525                     if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2526                         if (DEBUG_FILTERS) {
2527                             Slog.i(TAG, "Found setup wizard;"
2528                                 + " allow priority " + filter.getPriority() + ";"
2529                                 + " package: " + filter.activity.info.packageName
2530                                 + " activity: " + filter.activity.className
2531                                 + " priority: " + filter.getPriority());
2532                         }
2533                         // skip setup wizard; allow it to keep the high priority filter
2534                         continue;
2535                     }
2536                     Slog.w(TAG, "Protected action; cap priority to 0;"
2537                             + " package: " + filter.activity.info.packageName
2538                             + " activity: " + filter.activity.className
2539                             + " origPrio: " + filter.getPriority());
2540                     filter.setPriority(0);
2541                 }
2542             }
2543             mDeferProtectedFilters = false;
2544             mProtectedFilters.clear();
2545
2546             // Now that we know all of the shared libraries, update all clients to have
2547             // the correct library paths.
2548             updateAllSharedLibrariesLPw();
2549
2550             for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2551                 // NOTE: We ignore potential failures here during a system scan (like
2552                 // the rest of the commands above) because there's precious little we
2553                 // can do about it. A settings error is reported, though.
2554                 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2555                         false /* boot complete */);
2556             }
2557
2558             // Now that we know all the packages we are keeping,
2559             // read and update their last usage times.
2560             mPackageUsage.read(mPackages);
2561             mCompilerStats.read();
2562
2563             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2564                     SystemClock.uptimeMillis());
2565             Slog.i(TAG, "Time to scan packages: "
2566                     + ((SystemClock.uptimeMillis()-startTime)/1000f)
2567                     + " seconds");
2568
2569             // If the platform SDK has changed since the last time we booted,
2570             // we need to re-grant app permission to catch any new ones that
2571             // appear.  This is really a hack, and means that apps can in some
2572             // cases get permissions that the user didn't initially explicitly
2573             // allow...  it would be nice to have some better way to handle
2574             // this situation.
2575             int updateFlags = UPDATE_PERMISSIONS_ALL;
2576             if (ver.sdkVersion != mSdkVersion) {
2577                 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2578                         + mSdkVersion + "; regranting permissions for internal storage");
2579                 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2580             }
2581             updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2582             ver.sdkVersion = mSdkVersion;
2583
2584             // If this is the first boot or an update from pre-M, and it is a normal
2585             // boot, then we need to initialize the default preferred apps across
2586             // all defined users.
2587             if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2588                 for (UserInfo user : sUserManager.getUsers(true)) {
2589                     mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2590                     applyFactoryDefaultBrowserLPw(user.id);
2591                     primeDomainVerificationsLPw(user.id);
2592                 }
2593             }
2594
2595             // Prepare storage for system user really early during boot,
2596             // since core system apps like SettingsProvider and SystemUI
2597             // can't wait for user to start
2598             final int storageFlags;
2599             if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2600                 storageFlags = StorageManager.FLAG_STORAGE_DE;
2601             } else {
2602                 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2603             }
2604             reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2605                     storageFlags);
2606
2607             // If this is first boot after an OTA, and a normal boot, then
2608             // we need to clear code cache directories.
2609             // Note that we do *not* clear the application profiles. These remain valid
2610             // across OTAs and are used to drive profile verification (post OTA) and
2611             // profile compilation (without waiting to collect a fresh set of profiles).
2612             if (mIsUpgrade && !onlyCore) {
2613                 Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2614                 for (int i = 0; i < mSettings.mPackages.size(); i++) {
2615                     final PackageSetting ps = mSettings.mPackages.valueAt(i);
2616                     if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2617                         // No apps are running this early, so no need to freeze
2618                         clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2619                                 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2620                                         | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2621                     }
2622                 }
2623                 ver.fingerprint = Build.FINGERPRINT;
2624             }
2625
2626             checkDefaultBrowser();
2627
2628             // clear only after permissions and other defaults have been updated
2629             mExistingSystemPackages.clear();
2630             mPromoteSystemApps = false;
2631
2632             // All the changes are done during package scanning.
2633             ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2634
2635             // can downgrade to reader
2636             mSettings.writeLPr();
2637
2638             // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2639             // early on (before the package manager declares itself as early) because other
2640             // components in the system server might ask for package contexts for these apps.
2641             //
2642             // Note that "onlyCore" in this context means the system is encrypted or encrypting
2643             // (i.e, that the data partition is unavailable).
2644             if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2645                 long start = System.nanoTime();
2646                 List<PackageParser.Package> coreApps = new ArrayList<>();
2647                 for (PackageParser.Package pkg : mPackages.values()) {
2648                     if (pkg.coreApp) {
2649                         coreApps.add(pkg);
2650                     }
2651                 }
2652
2653                 int[] stats = performDexOptUpgrade(coreApps, false,
2654                         getCompilerFilterForReason(REASON_CORE_APP));
2655
2656                 final int elapsedTimeSeconds =
2657                         (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2658                 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2659
2660                 if (DEBUG_DEXOPT) {
2661                     Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2662                             stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2663                 }
2664
2665
2666                 // TODO: Should we log these stats to tron too ?
2667                 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2668                 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2669                 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2670                 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2671             }
2672
2673             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2674                     SystemClock.uptimeMillis());
2675
2676             if (!mOnlyCore) {
2677                 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2678                 mRequiredInstallerPackage = getRequiredInstallerLPr();
2679                 mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2680                 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2681                 mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2682                         mIntentFilterVerifierComponent);
2683                 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2684                         PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2685                 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2686                         PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2687             } else {
2688                 mRequiredVerifierPackage = null;
2689                 mRequiredInstallerPackage = null;
2690                 mRequiredUninstallerPackage = null;
2691                 mIntentFilterVerifierComponent = null;
2692                 mIntentFilterVerifier = null;
2693                 mServicesSystemSharedLibraryPackageName = null;
2694                 mSharedSystemSharedLibraryPackageName = null;
2695             }
2696
2697             mInstallerService = new PackageInstallerService(context, this);
2698
2699             final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2700             final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2701             // both the installer and resolver must be present to enable ephemeral
2702             if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2703                 if (DEBUG_EPHEMERAL) {
2704                     Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2705                             + " installer:" + ephemeralInstallerComponent);
2706                 }
2707                 mEphemeralResolverComponent = ephemeralResolverComponent;
2708                 mEphemeralInstallerComponent = ephemeralInstallerComponent;
2709                 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2710                 mEphemeralResolverConnection =
2711                         new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2712             } else {
2713                 if (DEBUG_EPHEMERAL) {
2714                     final String missingComponent =
2715                             (ephemeralResolverComponent == null)
2716                             ? (ephemeralInstallerComponent == null)
2717                                     ? "resolver and installer"
2718                                     : "resolver"
2719                             : "installer";
2720                     Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2721                 }
2722                 mEphemeralResolverComponent = null;
2723                 mEphemeralInstallerComponent = null;
2724                 mEphemeralResolverConnection = null;
2725             }
2726
2727             mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2728         } // synchronized (mPackages)
2729         } // synchronized (mInstallLock)
2730
2731         // Now after opening every single application zip, make sure they
2732         // are all flushed.  Not really needed, but keeps things nice and
2733         // tidy.
2734         Runtime.getRuntime().gc();
2735
2736         // The initial scanning above does many calls into installd while
2737         // holding the mPackages lock, but we're mostly interested in yelling
2738         // once we have a booted system.
2739         mInstaller.setWarnIfHeld(mPackages);
2740
2741         // Expose private service for system components to use.
2742         LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2743     }
2744
2745     @Override
2746     public boolean isFirstBoot() {
2747         return mFirstBoot;
2748     }
2749
2750     @Override
2751     public boolean isOnlyCoreApps() {
2752         return mOnlyCore;
2753     }
2754
2755     @Override
2756     public boolean isUpgrade() {
2757         return mIsUpgrade;
2758     }
2759
2760     private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2761         final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2762
2763         final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2764                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2765                 UserHandle.USER_SYSTEM);
2766         if (matches.size() == 1) {
2767             return matches.get(0).getComponentInfo().packageName;
2768         } else if (matches.size() == 0) {
2769             Log.e(TAG, "There should probably be a verifier, but, none were found");
2770             return null;
2771         }
2772         throw new RuntimeException("There must be exactly one verifier; found " + matches);
2773     }
2774
2775     private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2776         synchronized (mPackages) {
2777             SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2778             if (libraryEntry == null) {
2779                 throw new IllegalStateException("Missing required shared library:" + libraryName);
2780             }
2781             return libraryEntry.apk;
2782         }
2783     }
2784
2785     private @NonNull String getRequiredInstallerLPr() {
2786         final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2787         intent.addCategory(Intent.CATEGORY_DEFAULT);
2788         intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2789
2790         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2791                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2792                 UserHandle.USER_SYSTEM);
2793         if (matches.size() == 1) {
2794             ResolveInfo resolveInfo = matches.get(0);
2795             if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2796                 throw new RuntimeException("The installer must be a privileged app");
2797             }
2798             return matches.get(0).getComponentInfo().packageName;
2799         } else {
2800             throw new RuntimeException("There must be exactly one installer; found " + matches);
2801         }
2802     }
2803
2804     private @NonNull String getRequiredUninstallerLPr() {
2805         final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2806         intent.addCategory(Intent.CATEGORY_DEFAULT);
2807         intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2808
2809         final ResolveInfo resolveInfo = resolveIntent(intent, null,
2810                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2811                 UserHandle.USER_SYSTEM);
2812         if (resolveInfo == null ||
2813                 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2814             throw new RuntimeException("There must be exactly one uninstaller; found "
2815                     + resolveInfo);
2816         }
2817         return resolveInfo.getComponentInfo().packageName;
2818     }
2819
2820     private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2821         final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2822
2823         final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2824                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2825                 UserHandle.USER_SYSTEM);
2826         ResolveInfo best = null;
2827         final int N = matches.size();
2828         for (int i = 0; i < N; i++) {
2829             final ResolveInfo cur = matches.get(i);
2830             final String packageName = cur.getComponentInfo().packageName;
2831             if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2832                     packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2833                 continue;
2834             }
2835
2836             if (best == null || cur.priority > best.priority) {
2837                 best = cur;
2838             }
2839         }
2840
2841         if (best != null) {
2842             return best.getComponentInfo().getComponentName();
2843         } else {
2844             throw new RuntimeException("There must be at least one intent filter verifier");
2845         }
2846     }
2847
2848     private @Nullable ComponentName getEphemeralResolverLPr() {
2849         final String[] packageArray =
2850                 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2851         if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2852             if (DEBUG_EPHEMERAL) {
2853                 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2854             }
2855             return null;
2856         }
2857
2858         final int resolveFlags =
2859                 MATCH_DIRECT_BOOT_AWARE
2860                 | MATCH_DIRECT_BOOT_UNAWARE
2861                 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2862         final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2863         final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2864                 resolveFlags, UserHandle.USER_SYSTEM);
2865
2866         final int N = resolvers.size();
2867         if (N == 0) {
2868             if (DEBUG_EPHEMERAL) {
2869                 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2870             }
2871             return null;
2872         }
2873
2874         final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2875         for (int i = 0; i < N; i++) {
2876             final ResolveInfo info = resolvers.get(i);
2877
2878             if (info.serviceInfo == null) {
2879                 continue;
2880             }
2881
2882             final String packageName = info.serviceInfo.packageName;
2883             if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2884                 if (DEBUG_EPHEMERAL) {
2885                     Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2886                             + " pkg: " + packageName + ", info:" + info);
2887                 }
2888                 continue;
2889             }
2890
2891             if (DEBUG_EPHEMERAL) {
2892                 Slog.v(TAG, "Ephemeral resolver found;"
2893                         + " pkg: " + packageName + ", info:" + info);
2894             }
2895             return new ComponentName(packageName, info.serviceInfo.name);
2896         }
2897         if (DEBUG_EPHEMERAL) {
2898             Slog.v(TAG, "Ephemeral resolver NOT found");
2899         }
2900         return null;
2901     }
2902
2903     private @Nullable ComponentName getEphemeralInstallerLPr() {
2904         final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2905         intent.addCategory(Intent.CATEGORY_DEFAULT);
2906         intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2907
2908         final int resolveFlags =
2909                 MATCH_DIRECT_BOOT_AWARE
2910                 | MATCH_DIRECT_BOOT_UNAWARE
2911                 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2912         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2913                 resolveFlags, UserHandle.USER_SYSTEM);
2914         if (matches.size() == 0) {
2915             return null;
2916         } else if (matches.size() == 1) {
2917             return matches.get(0).getComponentInfo().getComponentName();
2918         } else {
2919             throw new RuntimeException(
2920                     "There must be at most one ephemeral installer; found " + matches);
2921         }
2922     }
2923
2924     private void primeDomainVerificationsLPw(int userId) {
2925         if (DEBUG_DOMAIN_VERIFICATION) {
2926             Slog.d(TAG, "Priming domain verifications in user " + userId);
2927         }
2928
2929         SystemConfig systemConfig = SystemConfig.getInstance();
2930         ArraySet<String> packages = systemConfig.getLinkedApps();
2931         ArraySet<String> domains = new ArraySet<String>();
2932
2933         for (String packageName : packages) {
2934             PackageParser.Package pkg = mPackages.get(packageName);
2935             if (pkg != null) {
2936                 if (!pkg.isSystemApp()) {
2937                     Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2938                     continue;
2939                 }
2940
2941                 domains.clear();
2942                 for (PackageParser.Activity a : pkg.activities) {
2943                     for (ActivityIntentInfo filter : a.intents) {
2944                         if (hasValidDomains(filter)) {
2945                             domains.addAll(filter.getHostsList());
2946                         }
2947                     }
2948                 }
2949
2950                 if (domains.size() > 0) {
2951                     if (DEBUG_DOMAIN_VERIFICATION) {
2952                         Slog.v(TAG, "      + " + packageName);
2953                     }
2954                     // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2955                     // state w.r.t. the formal app-linkage "no verification attempted" state;
2956                     // and then 'always' in the per-user state actually used for intent resolution.
2957                     final IntentFilterVerificationInfo ivi;
2958                     ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2959                             new ArrayList<String>(domains));
2960                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2961                     mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2962                             INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2963                 } else {
2964                     Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2965                             + "' does not handle web links");
2966                 }
2967             } else {
2968                 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2969             }
2970         }
2971
2972         scheduleWritePackageRestrictionsLocked(userId);
2973         scheduleWriteSettingsLocked();
2974     }
2975
2976     private void applyFactoryDefaultBrowserLPw(int userId) {
2977         // The default browser app's package name is stored in a string resource,
2978         // with a product-specific overlay used for vendor customization.
2979         String browserPkg = mContext.getResources().getString(
2980                 com.android.internal.R.string.default_browser);
2981         if (!TextUtils.isEmpty(browserPkg)) {
2982             // non-empty string => required to be a known package
2983             PackageSetting ps = mSettings.mPackages.get(browserPkg);
2984             if (ps == null) {
2985                 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2986                 browserPkg = null;
2987             } else {
2988                 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2989             }
2990         }
2991
2992         // Nothing valid explicitly set? Make the factory-installed browser the explicit
2993         // default.  If there's more than one, just leave everything alone.
2994         if (browserPkg == null) {
2995             calculateDefaultBrowserLPw(userId);
2996         }
2997     }
2998
2999     private void calculateDefaultBrowserLPw(int userId) {
3000         List<String> allBrowsers = resolveAllBrowserApps(userId);
3001         final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3002         mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3003     }
3004
3005     private List<String> resolveAllBrowserApps(int userId) {
3006         // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3007         List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3008                 PackageManager.MATCH_ALL, userId);
3009
3010         final int count = list.size();
3011         List<String> result = new ArrayList<String>(count);
3012         for (int i=0; i<count; i++) {
3013             ResolveInfo info = list.get(i);
3014             if (info.activityInfo == null
3015                     || !info.handleAllWebDataURI
3016                     || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3017                     || result.contains(info.activityInfo.packageName)) {
3018                 continue;
3019             }
3020             result.add(info.activityInfo.packageName);
3021         }
3022
3023         return result;
3024     }
3025
3026     private boolean packageIsBrowser(String packageName, int userId) {
3027         List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3028                 PackageManager.MATCH_ALL, userId);
3029         final int N = list.size();
3030         for (int i = 0; i < N; i++) {
3031             ResolveInfo info = list.get(i);
3032             if (packageName.equals(info.activityInfo.packageName)) {
3033                 return true;
3034             }
3035         }
3036         return false;
3037     }
3038
3039     private void checkDefaultBrowser() {
3040         final int myUserId = UserHandle.myUserId();
3041         final String packageName = getDefaultBrowserPackageName(myUserId);
3042         if (packageName != null) {
3043             PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3044             if (info == null) {
3045                 Slog.w(TAG, "Default browser no longer installed: " + packageName);
3046                 synchronized (mPackages) {
3047                     applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3048                 }
3049             }
3050         }
3051     }
3052
3053     @Override
3054     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3055             throws RemoteException {
3056         try {
3057             return super.onTransact(code, data, reply, flags);
3058         } catch (RuntimeException e) {
3059             if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3060                 Slog.wtf(TAG, "Package Manager Crash", e);
3061             }
3062             throw e;
3063         }
3064     }
3065
3066     static int[] appendInts(int[] cur, int[] add) {
3067         if (add == null) return cur;
3068         if (cur == null) return add;
3069         final int N = add.length;
3070         for (int i=0; i<N; i++) {
3071             cur = appendInt(cur, add[i]);
3072         }
3073         return cur;
3074     }
3075
3076     private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3077         if (!sUserManager.exists(userId)) return null;
3078         if (ps == null) {
3079             return null;
3080         }
3081         final PackageParser.Package p = ps.pkg;
3082         if (p == null) {
3083             return null;
3084         }
3085
3086         final PermissionsState permissionsState = ps.getPermissionsState();
3087
3088         // Compute GIDs only if requested
3089         final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3090                 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3091         // Compute granted permissions only if package has requested permissions
3092         final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3093                 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3094         final PackageUserState state = ps.readUserState(userId);
3095
3096         return PackageParser.generatePackageInfo(p, gids, flags,
3097                 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3098     }
3099
3100     @Override
3101     public void checkPackageStartable(String packageName, int userId) {
3102         final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3103
3104         synchronized (mPackages) {
3105             final PackageSetting ps = mSettings.mPackages.get(packageName);
3106             if (ps == null) {
3107                 throw new SecurityException("Package " + packageName + " was not found!");
3108             }
3109
3110             if (!ps.getInstalled(userId)) {
3111                 throw new SecurityException(
3112                         "Package " + packageName + " was not installed for user " + userId + "!");
3113             }
3114
3115             if (mSafeMode && !ps.isSystem()) {
3116                 throw new SecurityException("Package " + packageName + " not a system app!");
3117             }
3118
3119             if (mFrozenPackages.contains(packageName)) {
3120                 throw new SecurityException("Package " + packageName + " is currently frozen!");
3121             }
3122
3123             if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3124                     || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3125                 throw new SecurityException("Package " + packageName + " is not encryption aware!");
3126             }
3127         }
3128     }
3129
3130     @Override
3131     public boolean isPackageAvailable(String packageName, int userId) {
3132         if (!sUserManager.exists(userId)) return false;
3133         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3134                 false /* requireFullPermission */, false /* checkShell */, "is package available");
3135         synchronized (mPackages) {
3136             PackageParser.Package p = mPackages.get(packageName);
3137             if (p != null) {
3138                 final PackageSetting ps = (PackageSetting) p.mExtras;
3139                 if (ps != null) {
3140                     final PackageUserState state = ps.readUserState(userId);
3141                     if (state != null) {
3142                         return PackageParser.isAvailable(state);
3143                     }
3144                 }
3145             }
3146         }
3147         return false;
3148     }
3149
3150     @Override
3151     public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3152         if (!sUserManager.exists(userId)) return null;
3153         flags = updateFlagsForPackage(flags, userId, packageName);
3154         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3155                 false /* requireFullPermission */, false /* checkShell */, "get package info");
3156
3157         // reader
3158         synchronized (mPackages) {
3159             // Normalize package name to hanlde renamed packages
3160             packageName = normalizePackageNameLPr(packageName);
3161
3162             final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3163             PackageParser.Package p = null;
3164             if (matchFactoryOnly) {
3165                 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3166                 if (ps != null) {
3167                     return generatePackageInfo(ps, flags, userId);
3168                 }
3169             }
3170             if (p == null) {
3171                 p = mPackages.get(packageName);
3172                 if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3173                     return null;
3174                 }
3175             }
3176             if (DEBUG_PACKAGE_INFO)
3177                 Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3178             if (p != null) {
3179                 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3180             }
3181             if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3182                 final PackageSetting ps = mSettings.mPackages.get(packageName);
3183                 return generatePackageInfo(ps, flags, userId);
3184             }
3185         }
3186         return null;
3187     }
3188
3189     @Override
3190     public String[] currentToCanonicalPackageNames(String[] names) {
3191         String[] out = new String[names.length];
3192         // reader
3193         synchronized (mPackages) {
3194             for (int i=names.length-1; i>=0; i--) {
3195                 PackageSetting ps = mSettings.mPackages.get(names[i]);
3196                 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3197             }
3198         }
3199         return out;
3200     }
3201
3202     @Override
3203     public String[] canonicalToCurrentPackageNames(String[] names) {
3204         String[] out = new String[names.length];
3205         // reader
3206         synchronized (mPackages) {
3207             for (int i=names.length-1; i>=0; i--) {
3208                 String cur = mSettings.mRenamedPackages.get(names[i]);
3209                 out[i] = cur != null ? cur : names[i];
3210             }
3211         }
3212         return out;
3213     }
3214
3215     @Override
3216     public int getPackageUid(String packageName, int flags, int userId) {
3217         if (!sUserManager.exists(userId)) return -1;
3218         flags = updateFlagsForPackage(flags, userId, packageName);
3219         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3220                 false /* requireFullPermission */, false /* checkShell */, "get package uid");
3221
3222         // reader
3223         synchronized (mPackages) {
3224             final PackageParser.Package p = mPackages.get(packageName);
3225             if (p != null && p.isMatch(flags)) {
3226                 return UserHandle.getUid(userId, p.applicationInfo.uid);
3227             }
3228             if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3229                 final PackageSetting ps = mSettings.mPackages.get(packageName);
3230                 if (ps != null && ps.isMatch(flags)) {
3231                     return UserHandle.getUid(userId, ps.appId);
3232                 }
3233             }
3234         }
3235
3236         return -1;
3237     }
3238
3239     @Override
3240     public int[] getPackageGids(String packageName, int flags, int userId) {
3241         if (!sUserManager.exists(userId)) return null;
3242         flags = updateFlagsForPackage(flags, userId, packageName);
3243         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3244                 false /* requireFullPermission */, false /* checkShell */,
3245                 "getPackageGids");
3246
3247         // reader
3248         synchronized (mPackages) {
3249             final PackageParser.Package p = mPackages.get(packageName);
3250             if (p != null && p.isMatch(flags)) {
3251                 PackageSetting ps = (PackageSetting) p.mExtras;
3252                 return ps.getPermissionsState().computeGids(userId);
3253             }
3254             if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3255                 final PackageSetting ps = mSettings.mPackages.get(packageName);
3256                 if (ps != null && ps.isMatch(flags)) {
3257                     return ps.getPermissionsState().computeGids(userId);
3258                 }
3259             }
3260         }
3261
3262         return null;
3263     }
3264
3265     static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3266         if (bp.perm != null) {
3267             return PackageParser.generatePermissionInfo(bp.perm, flags);
3268         }
3269         PermissionInfo pi = new PermissionInfo();
3270         pi.name = bp.name;
3271         pi.packageName = bp.sourcePackage;
3272         pi.nonLocalizedLabel = bp.name;
3273         pi.protectionLevel = bp.protectionLevel;
3274         return pi;
3275     }
3276
3277     @Override
3278     public PermissionInfo getPermissionInfo(String name, int flags) {
3279         // reader
3280         synchronized (mPackages) {
3281             final BasePermission p = mSettings.mPermissions.get(name);
3282             if (p != null) {
3283                 return generatePermissionInfo(p, flags);
3284             }
3285             return null;
3286         }
3287     }
3288
3289     @Override
3290     public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3291             int flags) {
3292         // reader
3293         synchronized (mPackages) {
3294             if (group != null && !mPermissionGroups.containsKey(group)) {
3295                 // This is thrown as NameNotFoundException
3296                 return null;
3297             }
3298
3299             ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3300             for (BasePermission p : mSettings.mPermissions.values()) {
3301                 if (group == null) {
3302                     if (p.perm == null || p.perm.info.group == null) {
3303                         out.add(generatePermissionInfo(p, flags));
3304                     }
3305                 } else {
3306                     if (p.perm != null && group.equals(p.perm.info.group)) {
3307                         out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3308                     }
3309                 }
3310             }
3311             return new ParceledListSlice<>(out);
3312         }
3313     }
3314
3315     @Override
3316     public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3317         // reader
3318         synchronized (mPackages) {
3319             return PackageParser.generatePermissionGroupInfo(
3320                     mPermissionGroups.get(name), flags);
3321         }
3322     }
3323
3324     @Override
3325     public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3326         // reader
3327         synchronized (mPackages) {
3328             final int N = mPermissionGroups.size();
3329             ArrayList<PermissionGroupInfo> out
3330                     = new ArrayList<PermissionGroupInfo>(N);
3331             for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3332                 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3333             }
3334             return new ParceledListSlice<>(out);
3335         }
3336     }
3337
3338     private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3339             int userId) {
3340         if (!sUserManager.exists(userId)) return null;
3341         PackageSetting ps = mSettings.mPackages.get(packageName);
3342         if (ps != null) {
3343             if (ps.pkg == null) {
3344                 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3345                 if (pInfo != null) {
3346                     return pInfo.applicationInfo;
3347                 }
3348                 return null;
3349             }
3350             return PackageParser.generateApplicationInfo(ps.pkg, flags,
3351                     ps.readUserState(userId), userId);
3352         }
3353         return null;
3354     }
3355
3356     @Override
3357     public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3358         if (!sUserManager.exists(userId)) return null;
3359         flags = updateFlagsForApplication(flags, userId, packageName);
3360         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3361                 false /* requireFullPermission */, false /* checkShell */, "get application info");
3362
3363         // writer
3364         synchronized (mPackages) {
3365             // Normalize package name to hanlde renamed packages
3366             packageName = normalizePackageNameLPr(packageName);
3367
3368             PackageParser.Package p = mPackages.get(packageName);
3369             if (DEBUG_PACKAGE_INFO) Log.v(
3370                     TAG, "getApplicationInfo " + packageName
3371                     + ": " + p);
3372             if (p != null) {
3373                 PackageSetting ps = mSettings.mPackages.get(packageName);
3374                 if (ps == null) return null;
3375                 // Note: isEnabledLP() does not apply here - always return info
3376                 return PackageParser.generateApplicationInfo(
3377                         p, flags, ps.readUserState(userId), userId);
3378             }
3379             if ("android".equals(packageName)||"system".equals(packageName)) {
3380                 return mAndroidApplication;
3381             }
3382             if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3383                 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3384             }
3385         }
3386         return null;
3387     }
3388
3389     private String normalizePackageNameLPr(String packageName) {
3390         String normalizedPackageName = mSettings.mRenamedPackages.get(packageName);
3391         return normalizedPackageName != null ? normalizedPackageName : packageName;
3392     }
3393
3394     @Override
3395     public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3396             final IPackageDataObserver observer) {
3397         mContext.enforceCallingOrSelfPermission(
3398                 android.Manifest.permission.CLEAR_APP_CACHE, null);
3399         // Queue up an async operation since clearing cache may take a little while.
3400         mHandler.post(new Runnable() {
3401             public void run() {
3402                 mHandler.removeCallbacks(this);
3403                 boolean success = true;
3404                 synchronized (mInstallLock) {
3405                     try {
3406                         mInstaller.freeCache(volumeUuid, freeStorageSize);
3407                     } catch (InstallerException e) {
3408                         Slog.w(TAG, "Couldn't clear application caches: " + e);
3409                         success = false;
3410                     }
3411                 }
3412                 if (observer != null) {
3413                     try {
3414                         observer.onRemoveCompleted(null, success);
3415                     } catch (RemoteException e) {
3416                         Slog.w(TAG, "RemoveException when invoking call back");
3417                     }
3418                 }
3419             }
3420         });
3421     }
3422
3423     @Override
3424     public void freeStorage(final String volumeUuid, final long freeStorageSize,
3425             final IntentSender pi) {
3426         mContext.enforceCallingOrSelfPermission(
3427                 android.Manifest.permission.CLEAR_APP_CACHE, null);
3428         // Queue up an async operation since clearing cache may take a little while.
3429         mHandler.post(new Runnable() {
3430             public void run() {
3431                 mHandler.removeCallbacks(this);
3432                 boolean success = true;
3433                 synchronized (mInstallLock) {
3434                     try {
3435                         mInstaller.freeCache(volumeUuid, freeStorageSize);
3436                     } catch (InstallerException e) {
3437                         Slog.w(TAG, "Couldn't clear application caches: " + e);
3438                         success = false;
3439                     }
3440                 }
3441                 if(pi != null) {
3442                     try {
3443                         // Callback via pending intent
3444                         int code = success ? 1 : 0;
3445                         pi.sendIntent(null, code, null,
3446                                 null, null);
3447                     } catch (SendIntentException e1) {
3448                         Slog.i(TAG, "Failed to send pending intent");
3449                     }
3450                 }
3451             }
3452         });
3453     }
3454
3455     void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3456         synchronized (mInstallLock) {
3457             try {
3458                 mInstaller.freeCache(volumeUuid, freeStorageSize);
3459             } catch (InstallerException e) {
3460                 throw new IOException("Failed to free enough space", e);
3461             }
3462         }
3463     }
3464
3465     /**
3466      * Update given flags based on encryption status of current user.
3467      */
3468     private int updateFlags(int flags, int userId) {
3469         if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3470                 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3471             // Caller expressed an explicit opinion about what encryption
3472             // aware/unaware components they want to see, so fall through and
3473             // give them what they want
3474         } else {
3475             // Caller expressed no opinion, so match based on user state
3476             if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3477                 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3478             } else {
3479                 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3480             }
3481         }
3482         return flags;
3483     }
3484
3485     private UserManagerInternal getUserManagerInternal() {
3486         if (mUserManagerInternal == null) {
3487             mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3488         }
3489         return mUserManagerInternal;
3490     }
3491
3492     /**
3493      * Update given flags when being used to request {@link PackageInfo}.
3494      */
3495     private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3496         boolean triaged = true;
3497         if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3498                 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3499             // Caller is asking for component details, so they'd better be
3500             // asking for specific encryption matching behavior, or be triaged
3501             if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3502                     | PackageManager.MATCH_DIRECT_BOOT_AWARE
3503                     | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3504                 triaged = false;
3505             }
3506         }
3507         if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3508                 | PackageManager.MATCH_SYSTEM_ONLY
3509                 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3510             triaged = false;
3511         }
3512         if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3513             Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3514                     + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3515         }
3516         return updateFlags(flags, userId);
3517     }
3518
3519     /**
3520      * Update given flags when being used to request {@link ApplicationInfo}.
3521      */
3522     private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3523         return updateFlagsForPackage(flags, userId, cookie);
3524     }
3525
3526     /**
3527      * Update given flags when being used to request {@link ComponentInfo}.
3528      */
3529     private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3530         if (cookie instanceof Intent) {
3531             if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3532                 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3533             }
3534         }
3535
3536         boolean triaged = true;
3537         // Caller is asking for component details, so they'd better be
3538         // asking for specific encryption matching behavior, or be triaged
3539         if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3540                 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3541                 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3542             triaged = false;
3543         }
3544         if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3545             Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3546                     + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3547         }
3548
3549         return updateFlags(flags, userId);
3550     }
3551
3552     /**
3553      * Update given flags when being used to request {@link ResolveInfo}.
3554      */
3555     int updateFlagsForResolve(int flags, int userId, Object cookie) {
3556         // Safe mode means we shouldn't match any third-party components
3557         if (mSafeMode) {
3558             flags |= PackageManager.MATCH_SYSTEM_ONLY;
3559         }
3560
3561         return updateFlagsForComponent(flags, userId, cookie);
3562     }
3563
3564     @Override
3565     public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3566         if (!sUserManager.exists(userId)) return null;
3567         flags = updateFlagsForComponent(flags, userId, component);
3568         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3569                 false /* requireFullPermission */, false /* checkShell */, "get activity info");
3570         synchronized (mPackages) {
3571             PackageParser.Activity a = mActivities.mActivities.get(component);
3572
3573             if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3574             if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3575                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3576                 if (ps == null) return null;
3577                 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3578                         userId);
3579             }
3580             if (mResolveComponentName.equals(component)) {
3581                 return PackageParser.generateActivityInfo(mResolveActivity, flags,
3582                         new PackageUserState(), userId);
3583             }
3584         }
3585         return null;
3586     }
3587
3588     @Override
3589     public boolean activitySupportsIntent(ComponentName component, Intent intent,
3590             String resolvedType) {
3591         synchronized (mPackages) {
3592             if (component.equals(mResolveComponentName)) {
3593                 // The resolver supports EVERYTHING!
3594                 return true;
3595             }
3596             PackageParser.Activity a = mActivities.mActivities.get(component);
3597             if (a == null) {
3598                 return false;
3599             }
3600             for (int i=0; i<a.intents.size(); i++) {
3601                 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3602                         intent.getData(), intent.getCategories(), TAG) >= 0) {
3603                     return true;
3604                 }
3605             }
3606             return false;
3607         }
3608     }
3609
3610     @Override
3611     public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3612         if (!sUserManager.exists(userId)) return null;
3613         flags = updateFlagsForComponent(flags, userId, component);
3614         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3615                 false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3616         synchronized (mPackages) {
3617             PackageParser.Activity a = mReceivers.mActivities.get(component);
3618             if (DEBUG_PACKAGE_INFO) Log.v(
3619                 TAG, "getReceiverInfo " + component + ": " + a);
3620             if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3621                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3622                 if (ps == null) return null;
3623                 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3624                         userId);
3625             }
3626         }
3627         return null;
3628     }
3629
3630     @Override
3631     public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3632         if (!sUserManager.exists(userId)) return null;
3633         flags = updateFlagsForComponent(flags, userId, component);
3634         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3635                 false /* requireFullPermission */, false /* checkShell */, "get service info");
3636         synchronized (mPackages) {
3637             PackageParser.Service s = mServices.mServices.get(component);
3638             if (DEBUG_PACKAGE_INFO) Log.v(
3639                 TAG, "getServiceInfo " + component + ": " + s);
3640             if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3641                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3642                 if (ps == null) return null;
3643                 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3644                         userId);
3645             }
3646         }
3647         return null;
3648     }
3649
3650     @Override
3651     public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3652         if (!sUserManager.exists(userId)) return null;
3653         flags = updateFlagsForComponent(flags, userId, component);
3654         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3655                 false /* requireFullPermission */, false /* checkShell */, "get provider info");
3656         synchronized (mPackages) {
3657             PackageParser.Provider p = mProviders.mProviders.get(component);
3658             if (DEBUG_PACKAGE_INFO) Log.v(
3659                 TAG, "getProviderInfo " + component + ": " + p);
3660             if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3661                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3662                 if (ps == null) return null;
3663                 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3664                         userId);
3665             }
3666         }
3667         return null;
3668     }
3669
3670     @Override
3671     public String[] getSystemSharedLibraryNames() {
3672         Set<String> libSet;
3673         synchronized (mPackages) {
3674             libSet = mSharedLibraries.keySet();
3675             int size = libSet.size();
3676             if (size > 0) {
3677                 String[] libs = new String[size];
3678                 libSet.toArray(libs);
3679                 return libs;
3680             }
3681         }
3682         return null;
3683     }
3684
3685     @Override
3686     public @NonNull String getServicesSystemSharedLibraryPackageName() {
3687         synchronized (mPackages) {
3688             return mServicesSystemSharedLibraryPackageName;
3689         }
3690     }
3691
3692     @Override
3693     public @NonNull String getSharedSystemSharedLibraryPackageName() {
3694         synchronized (mPackages) {
3695             return mSharedSystemSharedLibraryPackageName;
3696         }
3697     }
3698
3699     @Override
3700     public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3701         synchronized (mPackages) {
3702             final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3703
3704             final FeatureInfo fi = new FeatureInfo();
3705             fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3706                     FeatureInfo.GL_ES_VERSION_UNDEFINED);
3707             res.add(fi);
3708
3709             return new ParceledListSlice<>(res);
3710         }
3711     }
3712
3713     @Override
3714     public boolean hasSystemFeature(String name, int version) {
3715         synchronized (mPackages) {
3716             final FeatureInfo feat = mAvailableFeatures.get(name);
3717             if (feat == null) {
3718                 return false;
3719             } else {
3720                 return feat.version >= version;
3721             }
3722         }
3723     }
3724
3725     @Override
3726     public int checkPermission(String permName, String pkgName, int userId) {
3727         if (!sUserManager.exists(userId)) {
3728             return PackageManager.PERMISSION_DENIED;
3729         }
3730
3731         synchronized (mPackages) {
3732             final PackageParser.Package p = mPackages.get(pkgName);
3733             if (p != null && p.mExtras != null) {
3734                 final PackageSetting ps = (PackageSetting) p.mExtras;
3735                 final PermissionsState permissionsState = ps.getPermissionsState();
3736                 if (permissionsState.hasPermission(permName, userId)) {
3737                     return PackageManager.PERMISSION_GRANTED;
3738                 }
3739                 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3740                 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3741                         .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3742                     return PackageManager.PERMISSION_GRANTED;
3743                 }
3744             }
3745         }
3746
3747         return PackageManager.PERMISSION_DENIED;
3748     }
3749
3750     @Override
3751     public int checkUidPermission(String permName, int uid) {
3752         final int userId = UserHandle.getUserId(uid);
3753
3754         if (!sUserManager.exists(userId)) {
3755             return PackageManager.PERMISSION_DENIED;
3756         }
3757
3758         synchronized (mPackages) {
3759             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3760             if (obj != null) {
3761                 final SettingBase ps = (SettingBase) obj;
3762                 final PermissionsState permissionsState = ps.getPermissionsState();
3763                 if (permissionsState.hasPermission(permName, userId)) {
3764                     return PackageManager.PERMISSION_GRANTED;
3765                 }
3766                 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3767                 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3768                         .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3769                     return PackageManager.PERMISSION_GRANTED;
3770                 }
3771             } else {
3772                 ArraySet<String> perms = mSystemPermissions.get(uid);
3773                 if (perms != null) {
3774                     if (perms.contains(permName)) {
3775                         return PackageManager.PERMISSION_GRANTED;
3776                     }
3777                     if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3778                             .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3779                         return PackageManager.PERMISSION_GRANTED;
3780                     }
3781                 }
3782             }
3783         }
3784
3785         return PackageManager.PERMISSION_DENIED;
3786     }
3787
3788     @Override
3789     public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3790         if (UserHandle.getCallingUserId() != userId) {
3791             mContext.enforceCallingPermission(
3792                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3793                     "isPermissionRevokedByPolicy for user " + userId);
3794         }
3795
3796         if (checkPermission(permission, packageName, userId)
3797                 == PackageManager.PERMISSION_GRANTED) {
3798             return false;
3799         }
3800
3801         final long identity = Binder.clearCallingIdentity();
3802         try {
3803             final int flags = getPermissionFlags(permission, packageName, userId);
3804             return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3805         } finally {
3806             Binder.restoreCallingIdentity(identity);
3807         }
3808     }
3809
3810     @Override
3811     public String getPermissionControllerPackageName() {
3812         synchronized (mPackages) {
3813             return mRequiredInstallerPackage;
3814         }
3815     }
3816
3817     /**
3818      * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3819      * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3820      * @param checkShell whether to prevent shell from access if there's a debugging restriction
3821      * @param message the message to log on security exception
3822      */
3823     void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3824             boolean checkShell, String message) {
3825         if (userId < 0) {
3826             throw new IllegalArgumentException("Invalid userId " + userId);
3827         }
3828         if (checkShell) {
3829             enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3830         }
3831         if (userId == UserHandle.getUserId(callingUid)) return;
3832         if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3833             if (requireFullPermission) {
3834                 mContext.enforceCallingOrSelfPermission(
3835                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3836             } else {
3837                 try {
3838                     mContext.enforceCallingOrSelfPermission(
3839                             android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3840                 } catch (SecurityException se) {
3841                     mContext.enforceCallingOrSelfPermission(
3842                             android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3843                 }
3844             }
3845         }
3846     }
3847
3848     void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3849         if (callingUid == Process.SHELL_UID) {
3850             if (userHandle >= 0
3851                     && sUserManager.hasUserRestriction(restriction, userHandle)) {
3852                 throw new SecurityException("Shell does not have permission to access user "
3853                         + userHandle);
3854             } else if (userHandle < 0) {
3855                 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3856                         + Debug.getCallers(3));
3857             }
3858         }
3859     }
3860
3861     private BasePermission findPermissionTreeLP(String permName) {
3862         for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3863             if (permName.startsWith(bp.name) &&
3864                     permName.length() > bp.name.length() &&
3865                     permName.charAt(bp.name.length()) == '.') {
3866                 return bp;
3867             }
3868         }
3869         return null;
3870     }
3871
3872     private BasePermission checkPermissionTreeLP(String permName) {
3873         if (permName != null) {
3874             BasePermission bp = findPermissionTreeLP(permName);
3875             if (bp != null) {
3876                 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3877                     return bp;
3878                 }
3879                 throw new SecurityException("Calling uid "
3880                         + Binder.getCallingUid()
3881                         + " is not allowed to add to permission tree "
3882                         + bp.name + " owned by uid " + bp.uid);
3883             }
3884         }
3885         throw new SecurityException("No permission tree found for " + permName);
3886     }
3887
3888     static boolean compareStrings(CharSequence s1, CharSequence s2) {
3889         if (s1 == null) {
3890             return s2 == null;
3891         }
3892         if (s2 == null) {
3893             return false;
3894         }
3895         if (s1.getClass() != s2.getClass()) {
3896             return false;
3897         }
3898         return s1.equals(s2);
3899     }
3900
3901     static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3902         if (pi1.icon != pi2.icon) return false;
3903         if (pi1.logo != pi2.logo) return false;
3904         if (pi1.protectionLevel != pi2.protectionLevel) return false;
3905         if (!compareStrings(pi1.name, pi2.name)) return false;
3906         if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3907         // We'll take care of setting this one.
3908         if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3909         // These are not currently stored in settings.
3910         //if (!compareStrings(pi1.group, pi2.group)) return false;
3911         //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3912         //if (pi1.labelRes != pi2.labelRes) return false;
3913         //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3914         return true;
3915     }
3916
3917     int permissionInfoFootprint(PermissionInfo info) {
3918         int size = info.name.length();
3919         if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3920         if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3921         return size;
3922     }
3923
3924     int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3925         int size = 0;
3926         for (BasePermission perm : mSettings.mPermissions.values()) {
3927             if (perm.uid == tree.uid) {
3928                 size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3929             }
3930         }
3931         return size;
3932     }
3933
3934     void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3935         // We calculate the max size of permissions defined by this uid and throw
3936         // if that plus the size of 'info' would exceed our stated maximum.
3937         if (tree.uid != Process.SYSTEM_UID) {
3938             final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3939             if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3940                 throw new SecurityException("Permission tree size cap exceeded");
3941             }
3942         }
3943     }
3944
3945     boolean addPermissionLocked(PermissionInfo info, boolean async) {
3946         if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3947             throw new SecurityException("Label must be specified in permission");
3948         }
3949         BasePermission tree = checkPermissionTreeLP(info.name);
3950         BasePermission bp = mSettings.mPermissions.get(info.name);
3951         boolean added = bp == null;
3952         boolean changed = true;
3953         int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3954         if (added) {
3955             enforcePermissionCapLocked(info, tree);
3956             bp = new BasePermission(info.name, tree.sourcePackage,
3957                     BasePermission.TYPE_DYNAMIC);
3958         } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3959             throw new SecurityException(
3960                     "Not allowed to modify non-dynamic permission "
3961                     + info.name);
3962         } else {
3963             if (bp.protectionLevel == fixedLevel
3964                     && bp.perm.owner.equals(tree.perm.owner)
3965                     && bp.uid == tree.uid
3966                     && comparePermissionInfos(bp.perm.info, info)) {
3967                 changed = false;
3968             }
3969         }
3970         bp.protectionLevel = fixedLevel;
3971         info = new PermissionInfo(info);
3972         info.protectionLevel = fixedLevel;
3973         bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3974         bp.perm.info.packageName = tree.perm.info.packageName;
3975         bp.uid = tree.uid;
3976         if (added) {
3977             mSettings.mPermissions.put(info.name, bp);
3978         }
3979         if (changed) {
3980             if (!async) {
3981                 mSettings.writeLPr();
3982             } else {
3983                 scheduleWriteSettingsLocked();
3984             }
3985         }
3986         return added;
3987     }
3988
3989     @Override
3990     public boolean addPermission(PermissionInfo info) {
3991         synchronized (mPackages) {
3992             return addPermissionLocked(info, false);
3993         }
3994     }
3995
3996     @Override
3997     public boolean addPermissionAsync(PermissionInfo info) {
3998         synchronized (mPackages) {
3999             return addPermissionLocked(info, true);
4000         }
4001     }
4002
4003     @Override
4004     public void removePermission(String name) {
4005         synchronized (mPackages) {
4006             checkPermissionTreeLP(name);
4007             BasePermission bp = mSettings.mPermissions.get(name);
4008             if (bp != null) {
4009                 if (bp.type != BasePermission.TYPE_DYNAMIC) {
4010                     throw new SecurityException(
4011                             "Not allowed to modify non-dynamic permission "
4012                             + name);
4013                 }
4014                 mSettings.mPermissions.remove(name);
4015                 mSettings.writeLPr();
4016             }
4017         }
4018     }
4019
4020     private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4021             BasePermission bp) {
4022         int index = pkg.requestedPermissions.indexOf(bp.name);
4023         if (index == -1) {
4024             throw new SecurityException("Package " + pkg.packageName
4025                     + " has not requested permission " + bp.name);
4026         }
4027         if (!bp.isRuntime() && !bp.isDevelopment()) {
4028             throw new SecurityException("Permission " + bp.name
4029                     + " is not a changeable permission type");
4030         }
4031     }
4032
4033     @Override
4034     public void grantRuntimePermission(String packageName, String name, final int userId) {
4035         if (!sUserManager.exists(userId)) {
4036             Log.e(TAG, "No such user:" + userId);
4037             return;
4038         }
4039
4040         mContext.enforceCallingOrSelfPermission(
4041                 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4042                 "grantRuntimePermission");
4043
4044         enforceCrossUserPermission(Binder.getCallingUid(), userId,
4045                 true /* requireFullPermission */, true /* checkShell */,
4046                 "grantRuntimePermission");
4047
4048         final int uid;
4049         final SettingBase sb;
4050
4051         synchronized (mPackages) {
4052             final PackageParser.Package pkg = mPackages.get(packageName);
4053             if (pkg == null) {
4054                 throw new IllegalArgumentException("Unknown package: " + packageName);
4055             }
4056
4057             final BasePermission bp = mSettings.mPermissions.get(name);
4058             if (bp == null) {
4059                 throw new IllegalArgumentException("Unknown permission: " + name);
4060             }
4061
4062             enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4063
4064             // If a permission review is required for legacy apps we represent
4065             // their permissions as always granted runtime ones since we need
4066             // to keep the review required permission flag per user while an
4067             // install permission's state is shared across all users.
4068             if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
4069                     && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4070                     && bp.isRuntime()) {
4071                 return;
4072             }
4073
4074             uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4075             sb = (SettingBase) pkg.mExtras;
4076             if (sb == null) {
4077                 throw new IllegalArgumentException("Unknown package: " + packageName);
4078             }
4079
4080             final PermissionsState permissionsState = sb.getPermissionsState();
4081
4082             final int flags = permissionsState.getPermissionFlags(name, userId);
4083             if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4084                 throw new SecurityException("Cannot grant system fixed permission "
4085                         + name + " for package " + packageName);
4086             }
4087
4088             if (bp.isDevelopment()) {
4089                 // Development permissions must be handled specially, since they are not
4090                 // normal runtime permissions.  For now they apply to all users.
4091                 if (permissionsState.grantInstallPermission(bp) !=
4092                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
4093                     scheduleWriteSettingsLocked();
4094                 }
4095                 return;
4096             }
4097
4098             if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4099                 Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4100                 return;
4101             }
4102
4103             final int result = permissionsState.grantRuntimePermission(bp, userId);
4104             switch (result) {
4105                 case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4106                     return;
4107                 }
4108
4109                 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4110                     final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4111                     mHandler.post(new Runnable() {
4112                         @Override
4113                         public void run() {
4114                             killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4115                         }
4116                     });
4117                 }
4118                 break;
4119             }
4120
4121             mOnPermissionChangeListeners.onPermissionsChanged(uid);
4122
4123             // Not critical if that is lost - app has to request again.
4124             mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4125         }
4126
4127         // Only need to do this if user is initialized. Otherwise it's a new user
4128         // and there are no processes running as the user yet and there's no need
4129         // to make an expensive call to remount processes for the changed permissions.
4130         if (READ_EXTERNAL_STORAGE.equals(name)
4131                 || WRITE_EXTERNAL_STORAGE.equals(name)) {
4132             final long token = Binder.clearCallingIdentity();
4133             try {
4134                 if (sUserManager.isInitialized(userId)) {
4135                     MountServiceInternal mountServiceInternal = LocalServices.getService(
4136                             MountServiceInternal.class);
4137                     mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4138                 }
4139             } finally {
4140                 Binder.restoreCallingIdentity(token);
4141             }
4142         }
4143     }
4144
4145     @Override
4146     public void revokeRuntimePermission(String packageName, String name, int userId) {
4147         if (!sUserManager.exists(userId)) {
4148             Log.e(TAG, "No such user:" + userId);
4149             return;
4150         }
4151
4152         mContext.enforceCallingOrSelfPermission(
4153                 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4154                 "revokeRuntimePermission");
4155
4156         enforceCrossUserPermission(Binder.getCallingUid(), userId,
4157                 true /* requireFullPermission */, true /* checkShell */,
4158                 "revokeRuntimePermission");
4159
4160         final int appId;
4161
4162         synchronized (mPackages) {
4163             final PackageParser.Package pkg = mPackages.get(packageName);
4164             if (pkg == null) {
4165                 throw new IllegalArgumentException("Unknown package: " + packageName);
4166             }
4167
4168             final BasePermission bp = mSettings.mPermissions.get(name);
4169             if (bp == null) {
4170                 throw new IllegalArgumentException("Unknown permission: " + name);
4171             }
4172
4173             enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4174
4175             // If a permission review is required for legacy apps we represent
4176             // their permissions as always granted runtime ones since we need
4177             // to keep the review required permission flag per user while an
4178             // install permission's state is shared across all users.
4179             if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
4180                     && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4181                     && bp.isRuntime()) {
4182                 return;
4183             }
4184
4185             SettingBase sb = (SettingBase) pkg.mExtras;
4186             if (sb == null) {
4187                 throw new IllegalArgumentException("Unknown package: " + packageName);
4188             }
4189
4190             final PermissionsState permissionsState = sb.getPermissionsState();
4191
4192             final int flags = permissionsState.getPermissionFlags(name, userId);
4193             if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4194                 throw new SecurityException("Cannot revoke system fixed permission "
4195                         + name + " for package " + packageName);
4196             }
4197
4198             if (bp.isDevelopment()) {
4199                 // Development permissions must be handled specially, since they are not
4200                 // normal runtime permissions.  For now they apply to all users.
4201                 if (permissionsState.revokeInstallPermission(bp) !=
4202                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
4203                     scheduleWriteSettingsLocked();
4204                 }
4205                 return;
4206             }
4207
4208             if (permissionsState.revokeRuntimePermission(bp, userId) ==
4209                     PermissionsState.PERMISSION_OPERATION_FAILURE) {
4210                 return;
4211             }
4212
4213             mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4214
4215             // Critical, after this call app should never have the permission.
4216             mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4217
4218             appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4219         }
4220
4221         killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4222     }
4223
4224     @Override
4225     public void resetRuntimePermissions() {
4226         mContext.enforceCallingOrSelfPermission(
4227                 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4228                 "revokeRuntimePermission");
4229
4230         int callingUid = Binder.getCallingUid();
4231         if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4232             mContext.enforceCallingOrSelfPermission(
4233                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4234                     "resetRuntimePermissions");
4235         }
4236
4237         synchronized (mPackages) {
4238             updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4239             for (int userId : UserManagerService.getInstance().getUserIds()) {
4240                 final int packageCount = mPackages.size();
4241                 for (int i = 0; i < packageCount; i++) {
4242                     PackageParser.Package pkg = mPackages.valueAt(i);
4243                     if (!(pkg.mExtras instanceof PackageSetting)) {
4244                         continue;
4245                     }
4246                     PackageSetting ps = (PackageSetting) pkg.mExtras;
4247                     resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4248                 }
4249             }
4250         }
4251     }
4252
4253     @Override
4254     public int getPermissionFlags(String name, String packageName, int userId) {
4255         if (!sUserManager.exists(userId)) {
4256             return 0;
4257         }
4258
4259         enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4260
4261         enforceCrossUserPermission(Binder.getCallingUid(), userId,
4262                 true /* requireFullPermission */, false /* checkShell */,
4263                 "getPermissionFlags");
4264
4265         synchronized (mPackages) {
4266             final PackageParser.Package pkg = mPackages.get(packageName);
4267             if (pkg == null) {
4268                 return 0;
4269             }
4270
4271             final BasePermission bp = mSettings.mPermissions.get(name);
4272             if (bp == null) {
4273                 return 0;
4274             }
4275
4276             SettingBase sb = (SettingBase) pkg.mExtras;
4277             if (sb == null) {
4278                 return 0;
4279             }
4280
4281             PermissionsState permissionsState = sb.getPermissionsState();
4282             return permissionsState.getPermissionFlags(name, userId);
4283         }
4284     }
4285
4286     @Override
4287     public void updatePermissionFlags(String name, String packageName, int flagMask,
4288             int flagValues, int userId) {
4289         if (!sUserManager.exists(userId)) {
4290             return;
4291         }
4292
4293         enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4294
4295         enforceCrossUserPermission(Binder.getCallingUid(), userId,
4296                 true /* requireFullPermission */, true /* checkShell */,
4297                 "updatePermissionFlags");
4298
4299         // Only the system can change these flags and nothing else.
4300         if (getCallingUid() != Process.SYSTEM_UID) {
4301             flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4302             flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4303             flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4304             flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4305             flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4306         }
4307
4308         synchronized (mPackages) {
4309             final PackageParser.Package pkg = mPackages.get(packageName);
4310             if (pkg == null) {
4311                 throw new IllegalArgumentException("Unknown package: " + packageName);
4312             }
4313
4314             final BasePermission bp = mSettings.mPermissions.get(name);
4315             if (bp == null) {
4316                 throw new IllegalArgumentException("Unknown permission: " + name);
4317             }
4318
4319             SettingBase sb = (SettingBase) pkg.mExtras;
4320             if (sb == null) {
4321                 throw new IllegalArgumentException("Unknown package: " + packageName);
4322             }
4323
4324             PermissionsState permissionsState = sb.getPermissionsState();
4325
4326             boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4327
4328             if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4329                 // Install and runtime permissions are stored in different places,
4330                 // so figure out what permission changed and persist the change.
4331                 if (permissionsState.getInstallPermissionState(name) != null) {
4332                     scheduleWriteSettingsLocked();
4333                 } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4334                         || hadState) {
4335                     mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4336                 }
4337             }
4338         }
4339     }
4340
4341     /**
4342      * Update the permission flags for all packages and runtime permissions of a user in order
4343      * to allow device or profile owner to remove POLICY_FIXED.
4344      */
4345     @Override
4346     public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4347         if (!sUserManager.exists(userId)) {
4348             return;
4349         }
4350
4351         enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4352
4353         enforceCrossUserPermission(Binder.getCallingUid(), userId,
4354                 true /* requireFullPermission */, true /* checkShell */,
4355                 "updatePermissionFlagsForAllApps");
4356
4357         // Only the system can change system fixed flags.
4358         if (getCallingUid() != Process.SYSTEM_UID) {
4359             flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4360             flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4361         }
4362
4363         synchronized (mPackages) {
4364             boolean changed = false;
4365             final int packageCount = mPackages.size();
4366             for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4367                 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4368                 SettingBase sb = (SettingBase) pkg.mExtras;
4369                 if (sb == null) {
4370                     continue;
4371                 }
4372                 PermissionsState permissionsState = sb.getPermissionsState();
4373                 changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4374                         userId, flagMask, flagValues);
4375             }
4376             if (changed) {
4377                 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4378             }
4379         }
4380     }
4381
4382     private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4383         if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4384                 != PackageManager.PERMISSION_GRANTED
4385             && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4386                 != PackageManager.PERMISSION_GRANTED) {
4387             throw new SecurityException(message + " requires "
4388                     + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4389                     + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4390         }
4391     }
4392
4393     @Override
4394     public boolean shouldShowRequestPermissionRationale(String permissionName,
4395             String packageName, int userId) {
4396         if (UserHandle.getCallingUserId() != userId) {
4397             mContext.enforceCallingPermission(
4398                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4399                     "canShowRequestPermissionRationale for user " + userId);
4400         }
4401
4402         final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4403         if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4404             return false;
4405         }
4406
4407         if (checkPermission(permissionName, packageName, userId)
4408                 == PackageManager.PERMISSION_GRANTED) {
4409             return false;
4410         }
4411
4412         final int flags;
4413
4414         final long identity = Binder.clearCallingIdentity();
4415         try {
4416             flags = getPermissionFlags(permissionName,
4417                     packageName, userId);
4418         } finally {
4419             Binder.restoreCallingIdentity(identity);
4420         }
4421
4422         final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4423                 | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4424                 | PackageManager.FLAG_PERMISSION_USER_FIXED;
4425
4426         if ((flags & fixedFlags) != 0) {
4427             return false;
4428         }
4429
4430         return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4431     }
4432
4433     @Override
4434     public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4435         mContext.enforceCallingOrSelfPermission(
4436                 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4437                 "addOnPermissionsChangeListener");
4438
4439         synchronized (mPackages) {
4440             mOnPermissionChangeListeners.addListenerLocked(listener);
4441         }
4442     }
4443
4444     @Override
4445     public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4446         synchronized (mPackages) {
4447             mOnPermissionChangeListeners.removeListenerLocked(listener);
4448         }
4449     }
4450
4451     @Override
4452     public boolean isProtectedBroadcast(String actionName) {
4453         synchronized (mPackages) {
4454             if (mProtectedBroadcasts.contains(actionName)) {
4455                 return true;
4456             } else if (actionName != null) {
4457                 // TODO: remove these terrible hacks
4458                 if (actionName.startsWith("android.net.netmon.lingerExpired")
4459                         || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4460                         || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4461                         || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4462                     return true;
4463                 }
4464             }
4465         }
4466         return false;
4467     }
4468
4469     @Override
4470     public int checkSignatures(String pkg1, String pkg2) {
4471         synchronized (mPackages) {
4472             final PackageParser.Package p1 = mPackages.get(pkg1);
4473             final PackageParser.Package p2 = mPackages.get(pkg2);
4474             if (p1 == null || p1.mExtras == null
4475                     || p2 == null || p2.mExtras == null) {
4476                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4477             }
4478             return compareSignatures(p1.mSignatures, p2.mSignatures);
4479         }
4480     }
4481
4482     @Override
4483     public int checkUidSignatures(int uid1, int uid2) {
4484         // Map to base uids.
4485         uid1 = UserHandle.getAppId(uid1);
4486         uid2 = UserHandle.getAppId(uid2);
4487         // reader
4488         synchronized (mPackages) {
4489             Signature[] s1;
4490             Signature[] s2;
4491             Object obj = mSettings.getUserIdLPr(uid1);
4492             if (obj != null) {
4493                 if (obj instanceof SharedUserSetting) {
4494                     s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4495                 } else if (obj instanceof PackageSetting) {
4496                     s1 = ((PackageSetting)obj).signatures.mSignatures;
4497                 } else {
4498                     return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4499                 }
4500             } else {
4501                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4502             }
4503             obj = mSettings.getUserIdLPr(uid2);
4504             if (obj != null) {
4505                 if (obj instanceof SharedUserSetting) {
4506                     s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4507                 } else if (obj instanceof PackageSetting) {
4508                     s2 = ((PackageSetting)obj).signatures.mSignatures;
4509                 } else {
4510                     return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4511                 }
4512             } else {
4513                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4514             }
4515             return compareSignatures(s1, s2);
4516         }
4517     }
4518
4519     /**
4520      * This method should typically only be used when granting or revoking
4521      * permissions, since the app may immediately restart after this call.
4522      * <p>
4523      * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4524      * guard your work against the app being relaunched.
4525      */
4526     private void killUid(int appId, int userId, String reason) {
4527         final long identity = Binder.clearCallingIdentity();
4528         try {
4529             IActivityManager am = ActivityManagerNative.getDefault();
4530             if (am != null) {
4531                 try {
4532                     am.killUid(appId, userId, reason);
4533                 } catch (RemoteException e) {
4534                     /* ignore - same process */
4535                 }
4536             }
4537         } finally {
4538             Binder.restoreCallingIdentity(identity);
4539         }
4540     }
4541
4542     /**
4543      * Compares two sets of signatures. Returns:
4544      * <br />
4545      * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4546      * <br />
4547      * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4548      * <br />
4549      * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4550      * <br />
4551      * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4552      * <br />
4553      * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4554      */
4555     static int compareSignatures(Signature[] s1, Signature[] s2) {
4556         if (s1 == null) {
4557             return s2 == null
4558                     ? PackageManager.SIGNATURE_NEITHER_SIGNED
4559                     : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4560         }
4561
4562         if (s2 == null) {
4563             return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4564         }
4565
4566         if (s1.length != s2.length) {
4567             return PackageManager.SIGNATURE_NO_MATCH;
4568         }
4569
4570         // Since both signature sets are of size 1, we can compare without HashSets.
4571         if (s1.length == 1) {
4572             return s1[0].equals(s2[0]) ?
4573                     PackageManager.SIGNATURE_MATCH :
4574                     PackageManager.SIGNATURE_NO_MATCH;
4575         }
4576
4577         ArraySet<Signature> set1 = new ArraySet<Signature>();
4578         for (Signature sig : s1) {
4579             set1.add(sig);
4580         }
4581         ArraySet<Signature> set2 = new ArraySet<Signature>();
4582         for (Signature sig : s2) {
4583             set2.add(sig);
4584         }
4585         // Make sure s2 contains all signatures in s1.
4586         if (set1.equals(set2)) {
4587             return PackageManager.SIGNATURE_MATCH;
4588         }
4589         return PackageManager.SIGNATURE_NO_MATCH;
4590     }
4591
4592     /**
4593      * If the database version for this type of package (internal storage or
4594      * external storage) is less than the version where package signatures
4595      * were updated, return true.
4596      */
4597     private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4598         final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4599         return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4600     }
4601
4602     /**
4603      * Used for backward compatibility to make sure any packages with
4604      * certificate chains get upgraded to the new style. {@code existingSigs}
4605      * will be in the old format (since they were stored on disk from before the
4606      * system upgrade) and {@code scannedSigs} will be in the newer format.
4607      */
4608     private int compareSignaturesCompat(PackageSignatures existingSigs,
4609             PackageParser.Package scannedPkg) {
4610         if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4611             return PackageManager.SIGNATURE_NO_MATCH;
4612         }
4613
4614         ArraySet<Signature> existingSet = new ArraySet<Signature>();
4615         for (Signature sig : existingSigs.mSignatures) {
4616             existingSet.add(sig);
4617         }
4618         ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4619         for (Signature sig : scannedPkg.mSignatures) {
4620             try {
4621                 Signature[] chainSignatures = sig.getChainSignatures();
4622                 for (Signature chainSig : chainSignatures) {
4623                     scannedCompatSet.add(chainSig);
4624                 }
4625             } catch (CertificateEncodingException e) {
4626                 scannedCompatSet.add(sig);
4627             }
4628         }
4629         /*
4630          * Make sure the expanded scanned set contains all signatures in the
4631          * existing one.
4632          */
4633         if (scannedCompatSet.equals(existingSet)) {
4634             // Migrate the old signatures to the new scheme.
4635             existingSigs.assignSignatures(scannedPkg.mSignatures);
4636             // The new KeySets will be re-added later in the scanning process.
4637             synchronized (mPackages) {
4638                 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4639             }
4640             return PackageManager.SIGNATURE_MATCH;
4641         }
4642         return PackageManager.SIGNATURE_NO_MATCH;
4643     }
4644
4645     private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4646         final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4647         return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4648     }
4649
4650     private int compareSignaturesRecover(PackageSignatures existingSigs,
4651             PackageParser.Package scannedPkg) {
4652         if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4653             return PackageManager.SIGNATURE_NO_MATCH;
4654         }
4655
4656         String msg = null;
4657         try {
4658             if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4659                 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4660                         + scannedPkg.packageName);
4661                 return PackageManager.SIGNATURE_MATCH;
4662             }
4663         } catch (CertificateException e) {
4664             msg = e.getMessage();
4665         }
4666
4667         logCriticalInfo(Log.INFO,
4668                 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4669         return PackageManager.SIGNATURE_NO_MATCH;
4670     }
4671
4672     @Override
4673     public List<String> getAllPackages() {
4674         synchronized (mPackages) {
4675             return new ArrayList<String>(mPackages.keySet());
4676         }
4677     }
4678
4679     @Override
4680     public String[] getPackagesForUid(int uid) {
4681         uid = UserHandle.getAppId(uid);
4682         // reader
4683         synchronized (mPackages) {
4684             Object obj = mSettings.getUserIdLPr(uid);
4685             if (obj instanceof SharedUserSetting) {
4686                 final SharedUserSetting sus = (SharedUserSetting) obj;
4687                 final int N = sus.packages.size();
4688                 final String[] res = new String[N];
4689                 for (int i = 0; i < N; i++) {
4690                     res[i] = sus.packages.valueAt(i).name;
4691                 }
4692                 return res;
4693             } else if (obj instanceof PackageSetting) {
4694                 final PackageSetting ps = (PackageSetting) obj;
4695                 return new String[] { ps.name };
4696             }
4697         }
4698         return null;
4699     }
4700
4701     @Override
4702     public String getNameForUid(int uid) {
4703         // reader
4704         synchronized (mPackages) {
4705             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4706             if (obj instanceof SharedUserSetting) {
4707                 final SharedUserSetting sus = (SharedUserSetting) obj;
4708                 return sus.name + ":" + sus.userId;
4709             } else if (obj instanceof PackageSetting) {
4710                 final PackageSetting ps = (PackageSetting) obj;
4711                 return ps.name;
4712             }
4713         }
4714         return null;
4715     }
4716
4717     @Override
4718     public int getUidForSharedUser(String sharedUserName) {
4719         if(sharedUserName == null) {
4720             return -1;
4721         }
4722         // reader
4723         synchronized (mPackages) {
4724             final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4725             if (suid == null) {
4726                 return -1;
4727             }
4728             return suid.userId;
4729         }
4730     }
4731
4732     @Override
4733     public int getFlagsForUid(int uid) {
4734         synchronized (mPackages) {
4735             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4736             if (obj instanceof SharedUserSetting) {
4737                 final SharedUserSetting sus = (SharedUserSetting) obj;
4738                 return sus.pkgFlags;
4739             } else if (obj instanceof PackageSetting) {
4740                 final PackageSetting ps = (PackageSetting) obj;
4741                 return ps.pkgFlags;
4742             }
4743         }
4744         return 0;
4745     }
4746
4747     @Override
4748     public int getPrivateFlagsForUid(int uid) {
4749         synchronized (mPackages) {
4750             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4751             if (obj instanceof SharedUserSetting) {
4752                 final SharedUserSetting sus = (SharedUserSetting) obj;
4753                 return sus.pkgPrivateFlags;
4754             } else if (obj instanceof PackageSetting) {
4755                 final PackageSetting ps = (PackageSetting) obj;
4756                 return ps.pkgPrivateFlags;
4757             }
4758         }
4759         return 0;
4760     }
4761
4762     @Override
4763     public boolean isUidPrivileged(int uid) {
4764         uid = UserHandle.getAppId(uid);
4765         // reader
4766         synchronized (mPackages) {
4767             Object obj = mSettings.getUserIdLPr(uid);
4768             if (obj instanceof SharedUserSetting) {
4769                 final SharedUserSetting sus = (SharedUserSetting) obj;
4770                 final Iterator<PackageSetting> it = sus.packages.iterator();
4771                 while (it.hasNext()) {
4772                     if (it.next().isPrivileged()) {
4773                         return true;
4774                     }
4775                 }
4776             } else if (obj instanceof PackageSetting) {
4777                 final PackageSetting ps = (PackageSetting) obj;
4778                 return ps.isPrivileged();
4779             }
4780         }
4781         return false;
4782     }
4783
4784     @Override
4785     public String[] getAppOpPermissionPackages(String permissionName) {
4786         synchronized (mPackages) {
4787             ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4788             if (pkgs == null) {
4789                 return null;
4790             }
4791             return pkgs.toArray(new String[pkgs.size()]);
4792         }
4793     }
4794
4795     @Override
4796     public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4797             int flags, int userId) {
4798         try {
4799             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4800
4801             if (!sUserManager.exists(userId)) return null;
4802             flags = updateFlagsForResolve(flags, userId, intent);
4803             enforceCrossUserPermission(Binder.getCallingUid(), userId,
4804                     false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4805
4806             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4807             final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4808                     flags, userId);
4809             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4810
4811             final ResolveInfo bestChoice =
4812                     chooseBestActivity(intent, resolvedType, flags, query, userId);
4813             return bestChoice;
4814         } finally {
4815             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4816         }
4817     }
4818
4819     @Override
4820     public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4821             IntentFilter filter, int match, ComponentName activity) {
4822         final int userId = UserHandle.getCallingUserId();
4823         if (DEBUG_PREFERRED) {
4824             Log.v(TAG, "setLastChosenActivity intent=" + intent
4825                 + " resolvedType=" + resolvedType
4826                 + " flags=" + flags
4827                 + " filter=" + filter
4828                 + " match=" + match
4829                 + " activity=" + activity);
4830             filter.dump(new PrintStreamPrinter(System.out), "    ");
4831         }
4832         intent.setComponent(null);
4833         final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4834                 userId);
4835         // Find any earlier preferred or last chosen entries and nuke them
4836         findPreferredActivity(intent, resolvedType,
4837                 flags, query, 0, false, true, false, userId);
4838         // Add the new activity as the last chosen for this filter
4839         addPreferredActivityInternal(filter, match, null, activity, false, userId,
4840                 "Setting last chosen");
4841     }
4842
4843     @Override
4844     public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4845         final int userId = UserHandle.getCallingUserId();
4846         if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4847         final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4848                 userId);
4849         return findPreferredActivity(intent, resolvedType, flags, query, 0,
4850                 false, false, false, userId);
4851     }
4852
4853     private boolean isEphemeralDisabled() {
4854         // ephemeral apps have been disabled across the board
4855         if (DISABLE_EPHEMERAL_APPS) {
4856             return true;
4857         }
4858         // system isn't up yet; can't read settings, so, assume no ephemeral apps
4859         if (!mSystemReady) {
4860             return true;
4861         }
4862         // we can't get a content resolver until the system is ready; these checks must happen last
4863         final ContentResolver resolver = mContext.getContentResolver();
4864         if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
4865             return true;
4866         }
4867         return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
4868     }
4869
4870     private boolean isEphemeralAllowed(
4871             Intent intent, List<ResolveInfo> resolvedActivities, int userId,
4872             boolean skipPackageCheck) {
4873         // Short circuit and return early if possible.
4874         if (isEphemeralDisabled()) {
4875             return false;
4876         }
4877         final int callingUser = UserHandle.getCallingUserId();
4878         if (callingUser != UserHandle.USER_SYSTEM) {
4879             return false;
4880         }
4881         if (mEphemeralResolverConnection == null) {
4882             return false;
4883         }
4884         if (intent.getComponent() != null) {
4885             return false;
4886         }
4887         if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
4888             return false;
4889         }
4890         if (!skipPackageCheck && intent.getPackage() != null) {
4891             return false;
4892         }
4893         final boolean isWebUri = hasWebURI(intent);
4894         if (!isWebUri || intent.getData().getHost() == null) {
4895             return false;
4896         }
4897         // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4898         synchronized (mPackages) {
4899             final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
4900             for (int n = 0; n < count; n++) {
4901                 ResolveInfo info = resolvedActivities.get(n);
4902                 String packageName = info.activityInfo.packageName;
4903                 PackageSetting ps = mSettings.mPackages.get(packageName);
4904                 if (ps != null) {
4905                     // Try to get the status from User settings first
4906                     long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4907                     int status = (int) (packedStatus >> 32);
4908                     if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4909                             || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4910                         if (DEBUG_EPHEMERAL) {
4911                             Slog.v(TAG, "DENY ephemeral apps;"
4912                                 + " pkg: " + packageName + ", status: " + status);
4913                         }
4914                         return false;
4915                     }
4916                 }
4917             }
4918         }
4919         // We've exhausted all ways to deny ephemeral application; let the system look for them.
4920         return true;
4921     }
4922
4923     private static EphemeralResolveInfo getEphemeralResolveInfo(
4924             Context context, EphemeralResolverConnection resolverConnection, Intent intent,
4925             String resolvedType, int userId, String packageName) {
4926         final int ephemeralPrefixMask = Global.getInt(context.getContentResolver(),
4927                 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
4928         final int ephemeralPrefixCount = Global.getInt(context.getContentResolver(),
4929                 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
4930         final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
4931                 ephemeralPrefixCount);
4932         final int[] shaPrefix = digest.getDigestPrefix();
4933         final byte[][] digestBytes = digest.getDigestBytes();
4934         final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4935                 resolverConnection.getEphemeralResolveInfoList(shaPrefix, ephemeralPrefixMask);
4936         if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4937             // No hash prefix match; there are no ephemeral apps for this domain.
4938             return null;
4939         }
4940
4941         // Go in reverse order so we match the narrowest scope first.
4942         for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4943             for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4944                 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4945                     continue;
4946                 }
4947                 final List<IntentFilter> filters = ephemeralApplication.getFilters();
4948                 // No filters; this should never happen.
4949                 if (filters.isEmpty()) {
4950                     continue;
4951                 }
4952                 if (packageName != null
4953                         && !packageName.equals(ephemeralApplication.getPackageName())) {
4954                     continue;
4955                 }
4956                 // We have a domain match; resolve the filters to see if anything matches.
4957                 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4958                 for (int j = filters.size() - 1; j >= 0; --j) {
4959                     final EphemeralResolveIntentInfo intentInfo =
4960                             new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4961                     ephemeralResolver.addFilter(intentInfo);
4962                 }
4963                 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4964                         intent, resolvedType, false /*defaultOnly*/, userId);
4965                 if (!matchedResolveInfoList.isEmpty()) {
4966                     return matchedResolveInfoList.get(0);
4967                 }
4968             }
4969         }
4970         // Hash or filter mis-match; no ephemeral apps for this domain.
4971         return null;
4972     }
4973
4974     private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4975             int flags, List<ResolveInfo> query, int userId) {
4976         if (query != null) {
4977             final int N = query.size();
4978             if (N == 1) {
4979                 return query.get(0);
4980             } else if (N > 1) {
4981                 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4982                 // If there is more than one activity with the same priority,
4983                 // then let the user decide between them.
4984                 ResolveInfo r0 = query.get(0);
4985                 ResolveInfo r1 = query.get(1);
4986                 if (DEBUG_INTENT_MATCHING || debug) {
4987                     Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4988                             + r1.activityInfo.name + "=" + r1.priority);
4989                 }
4990                 // If the first activity has a higher priority, or a different
4991                 // default, then it is always desirable to pick it.
4992                 if (r0.priority != r1.priority
4993                         || r0.preferredOrder != r1.preferredOrder
4994                         || r0.isDefault != r1.isDefault) {
4995                     return query.get(0);
4996                 }
4997                 // If we have saved a preference for a preferred activity for
4998                 // this Intent, use that.
4999                 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5000                         flags, query, r0.priority, true, false, debug, userId);
5001                 if (ri != null) {
5002                     return ri;
5003                 }
5004                 ri = new ResolveInfo(mResolveInfo);
5005                 ri.activityInfo = new ActivityInfo(ri.activityInfo);
5006                 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5007                 // If all of the options come from the same package, show the application's
5008                 // label and icon instead of the generic resolver's.
5009                 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5010                 // and then throw away the ResolveInfo itself, meaning that the caller loses
5011                 // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5012                 // a fallback for this case; we only set the target package's resources on
5013                 // the ResolveInfo, not the ActivityInfo.
5014                 final String intentPackage = intent.getPackage();
5015                 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5016                     final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5017                     ri.resolvePackageName = intentPackage;
5018                     if (userNeedsBadging(userId)) {
5019                         ri.noResourceId = true;
5020                     } else {
5021                         ri.icon = appi.icon;
5022                     }
5023                     ri.iconResourceId = appi.icon;
5024                     ri.labelRes = appi.labelRes;
5025                 }
5026                 ri.activityInfo.applicationInfo = new ApplicationInfo(
5027                         ri.activityInfo.applicationInfo);
5028                 if (userId != 0) {
5029                     ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5030                             UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5031                 }
5032                 // Make sure that the resolver is displayable in car mode
5033                 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5034                 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5035                 return ri;
5036             }
5037         }
5038         return null;
5039     }
5040
5041     /**
5042      * Return true if the given list is not empty and all of its contents have
5043      * an activityInfo with the given package name.
5044      */
5045     private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5046         if (ArrayUtils.isEmpty(list)) {
5047             return false;
5048         }
5049         for (int i = 0, N = list.size(); i < N; i++) {
5050             final ResolveInfo ri = list.get(i);
5051             final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5052             if (ai == null || !packageName.equals(ai.packageName)) {
5053                 return false;
5054             }
5055         }
5056         return true;
5057     }
5058
5059     private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5060             int flags, List<ResolveInfo> query, boolean debug, int userId) {
5061         final int N = query.size();
5062         PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5063                 .get(userId);
5064         // Get the list of persistent preferred activities that handle the intent
5065         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5066         List<PersistentPreferredActivity> pprefs = ppir != null
5067                 ? ppir.queryIntent(intent, resolvedType,
5068                         (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5069                 : null;
5070         if (pprefs != null && pprefs.size() > 0) {
5071             final int M = pprefs.size();
5072             for (int i=0; i<M; i++) {
5073                 final PersistentPreferredActivity ppa = pprefs.get(i);
5074                 if (DEBUG_PREFERRED || debug) {
5075                     Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5076                             + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5077                             + "\n  component=" + ppa.mComponent);
5078                     ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5079                 }
5080                 final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5081                         flags | MATCH_DISABLED_COMPONENTS, userId);
5082                 if (DEBUG_PREFERRED || debug) {
5083                     Slog.v(TAG, "Found persistent preferred activity:");
5084                     if (ai != null) {
5085                         ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5086                     } else {
5087                         Slog.v(TAG, "  null");
5088                     }
5089                 }
5090                 if (ai == null) {
5091                     // This previously registered persistent preferred activity
5092                     // component is no longer known. Ignore it and do NOT remove it.
5093                     continue;
5094                 }
5095                 for (int j=0; j<N; j++) {
5096                     final ResolveInfo ri = query.get(j);
5097                     if (!ri.activityInfo.applicationInfo.packageName
5098                             .equals(ai.applicationInfo.packageName)) {
5099                         continue;
5100                     }
5101                     if (!ri.activityInfo.name.equals(ai.name)) {
5102                         continue;
5103                     }
5104                     //  Found a persistent preference that can handle the intent.
5105                     if (DEBUG_PREFERRED || debug) {
5106                         Slog.v(TAG, "Returning persistent preferred activity: " +
5107                                 ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5108                     }
5109                     return ri;
5110                 }
5111             }
5112         }
5113         return null;
5114     }
5115
5116     // TODO: handle preferred activities missing while user has amnesia
5117     ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5118             List<ResolveInfo> query, int priority, boolean always,
5119             boolean removeMatches, boolean debug, int userId) {
5120         if (!sUserManager.exists(userId)) return null;
5121         flags = updateFlagsForResolve(flags, userId, intent);
5122         // writer
5123         synchronized (mPackages) {
5124             if (intent.getSelector() != null) {
5125                 intent = intent.getSelector();
5126             }
5127             if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5128
5129             // Try to find a matching persistent preferred activity.
5130             ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5131                     debug, userId);
5132
5133             // If a persistent preferred activity matched, use it.
5134             if (pri != null) {
5135                 return pri;
5136             }
5137
5138             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5139             // Get the list of preferred activities that handle the intent
5140             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5141             List<PreferredActivity> prefs = pir != null
5142                     ? pir.queryIntent(intent, resolvedType,
5143                             (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5144                     : null;
5145             if (prefs != null && prefs.size() > 0) {
5146                 boolean changed = false;
5147                 try {
5148                     // First figure out how good the original match set is.
5149                     // We will only allow preferred activities that came
5150                     // from the same match quality.
5151                     int match = 0;
5152
5153                     if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5154
5155                     final int N = query.size();
5156                     for (int j=0; j<N; j++) {
5157                         final ResolveInfo ri = query.get(j);
5158                         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5159                                 + ": 0x" + Integer.toHexString(match));
5160                         if (ri.match > match) {
5161                             match = ri.match;
5162                         }
5163                     }
5164
5165                     if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5166                             + Integer.toHexString(match));
5167
5168                     match &= IntentFilter.MATCH_CATEGORY_MASK;
5169                     final int M = prefs.size();
5170                     for (int i=0; i<M; i++) {
5171                         final PreferredActivity pa = prefs.get(i);
5172                         if (DEBUG_PREFERRED || debug) {
5173                             Slog.v(TAG, "Checking PreferredActivity ds="
5174                                     + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5175                                     + "\n  component=" + pa.mPref.mComponent);
5176                             pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5177                         }
5178                         if (pa.mPref.mMatch != match) {
5179                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5180                                     + Integer.toHexString(pa.mPref.mMatch));
5181                             continue;
5182                         }
5183                         // If it's not an "always" type preferred activity and that's what we're
5184                         // looking for, skip it.
5185                         if (always && !pa.mPref.mAlways) {
5186                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5187                             continue;
5188                         }
5189                         final ActivityInfo ai = getActivityInfo(
5190                                 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5191                                         | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5192                                 userId);
5193                         if (DEBUG_PREFERRED || debug) {
5194                             Slog.v(TAG, "Found preferred activity:");
5195                             if (ai != null) {
5196                                 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5197                             } else {
5198                                 Slog.v(TAG, "  null");
5199                             }
5200                         }
5201                         if (ai == null) {
5202                             // This previously registered preferred activity
5203                             // component is no longer known.  Most likely an update
5204                             // to the app was installed and in the new version this
5205                             // component no longer exists.  Clean it up by removing
5206                             // it from the preferred activities list, and skip it.
5207                             Slog.w(TAG, "Removing dangling preferred activity: "
5208                                     + pa.mPref.mComponent);
5209                             pir.removeFilter(pa);
5210                             changed = true;
5211                             continue;
5212                         }
5213                         for (int j=0; j<N; j++) {
5214                             final ResolveInfo ri = query.get(j);
5215                             if (!ri.activityInfo.applicationInfo.packageName
5216                                     .equals(ai.applicationInfo.packageName)) {
5217                                 continue;
5218                             }
5219                             if (!ri.activityInfo.name.equals(ai.name)) {
5220                                 continue;
5221                             }
5222
5223                             if (removeMatches) {
5224                                 pir.removeFilter(pa);
5225                                 changed = true;
5226                                 if (DEBUG_PREFERRED) {
5227                                     Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5228                                 }
5229                                 break;
5230                             }
5231
5232                             // Okay we found a previously set preferred or last chosen app.
5233                             // If the result set is different from when this
5234                             // was created, we need to clear it and re-ask the
5235                             // user their preference, if we're looking for an "always" type entry.
5236                             if (always && !pa.mPref.sameSet(query)) {
5237                                 Slog.i(TAG, "Result set changed, dropping preferred activity for "
5238                                         + intent + " type " + resolvedType);
5239                                 if (DEBUG_PREFERRED) {
5240                                     Slog.v(TAG, "Removing preferred activity since set changed "
5241                                             + pa.mPref.mComponent);
5242                                 }
5243                                 pir.removeFilter(pa);
5244                                 // Re-add the filter as a "last chosen" entry (!always)
5245                                 PreferredActivity lastChosen = new PreferredActivity(
5246                                         pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5247                                 pir.addFilter(lastChosen);
5248                                 changed = true;
5249                                 return null;
5250                             }
5251
5252                             // Yay! Either the set matched or we're looking for the last chosen
5253                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5254                                     + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5255                             return ri;
5256                         }
5257                     }
5258                 } finally {
5259                     if (changed) {
5260                         if (DEBUG_PREFERRED) {
5261                             Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5262                         }
5263                         scheduleWritePackageRestrictionsLocked(userId);
5264                     }
5265                 }
5266             }
5267         }
5268         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5269         return null;
5270     }
5271
5272     /*
5273      * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5274      */
5275     @Override
5276     public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5277             int targetUserId) {
5278         mContext.enforceCallingOrSelfPermission(
5279                 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5280         List<CrossProfileIntentFilter> matches =
5281                 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5282         if (matches != null) {
5283             int size = matches.size();
5284             for (int i = 0; i < size; i++) {
5285                 if (matches.get(i).getTargetUserId() == targetUserId) return true;
5286             }
5287         }
5288         if (hasWebURI(intent)) {
5289             // cross-profile app linking works only towards the parent.
5290             final UserInfo parent = getProfileParent(sourceUserId);
5291             synchronized(mPackages) {
5292                 int flags = updateFlagsForResolve(0, parent.id, intent);
5293                 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5294                         intent, resolvedType, flags, sourceUserId, parent.id);
5295                 return xpDomainInfo != null;
5296             }
5297         }
5298         return false;
5299     }
5300
5301     private UserInfo getProfileParent(int userId) {
5302         final long identity = Binder.clearCallingIdentity();
5303         try {
5304             return sUserManager.getProfileParent(userId);
5305         } finally {
5306             Binder.restoreCallingIdentity(identity);
5307         }
5308     }
5309
5310     private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5311             String resolvedType, int userId) {
5312         CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5313         if (resolver != null) {
5314             return resolver.queryIntent(intent, resolvedType, false, userId);
5315         }
5316         return null;
5317     }
5318
5319     @Override
5320     public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5321             String resolvedType, int flags, int userId) {
5322         try {
5323             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5324
5325             return new ParceledListSlice<>(
5326                     queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5327         } finally {
5328             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5329         }
5330     }
5331
5332     private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5333             String resolvedType, int flags, int userId) {
5334         if (!sUserManager.exists(userId)) return Collections.emptyList();
5335         flags = updateFlagsForResolve(flags, userId, intent);
5336         enforceCrossUserPermission(Binder.getCallingUid(), userId,
5337                 false /* requireFullPermission */, false /* checkShell */,
5338                 "query intent activities");
5339         ComponentName comp = intent.getComponent();
5340         if (comp == null) {
5341             if (intent.getSelector() != null) {
5342                 intent = intent.getSelector();
5343                 comp = intent.getComponent();
5344             }
5345         }
5346
5347         if (comp != null) {
5348             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5349             final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5350             if (ai != null) {
5351                 final ResolveInfo ri = new ResolveInfo();
5352                 ri.activityInfo = ai;
5353                 list.add(ri);
5354             }
5355             return list;
5356         }
5357
5358         // reader
5359         boolean sortResult = false;
5360         boolean addEphemeral = false;
5361         boolean matchEphemeralPackage = false;
5362         List<ResolveInfo> result;
5363         final String pkgName = intent.getPackage();
5364         synchronized (mPackages) {
5365             if (pkgName == null) {
5366                 List<CrossProfileIntentFilter> matchingFilters =
5367                         getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5368                 // Check for results that need to skip the current profile.
5369                 ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5370                         resolvedType, flags, userId);
5371                 if (xpResolveInfo != null) {
5372                     List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
5373                     xpResult.add(xpResolveInfo);
5374                     return filterIfNotSystemUser(xpResult, userId);
5375                 }
5376
5377                 // Check for results in the current profile.
5378                 result = filterIfNotSystemUser(mActivities.queryIntent(
5379                         intent, resolvedType, flags, userId), userId);
5380                 addEphemeral =
5381                         isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
5382
5383                 // Check for cross profile results.
5384                 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5385                 xpResolveInfo = queryCrossProfileIntents(
5386                         matchingFilters, intent, resolvedType, flags, userId,
5387                         hasNonNegativePriorityResult);
5388                 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5389                     boolean isVisibleToUser = filterIfNotSystemUser(
5390                             Collections.singletonList(xpResolveInfo), userId).size() > 0;
5391                     if (isVisibleToUser) {
5392                         result.add(xpResolveInfo);
5393                         sortResult = true;
5394                     }
5395                 }
5396                 if (hasWebURI(intent)) {
5397                     CrossProfileDomainInfo xpDomainInfo = null;
5398                     final UserInfo parent = getProfileParent(userId);
5399                     if (parent != null) {
5400                         xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5401                                 flags, userId, parent.id);
5402                     }
5403                     if (xpDomainInfo != null) {
5404                         if (xpResolveInfo != null) {
5405                             // If we didn't remove it, the cross-profile ResolveInfo would be twice
5406                             // in the result.
5407                             result.remove(xpResolveInfo);
5408                         }
5409                         if (result.size() == 0 && !addEphemeral) {
5410                             result.add(xpDomainInfo.resolveInfo);
5411                             return result;
5412                         }
5413                     }
5414                     if (result.size() > 1 || addEphemeral) {
5415                         result = filterCandidatesWithDomainPreferredActivitiesLPr(
5416                                 intent, flags, result, xpDomainInfo, userId);
5417                         sortResult = true;
5418                     }
5419                 }
5420             } else {
5421                 final PackageParser.Package pkg = mPackages.get(pkgName);
5422                 if (pkg != null) {
5423                     result = filterIfNotSystemUser(
5424                             mActivities.queryIntentForPackage(
5425                                     intent, resolvedType, flags, pkg.activities, userId),
5426                             userId);
5427                 } else {
5428                     // the caller wants to resolve for a particular package; however, there
5429                     // were no installed results, so, try to find an ephemeral result
5430                     addEphemeral = isEphemeralAllowed(
5431                             intent, null /*result*/, userId, true /*skipPackageCheck*/);
5432                     matchEphemeralPackage = true;
5433                     result = new ArrayList<ResolveInfo>();
5434                 }
5435             }
5436         }
5437         if (addEphemeral) {
5438             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
5439             final EphemeralResolveInfo ai = getEphemeralResolveInfo(
5440                     mContext, mEphemeralResolverConnection, intent, resolvedType, userId,
5441                     matchEphemeralPackage ? pkgName : null);
5442             if (ai != null) {
5443                 if (DEBUG_EPHEMERAL) {
5444                     Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
5445                 }
5446                 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
5447                 ephemeralInstaller.ephemeralResolveInfo = ai;
5448                 // make sure this resolver is the default
5449                 ephemeralInstaller.isDefault = true;
5450                 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
5451                         | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
5452                 // add a non-generic filter
5453                 ephemeralInstaller.filter = new IntentFilter(intent.getAction());
5454                 ephemeralInstaller.filter.addDataPath(
5455                         intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
5456                 result.add(ephemeralInstaller);
5457             }
5458             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5459         }
5460         if (sortResult) {
5461             Collections.sort(result, mResolvePrioritySorter);
5462         }
5463         return result;
5464     }
5465
5466     private static class CrossProfileDomainInfo {
5467         /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5468         ResolveInfo resolveInfo;
5469         /* Best domain verification status of the activities found in the other profile */
5470         int bestDomainVerificationStatus;
5471     }
5472
5473     private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5474             String resolvedType, int flags, int sourceUserId, int parentUserId) {
5475         if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5476                 sourceUserId)) {
5477             return null;
5478         }
5479         List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5480                 resolvedType, flags, parentUserId);
5481
5482         if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5483             return null;
5484         }
5485         CrossProfileDomainInfo result = null;
5486         int size = resultTargetUser.size();
5487         for (int i = 0; i < size; i++) {
5488             ResolveInfo riTargetUser = resultTargetUser.get(i);
5489             // Intent filter verification is only for filters that specify a host. So don't return
5490             // those that handle all web uris.
5491             if (riTargetUser.handleAllWebDataURI) {
5492                 continue;
5493             }
5494             String packageName = riTargetUser.activityInfo.packageName;
5495             PackageSetting ps = mSettings.mPackages.get(packageName);
5496             if (ps == null) {
5497                 continue;
5498             }
5499             long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5500             int status = (int)(verificationState >> 32);
5501             if (result == null) {
5502                 result = new CrossProfileDomainInfo();
5503                 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5504                         sourceUserId, parentUserId);
5505                 result.bestDomainVerificationStatus = status;
5506             } else {
5507                 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5508                         result.bestDomainVerificationStatus);
5509             }
5510         }
5511         // Don't consider matches with status NEVER across profiles.
5512         if (result != null && result.bestDomainVerificationStatus
5513                 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5514             return null;
5515         }
5516         return result;
5517     }
5518
5519     /**
5520      * Verification statuses are ordered from the worse to the best, except for
5521      * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5522      */
5523     private int bestDomainVerificationStatus(int status1, int status2) {
5524         if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5525             return status2;
5526         }
5527         if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5528             return status1;
5529         }
5530         return (int) MathUtils.max(status1, status2);
5531     }
5532
5533     private boolean isUserEnabled(int userId) {
5534         long callingId = Binder.clearCallingIdentity();
5535         try {
5536             UserInfo userInfo = sUserManager.getUserInfo(userId);
5537             return userInfo != null && userInfo.isEnabled();
5538         } finally {
5539             Binder.restoreCallingIdentity(callingId);
5540         }
5541     }
5542
5543     /**
5544      * Filter out activities with systemUserOnly flag set, when current user is not System.
5545      *
5546      * @return filtered list
5547      */
5548     private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5549         if (userId == UserHandle.USER_SYSTEM) {
5550             return resolveInfos;
5551         }
5552         for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5553             ResolveInfo info = resolveInfos.get(i);
5554             if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5555                 resolveInfos.remove(i);
5556             }
5557         }
5558         return resolveInfos;
5559     }
5560
5561     /**
5562      * @param resolveInfos list of resolve infos in descending priority order
5563      * @return if the list contains a resolve info with non-negative priority
5564      */
5565     private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5566         return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5567     }
5568
5569     private static boolean hasWebURI(Intent intent) {
5570         if (intent.getData() == null) {
5571             return false;
5572         }
5573         final String scheme = intent.getScheme();
5574         if (TextUtils.isEmpty(scheme)) {
5575             return false;
5576         }
5577         return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5578     }
5579
5580     private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5581             int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5582             int userId) {
5583         final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5584
5585         if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5586             Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5587                     candidates.size());
5588         }
5589
5590         ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5591         ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5592         ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5593         ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5594         ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5595         ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5596
5597         synchronized (mPackages) {
5598             final int count = candidates.size();
5599             // First, try to use linked apps. Partition the candidates into four lists:
5600             // one for the final results, one for the "do not use ever", one for "undefined status"
5601             // and finally one for "browser app type".
5602             for (int n=0; n<count; n++) {
5603                 ResolveInfo info = candidates.get(n);
5604                 String packageName = info.activityInfo.packageName;
5605                 PackageSetting ps = mSettings.mPackages.get(packageName);
5606                 if (ps != null) {
5607                     // Add to the special match all list (Browser use case)
5608                     if (info.handleAllWebDataURI) {
5609                         matchAllList.add(info);
5610                         continue;
5611                     }
5612                     // Try to get the status from User settings first
5613                     long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5614                     int status = (int)(packedStatus >> 32);
5615                     int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5616                     if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5617                         if (DEBUG_DOMAIN_VERIFICATION) {
5618                             Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5619                                     + " : linkgen=" + linkGeneration);
5620                         }
5621                         // Use link-enabled generation as preferredOrder, i.e.
5622                         // prefer newly-enabled over earlier-enabled.
5623                         info.preferredOrder = linkGeneration;
5624                         alwaysList.add(info);
5625                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5626                         if (DEBUG_DOMAIN_VERIFICATION) {
5627                             Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5628                         }
5629                         neverList.add(info);
5630                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5631                         if (DEBUG_DOMAIN_VERIFICATION) {
5632                             Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5633                         }
5634                         alwaysAskList.add(info);
5635                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5636                             status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5637                         if (DEBUG_DOMAIN_VERIFICATION) {
5638                             Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5639                         }
5640                         undefinedList.add(info);
5641                     }
5642                 }
5643             }
5644
5645             // We'll want to include browser possibilities in a few cases
5646             boolean includeBrowser = false;
5647
5648             // First try to add the "always" resolution(s) for the current user, if any
5649             if (alwaysList.size() > 0) {
5650                 result.addAll(alwaysList);
5651             } else {
5652                 // Add all undefined apps as we want them to appear in the disambiguation dialog.
5653                 result.addAll(undefinedList);
5654                 // Maybe add one for the other profile.
5655                 if (xpDomainInfo != null && (
5656                         xpDomainInfo.bestDomainVerificationStatus
5657                         != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5658                     result.add(xpDomainInfo.resolveInfo);
5659                 }
5660                 includeBrowser = true;
5661             }
5662
5663             // The presence of any 'always ask' alternatives means we'll also offer browsers.
5664             // If there were 'always' entries their preferred order has been set, so we also
5665             // back that off to make the alternatives equivalent
5666             if (alwaysAskList.size() > 0) {
5667                 for (ResolveInfo i : result) {
5668                     i.preferredOrder = 0;
5669                 }
5670                 result.addAll(alwaysAskList);
5671                 includeBrowser = true;
5672             }
5673
5674             if (includeBrowser) {
5675                 // Also add browsers (all of them or only the default one)
5676                 if (DEBUG_DOMAIN_VERIFICATION) {
5677                     Slog.v(TAG, "   ...including browsers in candidate set");
5678                 }
5679                 if ((matchFlags & MATCH_ALL) != 0) {
5680                     result.addAll(matchAllList);
5681                 } else {
5682                     // Browser/generic handling case.  If there's a default browser, go straight
5683                     // to that (but only if there is no other higher-priority match).
5684                     final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5685                     int maxMatchPrio = 0;
5686                     ResolveInfo defaultBrowserMatch = null;
5687                     final int numCandidates = matchAllList.size();
5688                     for (int n = 0; n < numCandidates; n++) {
5689                         ResolveInfo info = matchAllList.get(n);
5690                         // track the highest overall match priority...
5691                         if (info.priority > maxMatchPrio) {
5692                             maxMatchPrio = info.priority;
5693                         }
5694                         // ...and the highest-priority default browser match
5695                         if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5696                             if (defaultBrowserMatch == null
5697                                     || (defaultBrowserMatch.priority < info.priority)) {
5698                                 if (debug) {
5699                                     Slog.v(TAG, "Considering default browser match " + info);
5700                                 }
5701                                 defaultBrowserMatch = info;
5702                             }
5703                         }
5704                     }
5705                     if (defaultBrowserMatch != null
5706                             && defaultBrowserMatch.priority >= maxMatchPrio
5707                             && !TextUtils.isEmpty(defaultBrowserPackageName))
5708                     {
5709                         if (debug) {
5710                             Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5711                         }
5712                         result.add(defaultBrowserMatch);
5713                     } else {
5714                         result.addAll(matchAllList);
5715                     }
5716                 }
5717
5718                 // If there is nothing selected, add all candidates and remove the ones that the user
5719                 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5720                 if (result.size() == 0) {
5721                     result.addAll(candidates);
5722                     result.removeAll(neverList);
5723                 }
5724             }
5725         }
5726         if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5727             Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5728                     result.size());
5729             for (ResolveInfo info : result) {
5730                 Slog.v(TAG, "  + " + info.activityInfo);
5731             }
5732         }
5733         return result;
5734     }
5735
5736     // Returns a packed value as a long:
5737     //
5738     // high 'int'-sized word: link status: undefined/ask/never/always.
5739     // low 'int'-sized word: relative priority among 'always' results.
5740     private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5741         long result = ps.getDomainVerificationStatusForUser(userId);
5742         // if none available, get the master status
5743         if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5744             if (ps.getIntentFilterVerificationInfo() != null) {
5745                 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5746             }
5747         }
5748         return result;
5749     }
5750
5751     private ResolveInfo querySkipCurrentProfileIntents(
5752             List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5753             int flags, int sourceUserId) {
5754         if (matchingFilters != null) {
5755             int size = matchingFilters.size();
5756             for (int i = 0; i < size; i ++) {
5757                 CrossProfileIntentFilter filter = matchingFilters.get(i);
5758                 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5759                     // Checking if there are activities in the target user that can handle the
5760                     // intent.
5761                     ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5762                             resolvedType, flags, sourceUserId);
5763                     if (resolveInfo != null) {
5764                         return resolveInfo;
5765                     }
5766                 }
5767             }
5768         }
5769         return null;
5770     }
5771
5772     // Return matching ResolveInfo in target user if any.
5773     private ResolveInfo queryCrossProfileIntents(
5774             List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5775             int flags, int sourceUserId, boolean matchInCurrentProfile) {
5776         if (matchingFilters != null) {
5777             // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5778             // match the same intent. For performance reasons, it is better not to
5779             // run queryIntent twice for the same userId
5780             SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5781             int size = matchingFilters.size();
5782             for (int i = 0; i < size; i++) {
5783                 CrossProfileIntentFilter filter = matchingFilters.get(i);
5784                 int targetUserId = filter.getTargetUserId();
5785                 boolean skipCurrentProfile =
5786                         (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5787                 boolean skipCurrentProfileIfNoMatchFound =
5788                         (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5789                 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5790                         && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5791                     // Checking if there are activities in the target user that can handle the
5792                     // intent.
5793                     ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5794                             resolvedType, flags, sourceUserId);
5795                     if (resolveInfo != null) return resolveInfo;
5796                     alreadyTriedUserIds.put(targetUserId, true);
5797                 }
5798             }
5799         }
5800         return null;
5801     }
5802
5803     /**
5804      * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5805      * will forward the intent to the filter's target user.
5806      * Otherwise, returns null.
5807      */
5808     private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5809             String resolvedType, int flags, int sourceUserId) {
5810         int targetUserId = filter.getTargetUserId();
5811         List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5812                 resolvedType, flags, targetUserId);
5813         if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5814             // If all the matches in the target profile are suspended, return null.
5815             for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5816                 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5817                         & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5818                     return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5819                             targetUserId);
5820                 }
5821             }
5822         }
5823         return null;
5824     }
5825
5826     private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5827             int sourceUserId, int targetUserId) {
5828         ResolveInfo forwardingResolveInfo = new ResolveInfo();
5829         long ident = Binder.clearCallingIdentity();
5830         boolean targetIsProfile;
5831         try {
5832             targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5833         } finally {
5834             Binder.restoreCallingIdentity(ident);
5835         }
5836         String className;
5837         if (targetIsProfile) {
5838             className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5839         } else {
5840             className = FORWARD_INTENT_TO_PARENT;
5841         }
5842         ComponentName forwardingActivityComponentName = new ComponentName(
5843                 mAndroidApplication.packageName, className);
5844         ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5845                 sourceUserId);
5846         if (!targetIsProfile) {
5847             forwardingActivityInfo.showUserIcon = targetUserId;
5848             forwardingResolveInfo.noResourceId = true;
5849         }
5850         forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5851         forwardingResolveInfo.priority = 0;
5852         forwardingResolveInfo.preferredOrder = 0;
5853         forwardingResolveInfo.match = 0;
5854         forwardingResolveInfo.isDefault = true;
5855         forwardingResolveInfo.filter = filter;
5856         forwardingResolveInfo.targetUserId = targetUserId;
5857         return forwardingResolveInfo;
5858     }
5859
5860     @Override
5861     public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5862             Intent[] specifics, String[] specificTypes, Intent intent,
5863             String resolvedType, int flags, int userId) {
5864         return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5865                 specificTypes, intent, resolvedType, flags, userId));
5866     }
5867
5868     private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5869             Intent[] specifics, String[] specificTypes, Intent intent,
5870             String resolvedType, int flags, int userId) {
5871         if (!sUserManager.exists(userId)) return Collections.emptyList();
5872         flags = updateFlagsForResolve(flags, userId, intent);
5873         enforceCrossUserPermission(Binder.getCallingUid(), userId,
5874                 false /* requireFullPermission */, false /* checkShell */,
5875                 "query intent activity options");
5876         final String resultsAction = intent.getAction();
5877
5878         final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5879                 | PackageManager.GET_RESOLVED_FILTER, userId);
5880
5881         if (DEBUG_INTENT_MATCHING) {
5882             Log.v(TAG, "Query " + intent + ": " + results);
5883         }
5884
5885         int specificsPos = 0;
5886         int N;
5887
5888         // todo: note that the algorithm used here is O(N^2).  This
5889         // isn't a problem in our current environment, but if we start running
5890         // into situations where we have more than 5 or 10 matches then this
5891         // should probably be changed to something smarter...
5892
5893         // First we go through and resolve each of the specific items
5894         // that were supplied, taking care of removing any corresponding
5895         // duplicate items in the generic resolve list.
5896         if (specifics != null) {
5897             for (int i=0; i<specifics.length; i++) {
5898                 final Intent sintent = specifics[i];
5899                 if (sintent == null) {
5900                     continue;
5901                 }
5902
5903                 if (DEBUG_INTENT_MATCHING) {
5904                     Log.v(TAG, "Specific #" + i + ": " + sintent);
5905                 }
5906
5907                 String action = sintent.getAction();
5908                 if (resultsAction != null && resultsAction.equals(action)) {
5909                     // If this action was explicitly requested, then don't
5910                     // remove things that have it.
5911                     action = null;
5912                 }
5913
5914                 ResolveInfo ri = null;
5915                 ActivityInfo ai = null;
5916
5917                 ComponentName comp = sintent.getComponent();
5918                 if (comp == null) {
5919                     ri = resolveIntent(
5920                         sintent,
5921                         specificTypes != null ? specificTypes[i] : null,
5922                             flags, userId);
5923                     if (ri == null) {
5924                         continue;
5925                     }
5926                     if (ri == mResolveInfo) {
5927                         // ACK!  Must do something better with this.
5928                     }
5929                     ai = ri.activityInfo;
5930                     comp = new ComponentName(ai.applicationInfo.packageName,
5931                             ai.name);
5932                 } else {
5933                     ai = getActivityInfo(comp, flags, userId);
5934                     if (ai == null) {
5935                         continue;
5936                     }
5937                 }
5938
5939                 // Look for any generic query activities that are duplicates
5940                 // of this specific one, and remove them from the results.
5941                 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5942                 N = results.size();
5943                 int j;
5944                 for (j=specificsPos; j<N; j++) {
5945                     ResolveInfo sri = results.get(j);
5946                     if ((sri.activityInfo.name.equals(comp.getClassName())
5947                             && sri.activityInfo.applicationInfo.packageName.equals(
5948                                     comp.getPackageName()))
5949                         || (action != null && sri.filter.matchAction(action))) {
5950                         results.remove(j);
5951                         if (DEBUG_INTENT_MATCHING) Log.v(
5952                             TAG, "Removing duplicate item from " + j
5953                             + " due to specific " + specificsPos);
5954                         if (ri == null) {
5955                             ri = sri;
5956                         }
5957                         j--;
5958                         N--;
5959                     }
5960                 }
5961
5962                 // Add this specific item to its proper place.
5963                 if (ri == null) {
5964                     ri = new ResolveInfo();
5965                     ri.activityInfo = ai;
5966                 }
5967                 results.add(specificsPos, ri);
5968                 ri.specificIndex = i;
5969                 specificsPos++;
5970             }
5971         }
5972
5973         // Now we go through the remaining generic results and remove any
5974         // duplicate actions that are found here.
5975         N = results.size();
5976         for (int i=specificsPos; i<N-1; i++) {
5977             final ResolveInfo rii = results.get(i);
5978             if (rii.filter == null) {
5979                 continue;
5980             }
5981
5982             // Iterate over all of the actions of this result's intent
5983             // filter...  typically this should be just one.
5984             final Iterator<String> it = rii.filter.actionsIterator();
5985             if (it == null) {
5986                 continue;
5987             }
5988             while (it.hasNext()) {
5989                 final String action = it.next();
5990                 if (resultsAction != null && resultsAction.equals(action)) {
5991                     // If this action was explicitly requested, then don't
5992                     // remove things that have it.
5993                     continue;
5994                 }
5995                 for (int j=i+1; j<N; j++) {
5996                     final ResolveInfo rij = results.get(j);
5997                     if (rij.filter != null && rij.filter.hasAction(action)) {
5998                         results.remove(j);
5999                         if (DEBUG_INTENT_MATCHING) Log.v(
6000                             TAG, "Removing duplicate item from " + j
6001                             + " due to action " + action + " at " + i);
6002                         j--;
6003                         N--;
6004                     }
6005                 }
6006             }
6007
6008             // If the caller didn't request filter information, drop it now
6009             // so we don't have to marshall/unmarshall it.
6010             if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6011                 rii.filter = null;
6012             }
6013         }
6014
6015         // Filter out the caller activity if so requested.
6016         if (caller != null) {
6017             N = results.size();
6018             for (int i=0; i<N; i++) {
6019                 ActivityInfo ainfo = results.get(i).activityInfo;
6020                 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6021                         && caller.getClassName().equals(ainfo.name)) {
6022                     results.remove(i);
6023                     break;
6024                 }
6025             }
6026         }
6027
6028         // If the caller didn't request filter information,
6029         // drop them now so we don't have to
6030         // marshall/unmarshall it.
6031         if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6032             N = results.size();
6033             for (int i=0; i<N; i++) {
6034                 results.get(i).filter = null;
6035             }
6036         }
6037
6038         if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6039         return results;
6040     }
6041
6042     @Override
6043     public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6044             String resolvedType, int flags, int userId) {
6045         return new ParceledListSlice<>(
6046                 queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6047     }
6048
6049     private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6050             String resolvedType, int flags, int userId) {
6051         if (!sUserManager.exists(userId)) return Collections.emptyList();
6052         flags = updateFlagsForResolve(flags, userId, intent);
6053         ComponentName comp = intent.getComponent();
6054         if (comp == null) {
6055             if (intent.getSelector() != null) {
6056                 intent = intent.getSelector();
6057                 comp = intent.getComponent();
6058             }
6059         }
6060         if (comp != null) {
6061             List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6062             ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6063             if (ai != null) {
6064                 ResolveInfo ri = new ResolveInfo();
6065                 ri.activityInfo = ai;
6066                 list.add(ri);
6067             }
6068             return list;
6069         }
6070
6071         // reader
6072         synchronized (mPackages) {
6073             String pkgName = intent.getPackage();
6074             if (pkgName == null) {
6075                 return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6076             }
6077             final PackageParser.Package pkg = mPackages.get(pkgName);
6078             if (pkg != null) {
6079                 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6080                         userId);
6081             }
6082             return Collections.emptyList();
6083         }
6084     }
6085
6086     @Override
6087     public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6088         if (!sUserManager.exists(userId)) return null;
6089         flags = updateFlagsForResolve(flags, userId, intent);
6090         List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6091         if (query != null) {
6092             if (query.size() >= 1) {
6093                 // If there is more than one service with the same priority,
6094                 // just arbitrarily pick the first one.
6095                 return query.get(0);
6096             }
6097         }
6098         return null;
6099     }
6100
6101     @Override
6102     public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6103             String resolvedType, int flags, int userId) {
6104         return new ParceledListSlice<>(
6105                 queryIntentServicesInternal(intent, resolvedType, flags, userId));
6106     }
6107
6108     private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6109             String resolvedType, int flags, int userId) {
6110         if (!sUserManager.exists(userId)) return Collections.emptyList();
6111         flags = updateFlagsForResolve(flags, userId, intent);
6112         ComponentName comp = intent.getComponent();
6113         if (comp == null) {
6114             if (intent.getSelector() != null) {
6115                 intent = intent.getSelector();
6116                 comp = intent.getComponent();
6117             }
6118         }
6119         if (comp != null) {
6120             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6121             final ServiceInfo si = getServiceInfo(comp, flags, userId);
6122             if (si != null) {
6123                 final ResolveInfo ri = new ResolveInfo();
6124                 ri.serviceInfo = si;
6125                 list.add(ri);
6126             }
6127             return list;
6128         }
6129
6130         // reader
6131         synchronized (mPackages) {
6132             String pkgName = intent.getPackage();
6133             if (pkgName == null) {
6134                 return mServices.queryIntent(intent, resolvedType, flags, userId);
6135             }
6136             final PackageParser.Package pkg = mPackages.get(pkgName);
6137             if (pkg != null) {
6138                 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6139                         userId);
6140             }
6141             return Collections.emptyList();
6142         }
6143     }
6144
6145     @Override
6146     public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6147             String resolvedType, int flags, int userId) {
6148         return new ParceledListSlice<>(
6149                 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6150     }
6151
6152     private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6153             Intent intent, String resolvedType, int flags, int userId) {
6154         if (!sUserManager.exists(userId)) return Collections.emptyList();
6155         flags = updateFlagsForResolve(flags, userId, intent);
6156         ComponentName comp = intent.getComponent();
6157         if (comp == null) {
6158             if (intent.getSelector() != null) {
6159                 intent = intent.getSelector();
6160                 comp = intent.getComponent();
6161             }
6162         }
6163         if (comp != null) {
6164             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6165             final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6166             if (pi != null) {
6167                 final ResolveInfo ri = new ResolveInfo();
6168                 ri.providerInfo = pi;
6169                 list.add(ri);
6170             }
6171             return list;
6172         }
6173
6174         // reader
6175         synchronized (mPackages) {
6176             String pkgName = intent.getPackage();
6177             if (pkgName == null) {
6178                 return mProviders.queryIntent(intent, resolvedType, flags, userId);
6179             }
6180             final PackageParser.Package pkg = mPackages.get(pkgName);
6181             if (pkg != null) {
6182                 return mProviders.queryIntentForPackage(
6183                         intent, resolvedType, flags, pkg.providers, userId);
6184             }
6185             return Collections.emptyList();
6186         }
6187     }
6188
6189     @Override
6190     public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6191         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6192         flags = updateFlagsForPackage(flags, userId, null);
6193         final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6194         enforceCrossUserPermission(Binder.getCallingUid(), userId,
6195                 true /* requireFullPermission */, false /* checkShell */,
6196                 "get installed packages");
6197
6198         // writer
6199         synchronized (mPackages) {
6200             ArrayList<PackageInfo> list;
6201             if (listUninstalled) {
6202                 list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6203                 for (PackageSetting ps : mSettings.mPackages.values()) {
6204                     final PackageInfo pi;
6205                     if (ps.pkg != null) {
6206                         pi = generatePackageInfo(ps, flags, userId);
6207                     } else {
6208                         pi = generatePackageInfo(ps, flags, userId);
6209                     }
6210                     if (pi != null) {
6211                         list.add(pi);
6212                     }
6213                 }
6214             } else {
6215                 list = new ArrayList<PackageInfo>(mPackages.size());
6216                 for (PackageParser.Package p : mPackages.values()) {
6217                     final PackageInfo pi =
6218                             generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6219                     if (pi != null) {
6220                         list.add(pi);
6221                     }
6222                 }
6223             }
6224
6225             return new ParceledListSlice<PackageInfo>(list);
6226         }
6227     }
6228
6229     private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6230             String[] permissions, boolean[] tmp, int flags, int userId) {
6231         int numMatch = 0;
6232         final PermissionsState permissionsState = ps.getPermissionsState();
6233         for (int i=0; i<permissions.length; i++) {
6234             final String permission = permissions[i];
6235             if (permissionsState.hasPermission(permission, userId)) {
6236                 tmp[i] = true;
6237                 numMatch++;
6238             } else {
6239                 tmp[i] = false;
6240             }
6241         }
6242         if (numMatch == 0) {
6243             return;
6244         }
6245         final PackageInfo pi;
6246         if (ps.pkg != null) {
6247             pi = generatePackageInfo(ps, flags, userId);
6248         } else {
6249             pi = generatePackageInfo(ps, flags, userId);
6250         }
6251         // The above might return null in cases of uninstalled apps or install-state
6252         // skew across users/profiles.
6253         if (pi != null) {
6254             if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6255                 if (numMatch == permissions.length) {
6256                     pi.requestedPermissions = permissions;
6257                 } else {
6258                     pi.requestedPermissions = new String[numMatch];
6259                     numMatch = 0;
6260                     for (int i=0; i<permissions.length; i++) {
6261                         if (tmp[i]) {
6262                             pi.requestedPermissions[numMatch] = permissions[i];
6263                             numMatch++;
6264                         }
6265                     }
6266                 }
6267             }
6268             list.add(pi);
6269         }
6270     }
6271
6272     @Override
6273     public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6274             String[] permissions, int flags, int userId) {
6275         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6276         flags = updateFlagsForPackage(flags, userId, permissions);
6277         final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6278
6279         // writer
6280         synchronized (mPackages) {
6281             ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6282             boolean[] tmpBools = new boolean[permissions.length];
6283             if (listUninstalled) {
6284                 for (PackageSetting ps : mSettings.mPackages.values()) {
6285                     addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6286                 }
6287             } else {
6288                 for (PackageParser.Package pkg : mPackages.values()) {
6289                     PackageSetting ps = (PackageSetting)pkg.mExtras;
6290                     if (ps != null) {
6291                         addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6292                                 userId);
6293                     }
6294                 }
6295             }
6296
6297             return new ParceledListSlice<PackageInfo>(list);
6298         }
6299     }
6300
6301     @Override
6302     public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6303         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6304         flags = updateFlagsForApplication(flags, userId, null);
6305         final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6306
6307         // writer
6308         synchronized (mPackages) {
6309             ArrayList<ApplicationInfo> list;
6310             if (listUninstalled) {
6311                 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6312                 for (PackageSetting ps : mSettings.mPackages.values()) {
6313                     ApplicationInfo ai;
6314                     if (ps.pkg != null) {
6315                         ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6316                                 ps.readUserState(userId), userId);
6317                     } else {
6318                         ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6319                     }
6320                     if (ai != null) {
6321                         list.add(ai);
6322                     }
6323                 }
6324             } else {
6325                 list = new ArrayList<ApplicationInfo>(mPackages.size());
6326                 for (PackageParser.Package p : mPackages.values()) {
6327                     if (p.mExtras != null) {
6328                         ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6329                                 ((PackageSetting)p.mExtras).readUserState(userId), userId);
6330                         if (ai != null) {
6331                             list.add(ai);
6332                         }
6333                     }
6334                 }
6335             }
6336
6337             return new ParceledListSlice<ApplicationInfo>(list);
6338         }
6339     }
6340
6341     @Override
6342     public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6343         if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6344             return null;
6345         }
6346
6347         mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6348                 "getEphemeralApplications");
6349         enforceCrossUserPermission(Binder.getCallingUid(), userId,
6350                 true /* requireFullPermission */, false /* checkShell */,
6351                 "getEphemeralApplications");
6352         synchronized (mPackages) {
6353             List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6354                     .getEphemeralApplicationsLPw(userId);
6355             if (ephemeralApps != null) {
6356                 return new ParceledListSlice<>(ephemeralApps);
6357             }
6358         }
6359         return null;
6360     }
6361
6362     @Override
6363     public boolean isEphemeralApplication(String packageName, int userId) {
6364         enforceCrossUserPermission(Binder.getCallingUid(), userId,
6365                 true /* requireFullPermission */, false /* checkShell */,
6366                 "isEphemeral");
6367         if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6368             return false;
6369         }
6370
6371         if (!isCallerSameApp(packageName)) {
6372             return false;
6373         }
6374         synchronized (mPackages) {
6375             PackageParser.Package pkg = mPackages.get(packageName);
6376             if (pkg != null) {
6377                 return pkg.applicationInfo.isEphemeralApp();
6378             }
6379         }
6380         return false;
6381     }
6382
6383     @Override
6384     public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6385         if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6386             return null;
6387         }
6388
6389         enforceCrossUserPermission(Binder.getCallingUid(), userId,
6390                 true /* requireFullPermission */, false /* checkShell */,
6391                 "getCookie");
6392         if (!isCallerSameApp(packageName)) {
6393             return null;
6394         }
6395         synchronized (mPackages) {
6396             return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6397                     packageName, userId);
6398         }
6399     }
6400
6401     @Override
6402     public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6403         if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6404             return true;
6405         }
6406
6407         enforceCrossUserPermission(Binder.getCallingUid(), userId,
6408                 true /* requireFullPermission */, true /* checkShell */,
6409                 "setCookie");
6410         if (!isCallerSameApp(packageName)) {
6411             return false;
6412         }
6413         synchronized (mPackages) {
6414             return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6415                     packageName, cookie, userId);
6416         }
6417     }
6418
6419     @Override
6420     public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6421         if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
6422             return null;
6423         }
6424
6425         mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6426                 "getEphemeralApplicationIcon");
6427         enforceCrossUserPermission(Binder.getCallingUid(), userId,
6428                 true /* requireFullPermission */, false /* checkShell */,
6429                 "getEphemeralApplicationIcon");
6430         synchronized (mPackages) {
6431             return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6432                     packageName, userId);
6433         }
6434     }
6435
6436     private boolean isCallerSameApp(String packageName) {
6437         PackageParser.Package pkg = mPackages.get(packageName);
6438         return pkg != null
6439                 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6440     }
6441
6442     @Override
6443     public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6444         return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6445     }
6446
6447     private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6448         final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6449
6450         // reader
6451         synchronized (mPackages) {
6452             final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6453             final int userId = UserHandle.getCallingUserId();
6454             while (i.hasNext()) {
6455                 final PackageParser.Package p = i.next();
6456                 if (p.applicationInfo == null) continue;
6457
6458                 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6459                         && !p.applicationInfo.isDirectBootAware();
6460                 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6461                         && p.applicationInfo.isDirectBootAware();
6462
6463                 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6464                         && (!mSafeMode || isSystemApp(p))
6465                         && (matchesUnaware || matchesAware)) {
6466                     PackageSetting ps = mSettings.mPackages.get(p.packageName);
6467                     if (ps != null) {
6468                         ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6469                                 ps.readUserState(userId), userId);
6470                         if (ai != null) {
6471                             finalList.add(ai);
6472                         }
6473                     }
6474                 }
6475             }
6476         }
6477
6478         return finalList;
6479     }
6480
6481     @Override
6482     public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6483         if (!sUserManager.exists(userId)) return null;
6484         flags = updateFlagsForComponent(flags, userId, name);
6485         // reader
6486         synchronized (mPackages) {
6487             final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6488             PackageSetting ps = provider != null
6489                     ? mSettings.mPackages.get(provider.owner.packageName)
6490                     : null;
6491             return ps != null
6492                     && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6493                     ? PackageParser.generateProviderInfo(provider, flags,
6494                             ps.readUserState(userId), userId)
6495                     : null;
6496         }
6497     }
6498
6499     /**
6500      * @deprecated
6501      */
6502     @Deprecated
6503     public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6504         // reader
6505         synchronized (mPackages) {
6506             final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6507                     .entrySet().iterator();
6508             final int userId = UserHandle.getCallingUserId();
6509             while (i.hasNext()) {
6510                 Map.Entry<String, PackageParser.Provider> entry = i.next();
6511                 PackageParser.Provider p = entry.getValue();
6512                 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6513
6514                 if (ps != null && p.syncable
6515                         && (!mSafeMode || (p.info.applicationInfo.flags
6516                                 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6517                     ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6518                             ps.readUserState(userId), userId);
6519                     if (info != null) {
6520                         outNames.add(entry.getKey());
6521                         outInfo.add(info);
6522                     }
6523                 }
6524             }
6525         }
6526     }
6527
6528     @Override
6529     public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6530             int uid, int flags) {
6531         final int userId = processName != null ? UserHandle.getUserId(uid)
6532                 : UserHandle.getCallingUserId();
6533         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6534         flags = updateFlagsForComponent(flags, userId, processName);
6535
6536         ArrayList<ProviderInfo> finalList = null;
6537         // reader
6538         synchronized (mPackages) {
6539             final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6540             while (i.hasNext()) {
6541                 final PackageParser.Provider p = i.next();
6542                 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6543                 if (ps != null && p.info.authority != null
6544                         && (processName == null
6545                                 || (p.info.processName.equals(processName)
6546                                         && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6547                         && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6548                     if (finalList == null) {
6549                         finalList = new ArrayList<ProviderInfo>(3);
6550                     }
6551                     ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6552                             ps.readUserState(userId), userId);
6553                     if (info != null) {
6554                         finalList.add(info);
6555                     }
6556                 }
6557             }
6558         }
6559
6560         if (finalList != null) {
6561             Collections.sort(finalList, mProviderInitOrderSorter);
6562             return new ParceledListSlice<ProviderInfo>(finalList);
6563         }
6564
6565         return ParceledListSlice.emptyList();
6566     }
6567
6568     @Override
6569     public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6570         // reader
6571         synchronized (mPackages) {
6572             final PackageParser.Instrumentation i = mInstrumentation.get(name);
6573             return PackageParser.generateInstrumentationInfo(i, flags);
6574         }
6575     }
6576
6577     @Override
6578     public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6579             String targetPackage, int flags) {
6580         return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6581     }
6582
6583     private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6584             int flags) {
6585         ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6586
6587         // reader
6588         synchronized (mPackages) {
6589             final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6590             while (i.hasNext()) {
6591                 final PackageParser.Instrumentation p = i.next();
6592                 if (targetPackage == null
6593                         || targetPackage.equals(p.info.targetPackage)) {
6594                     InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6595                             flags);
6596                     if (ii != null) {
6597                         finalList.add(ii);
6598                     }
6599                 }
6600             }
6601         }
6602
6603         return finalList;
6604     }
6605
6606     private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6607         ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6608         if (overlays == null) {
6609             Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6610             return;
6611         }
6612         for (PackageParser.Package opkg : overlays.values()) {
6613             // Not much to do if idmap fails: we already logged the error
6614             // and we certainly don't want to abort installation of pkg simply
6615             // because an overlay didn't fit properly. For these reasons,
6616             // ignore the return value of createIdmapForPackagePairLI.
6617             createIdmapForPackagePairLI(pkg, opkg);
6618         }
6619     }
6620
6621     private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6622             PackageParser.Package opkg) {
6623         if (!opkg.mTrustedOverlay) {
6624             Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6625                     opkg.baseCodePath + ": overlay not trusted");
6626             return false;
6627         }
6628         ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6629         if (overlaySet == null) {
6630             Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6631                     opkg.baseCodePath + " but target package has no known overlays");
6632             return false;
6633         }
6634         final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6635         // TODO: generate idmap for split APKs
6636         try {
6637             mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6638         } catch (InstallerException e) {
6639             Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6640                     + opkg.baseCodePath);
6641             return false;
6642         }
6643         PackageParser.Package[] overlayArray =
6644             overlaySet.values().toArray(new PackageParser.Package[0]);
6645         Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6646             public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6647                 return p1.mOverlayPriority - p2.mOverlayPriority;
6648             }
6649         };
6650         Arrays.sort(overlayArray, cmp);
6651
6652         pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6653         int i = 0;
6654         for (PackageParser.Package p : overlayArray) {
6655             pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6656         }
6657         return true;
6658     }
6659
6660     private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6661         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6662         try {
6663             scanDirLI(dir, parseFlags, scanFlags, currentTime);
6664         } finally {
6665             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6666         }
6667     }
6668
6669     private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6670         final File[] files = dir.listFiles();
6671         if (ArrayUtils.isEmpty(files)) {
6672             Log.d(TAG, "No files in app dir " + dir);
6673             return;
6674         }
6675
6676         if (DEBUG_PACKAGE_SCANNING) {
6677             Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6678                     + " flags=0x" + Integer.toHexString(parseFlags));
6679         }
6680
6681         for (File file : files) {
6682             final boolean isPackage = (isApkFile(file) || file.isDirectory())
6683                     && !PackageInstallerService.isStageName(file.getName());
6684             if (!isPackage) {
6685                 // Ignore entries which are not packages
6686                 continue;
6687             }
6688             try {
6689                 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6690                         scanFlags, currentTime, null);
6691             } catch (PackageManagerException e) {
6692                 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6693
6694                 // Delete invalid userdata apps
6695                 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6696                         e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6697                     logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6698                     removeCodePathLI(file);
6699                 }
6700             }
6701         }
6702     }
6703
6704     private static File getSettingsProblemFile() {
6705         File dataDir = Environment.getDataDirectory();
6706         File systemDir = new File(dataDir, "system");
6707         File fname = new File(systemDir, "uiderrors.txt");
6708         return fname;
6709     }
6710
6711     static void reportSettingsProblem(int priority, String msg) {
6712         logCriticalInfo(priority, msg);
6713     }
6714
6715     static void logCriticalInfo(int priority, String msg) {
6716         Slog.println(priority, TAG, msg);
6717         EventLogTags.writePmCriticalInfo(msg);
6718         try {
6719             File fname = getSettingsProblemFile();
6720             FileOutputStream out = new FileOutputStream(fname, true);
6721             PrintWriter pw = new FastPrintWriter(out);
6722             SimpleDateFormat formatter = new SimpleDateFormat();
6723             String dateString = formatter.format(new Date(System.currentTimeMillis()));
6724             pw.println(dateString + ": " + msg);
6725             pw.close();
6726             FileUtils.setPermissions(
6727                     fname.toString(),
6728                     FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6729                     -1, -1);
6730         } catch (java.io.IOException e) {
6731         }
6732     }
6733
6734     private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6735         if (srcFile.isDirectory()) {
6736             final File baseFile = new File(pkg.baseCodePath);
6737             long maxModifiedTime = baseFile.lastModified();
6738             if (pkg.splitCodePaths != null) {
6739                 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6740                     final File splitFile = new File(pkg.splitCodePaths[i]);
6741                     maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6742                 }
6743             }
6744             return maxModifiedTime;
6745         }
6746         return srcFile.lastModified();
6747     }
6748
6749     private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6750             final int policyFlags) throws PackageManagerException {
6751         // When upgrading from pre-N MR1, verify the package time stamp using the package
6752         // directory and not the APK file.
6753         final long lastModifiedTime = mIsPreNMR1Upgrade
6754                 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6755         if (ps != null
6756                 && ps.codePath.equals(srcFile)
6757                 && ps.timeStamp == lastModifiedTime
6758                 && !isCompatSignatureUpdateNeeded(pkg)
6759                 && !isRecoverSignatureUpdateNeeded(pkg)) {
6760             long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6761             KeySetManagerService ksms = mSettings.mKeySetManagerService;
6762             ArraySet<PublicKey> signingKs;
6763             synchronized (mPackages) {
6764                 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6765             }
6766             if (ps.signatures.mSignatures != null
6767                     && ps.signatures.mSignatures.length != 0
6768                     && signingKs != null) {
6769                 // Optimization: reuse the existing cached certificates
6770                 // if the package appears to be unchanged.
6771                 pkg.mSignatures = ps.signatures.mSignatures;
6772                 pkg.mSigningKeys = signingKs;
6773                 return;
6774             }
6775
6776             Slog.w(TAG, "PackageSetting for " + ps.name
6777                     + " is missing signatures.  Collecting certs again to recover them.");
6778         } else {
6779             Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6780         }
6781
6782         try {
6783             PackageParser.collectCertificates(pkg, policyFlags);
6784         } catch (PackageParserException e) {
6785             throw PackageManagerException.from(e);
6786         }
6787     }
6788
6789     /**
6790      *  Traces a package scan.
6791      *  @see #scanPackageLI(File, int, int, long, UserHandle)
6792      */
6793     private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6794             int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6795         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6796         try {
6797             return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6798         } finally {
6799             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6800         }
6801     }
6802
6803     /**
6804      *  Scans a package and returns the newly parsed package.
6805      *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6806      */
6807     private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6808             long currentTime, UserHandle user) throws PackageManagerException {
6809         if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6810         PackageParser pp = new PackageParser();
6811         pp.setSeparateProcesses(mSeparateProcesses);
6812         pp.setOnlyCoreApps(mOnlyCore);
6813         pp.setDisplayMetrics(mMetrics);
6814
6815         if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6816             parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6817         }
6818
6819         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6820         final PackageParser.Package pkg;
6821         try {
6822             pkg = pp.parsePackage(scanFile, parseFlags);
6823         } catch (PackageParserException e) {
6824             throw PackageManagerException.from(e);
6825         } finally {
6826             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6827         }
6828
6829         return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6830     }
6831
6832     /**
6833      *  Scans a package and returns the newly parsed package.
6834      *  @throws PackageManagerException on a parse error.
6835      */
6836     private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6837             final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6838             throws PackageManagerException {
6839         // If the package has children and this is the first dive in the function
6840         // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6841         // packages (parent and children) would be successfully scanned before the
6842         // actual scan since scanning mutates internal state and we want to atomically
6843         // install the package and its children.
6844         if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6845             if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6846                 scanFlags |= SCAN_CHECK_ONLY;
6847             }
6848         } else {
6849             scanFlags &= ~SCAN_CHECK_ONLY;
6850         }
6851
6852         // Scan the parent
6853         PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6854                 scanFlags, currentTime, user);
6855
6856         // Scan the children
6857         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6858         for (int i = 0; i < childCount; i++) {
6859             PackageParser.Package childPackage = pkg.childPackages.get(i);
6860             scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6861                     currentTime, user);
6862         }
6863
6864
6865         if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6866             return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6867         }
6868
6869         return scannedPkg;
6870     }
6871
6872     /**
6873      *  Scans a package and returns the newly parsed package.
6874      *  @throws PackageManagerException on a parse error.
6875      */
6876     private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6877             int policyFlags, int scanFlags, long currentTime, UserHandle user)
6878             throws PackageManagerException {
6879         PackageSetting ps = null;
6880         PackageSetting updatedPkg;
6881         // reader
6882         synchronized (mPackages) {
6883             // Look to see if we already know about this package.
6884             String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6885             if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6886                 // This package has been renamed to its original name.  Let's
6887                 // use that.
6888                 ps = mSettings.peekPackageLPr(oldName);
6889             }
6890             // If there was no original package, see one for the real package name.
6891             if (ps == null) {
6892                 ps = mSettings.peekPackageLPr(pkg.packageName);
6893             }
6894             // Check to see if this package could be hiding/updating a system
6895             // package.  Must look for it either under the original or real
6896             // package name depending on our state.
6897             updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6898             if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6899
6900             // If this is a package we don't know about on the system partition, we
6901             // may need to remove disabled child packages on the system partition
6902             // or may need to not add child packages if the parent apk is updated
6903             // on the data partition and no longer defines this child package.
6904             if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6905                 // If this is a parent package for an updated system app and this system
6906                 // app got an OTA update which no longer defines some of the child packages
6907                 // we have to prune them from the disabled system packages.
6908                 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6909                 if (disabledPs != null) {
6910                     final int scannedChildCount = (pkg.childPackages != null)
6911                             ? pkg.childPackages.size() : 0;
6912                     final int disabledChildCount = disabledPs.childPackageNames != null
6913                             ? disabledPs.childPackageNames.size() : 0;
6914                     for (int i = 0; i < disabledChildCount; i++) {
6915                         String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6916                         boolean disabledPackageAvailable = false;
6917                         for (int j = 0; j < scannedChildCount; j++) {
6918                             PackageParser.Package childPkg = pkg.childPackages.get(j);
6919                             if (childPkg.packageName.equals(disabledChildPackageName)) {
6920                                 disabledPackageAvailable = true;
6921                                 break;
6922                             }
6923                          }
6924                          if (!disabledPackageAvailable) {
6925                              mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6926                          }
6927                     }
6928                 }
6929             }
6930         }
6931
6932         boolean updatedPkgBetter = false;
6933         // First check if this is a system package that may involve an update
6934         if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6935             // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6936             // it needs to drop FLAG_PRIVILEGED.
6937             if (locationIsPrivileged(scanFile)) {
6938                 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6939             } else {
6940                 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6941             }
6942
6943             if (ps != null && !ps.codePath.equals(scanFile)) {
6944                 // The path has changed from what was last scanned...  check the
6945                 // version of the new path against what we have stored to determine
6946                 // what to do.
6947                 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6948                 if (pkg.mVersionCode <= ps.versionCode) {
6949                     // The system package has been updated and the code path does not match
6950                     // Ignore entry. Skip it.
6951                     if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6952                             + " ignored: updated version " + ps.versionCode
6953                             + " better than this " + pkg.mVersionCode);
6954                     if (!updatedPkg.codePath.equals(scanFile)) {
6955                         Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6956                                 + ps.name + " changing from " + updatedPkg.codePathString
6957                                 + " to " + scanFile);
6958                         updatedPkg.codePath = scanFile;
6959                         updatedPkg.codePathString = scanFile.toString();
6960                         updatedPkg.resourcePath = scanFile;
6961                         updatedPkg.resourcePathString = scanFile.toString();
6962                     }
6963                     updatedPkg.pkg = pkg;
6964                     updatedPkg.versionCode = pkg.mVersionCode;
6965
6966                     // Update the disabled system child packages to point to the package too.
6967                     final int childCount = updatedPkg.childPackageNames != null
6968                             ? updatedPkg.childPackageNames.size() : 0;
6969                     for (int i = 0; i < childCount; i++) {
6970                         String childPackageName = updatedPkg.childPackageNames.get(i);
6971                         PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6972                                 childPackageName);
6973                         if (updatedChildPkg != null) {
6974                             updatedChildPkg.pkg = pkg;
6975                             updatedChildPkg.versionCode = pkg.mVersionCode;
6976                         }
6977                     }
6978
6979                     throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6980                             + scanFile + " ignored: updated version " + ps.versionCode
6981                             + " better than this " + pkg.mVersionCode);
6982                 } else {
6983                     // The current app on the system partition is better than
6984                     // what we have updated to on the data partition; switch
6985                     // back to the system partition version.
6986                     // At this point, its safely assumed that package installation for
6987                     // apps in system partition will go through. If not there won't be a working
6988                     // version of the app
6989                     // writer
6990                     synchronized (mPackages) {
6991                         // Just remove the loaded entries from package lists.
6992                         mPackages.remove(ps.name);
6993                     }
6994
6995                     logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6996                             + " reverting from " + ps.codePathString
6997                             + ": new version " + pkg.mVersionCode
6998                             + " better than installed " + ps.versionCode);
6999
7000                     InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7001                             ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7002                     synchronized (mInstallLock) {
7003                         args.cleanUpResourcesLI();
7004                     }
7005                     synchronized (mPackages) {
7006                         mSettings.enableSystemPackageLPw(ps.name);
7007                     }
7008                     updatedPkgBetter = true;
7009                 }
7010             }
7011         }
7012
7013         if (updatedPkg != null) {
7014             // An updated system app will not have the PARSE_IS_SYSTEM flag set
7015             // initially
7016             policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7017
7018             // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7019             // flag set initially
7020             if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7021                 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7022             }
7023         }
7024
7025         // Verify certificates against what was last scanned
7026         collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7027
7028         /*
7029          * A new system app appeared, but we already had a non-system one of the
7030          * same name installed earlier.
7031          */
7032         boolean shouldHideSystemApp = false;
7033         if (updatedPkg == null && ps != null
7034                 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7035             /*
7036              * Check to make sure the signatures match first. If they don't,
7037              * wipe the installed application and its data.
7038              */
7039             if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7040                     != PackageManager.SIGNATURE_MATCH) {
7041                 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7042                         + " signatures don't match existing userdata copy; removing");
7043                 try (PackageFreezer freezer = freezePackage(pkg.packageName,
7044                         "scanPackageInternalLI")) {
7045                     deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7046                 }
7047                 ps = null;
7048             } else {
7049                 /*
7050                  * If the newly-added system app is an older version than the
7051                  * already installed version, hide it. It will be scanned later
7052                  * and re-added like an update.
7053                  */
7054                 if (pkg.mVersionCode <= ps.versionCode) {
7055                     shouldHideSystemApp = true;
7056                     logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7057                             + " but new version " + pkg.mVersionCode + " better than installed "
7058                             + ps.versionCode + "; hiding system");
7059                 } else {
7060                     /*
7061                      * The newly found system app is a newer version that the
7062                      * one previously installed. Simply remove the
7063                      * already-installed application and replace it with our own
7064                      * while keeping the application data.
7065                      */
7066                     logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7067                             + " reverting from " + ps.codePathString + ": new version "
7068                             + pkg.mVersionCode + " better than installed " + ps.versionCode);
7069                     InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7070                             ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7071                     synchronized (mInstallLock) {
7072                         args.cleanUpResourcesLI();
7073                     }
7074                 }
7075             }
7076         }
7077
7078         // The apk is forward locked (not public) if its code and resources
7079         // are kept in different files. (except for app in either system or
7080         // vendor path).
7081         // TODO grab this value from PackageSettings
7082         if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7083             if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7084                 policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7085             }
7086         }
7087
7088         // TODO: extend to support forward-locked splits
7089         String resourcePath = null;
7090         String baseResourcePath = null;
7091         if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7092             if (ps != null && ps.resourcePathString != null) {
7093                 resourcePath = ps.resourcePathString;
7094                 baseResourcePath = ps.resourcePathString;
7095             } else {
7096                 // Should not happen at all. Just log an error.
7097                 Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7098             }
7099         } else {
7100             resourcePath = pkg.codePath;
7101             baseResourcePath = pkg.baseCodePath;
7102         }
7103
7104         // Set application objects path explicitly.
7105         pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7106         pkg.setApplicationInfoCodePath(pkg.codePath);
7107         pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7108         pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7109         pkg.setApplicationInfoResourcePath(resourcePath);
7110         pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7111         pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7112
7113         // Note that we invoke the following method only if we are about to unpack an application
7114         PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7115                 | SCAN_UPDATE_SIGNATURE, currentTime, user);
7116
7117         /*
7118          * If the system app should be overridden by a previously installed
7119          * data, hide the system app now and let the /data/app scan pick it up
7120          * again.
7121          */
7122         if (shouldHideSystemApp) {
7123             synchronized (mPackages) {
7124                 mSettings.disableSystemPackageLPw(pkg.packageName, true);
7125             }
7126         }
7127
7128         return scannedPkg;
7129     }
7130
7131     private static String fixProcessName(String defProcessName,
7132             String processName, int uid) {
7133         if (processName == null) {
7134             return defProcessName;
7135         }
7136         return processName;
7137     }
7138
7139     private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7140             throws PackageManagerException {
7141         if (pkgSetting.signatures.mSignatures != null) {
7142             // Already existing package. Make sure signatures match
7143             boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7144                     == PackageManager.SIGNATURE_MATCH;
7145             if (!match) {
7146                 match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7147                         == PackageManager.SIGNATURE_MATCH;
7148             }
7149             if (!match) {
7150                 match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7151                         == PackageManager.SIGNATURE_MATCH;
7152             }
7153             if (!match) {
7154                 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7155                         + pkg.packageName + " signatures do not match the "
7156                         + "previously installed version; ignoring!");
7157             }
7158         }
7159
7160         // Check for shared user signatures
7161         if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7162             // Already existing package. Make sure signatures match
7163             boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7164                     pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7165             if (!match) {
7166                 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7167                         == PackageManager.SIGNATURE_MATCH;
7168             }
7169             if (!match) {
7170                 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7171                         == PackageManager.SIGNATURE_MATCH;
7172             }
7173             if (!match) {
7174                 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7175                         "Package " + pkg.packageName
7176                         + " has no signatures that match those in shared user "
7177                         + pkgSetting.sharedUser.name + "; ignoring!");
7178             }
7179         }
7180     }
7181
7182     /**
7183      * Enforces that only the system UID or root's UID can call a method exposed
7184      * via Binder.
7185      *
7186      * @param message used as message if SecurityException is thrown
7187      * @throws SecurityException if the caller is not system or root
7188      */
7189     private static final void enforceSystemOrRoot(String message) {
7190         final int uid = Binder.getCallingUid();
7191         if (uid != Process.SYSTEM_UID && uid != 0) {
7192             throw new SecurityException(message);
7193         }
7194     }
7195
7196     @Override
7197     public void performFstrimIfNeeded() {
7198         enforceSystemOrRoot("Only the system can request fstrim");
7199
7200         // Before everything else, see whether we need to fstrim.
7201         try {
7202             IMountService ms = PackageHelper.getMountService();
7203             if (ms != null) {
7204                 boolean doTrim = false;
7205                 final long interval = android.provider.Settings.Global.getLong(
7206                         mContext.getContentResolver(),
7207                         android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7208                         DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7209                 if (interval > 0) {
7210                     final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7211                     if (timeSinceLast > interval) {
7212                         doTrim = true;
7213                         Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7214                                 + "; running immediately");
7215                     }
7216                 }
7217                 if (doTrim) {
7218                     final boolean dexOptDialogShown;
7219                     synchronized (mPackages) {
7220                         dexOptDialogShown = mDexOptDialogShown;
7221                     }
7222                     if (!isFirstBoot() && dexOptDialogShown) {
7223                         try {
7224                             ActivityManagerNative.getDefault().showBootMessage(
7225                                     mContext.getResources().getString(
7226                                             R.string.android_upgrading_fstrim), true);
7227                         } catch (RemoteException e) {
7228                         }
7229                     }
7230                     ms.runMaintenance();
7231                 }
7232             } else {
7233                 Slog.e(TAG, "Mount service unavailable!");
7234             }
7235         } catch (RemoteException e) {
7236             // Can't happen; MountService is local
7237         }
7238     }
7239
7240     @Override
7241     public void updatePackagesIfNeeded() {
7242         enforceSystemOrRoot("Only the system can request package update");
7243
7244         // We need to re-extract after an OTA.
7245         boolean causeUpgrade = isUpgrade();
7246
7247         // First boot or factory reset.
7248         // Note: we also handle devices that are upgrading to N right now as if it is their
7249         //       first boot, as they do not have profile data.
7250         boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7251
7252         // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7253         boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7254
7255         if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7256             return;
7257         }
7258
7259         List<PackageParser.Package> pkgs;
7260         synchronized (mPackages) {
7261             pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7262         }
7263
7264         final long startTime = System.nanoTime();
7265         final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7266                     getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7267
7268         final int elapsedTimeSeconds =
7269                 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7270
7271         MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7272         MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7273         MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7274         MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7275         MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7276     }
7277
7278     /**
7279      * Performs dexopt on the set of packages in {@code packages} and returns an int array
7280      * containing statistics about the invocation. The array consists of three elements,
7281      * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7282      * and {@code numberOfPackagesFailed}.
7283      */
7284     private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7285             String compilerFilter) {
7286
7287         int numberOfPackagesVisited = 0;
7288         int numberOfPackagesOptimized = 0;
7289         int numberOfPackagesSkipped = 0;
7290         int numberOfPackagesFailed = 0;
7291         final int numberOfPackagesToDexopt = pkgs.size();
7292
7293         for (PackageParser.Package pkg : pkgs) {
7294             numberOfPackagesVisited++;
7295
7296             if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7297                 if (DEBUG_DEXOPT) {
7298                     Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7299                 }
7300                 numberOfPackagesSkipped++;
7301                 continue;
7302             }
7303
7304             if (DEBUG_DEXOPT) {
7305                 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7306                         numberOfPackagesToDexopt + ": " + pkg.packageName);
7307             }
7308
7309             if (showDialog) {
7310                 try {
7311                     ActivityManagerNative.getDefault().showBootMessage(
7312                             mContext.getResources().getString(R.string.android_upgrading_apk,
7313                                     numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7314                 } catch (RemoteException e) {
7315                 }
7316                 synchronized (mPackages) {
7317                     mDexOptDialogShown = true;
7318                 }
7319             }
7320
7321             // If the OTA updates a system app which was previously preopted to a non-preopted state
7322             // the app might end up being verified at runtime. That's because by default the apps
7323             // are verify-profile but for preopted apps there's no profile.
7324             // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7325             // that before the OTA the app was preopted) the app gets compiled with a non-profile
7326             // filter (by default interpret-only).
7327             // Note that at this stage unused apps are already filtered.
7328             if (isSystemApp(pkg) &&
7329                     DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7330                     !Environment.getReferenceProfile(pkg.packageName).exists()) {
7331                 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7332             }
7333
7334             // checkProfiles is false to avoid merging profiles during boot which
7335             // might interfere with background compilation (b/28612421).
7336             // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7337             // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7338             // trade-off worth doing to save boot time work.
7339             int dexOptStatus = performDexOptTraced(pkg.packageName,
7340                     false /* checkProfiles */,
7341                     compilerFilter,
7342                     false /* force */);
7343             switch (dexOptStatus) {
7344                 case PackageDexOptimizer.DEX_OPT_PERFORMED:
7345                     numberOfPackagesOptimized++;
7346                     break;
7347                 case PackageDexOptimizer.DEX_OPT_SKIPPED:
7348                     numberOfPackagesSkipped++;
7349                     break;
7350                 case PackageDexOptimizer.DEX_OPT_FAILED:
7351                     numberOfPackagesFailed++;
7352                     break;
7353                 default:
7354                     Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7355                     break;
7356             }
7357         }
7358
7359         return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7360                 numberOfPackagesFailed };
7361     }
7362
7363     @Override
7364     public void notifyPackageUse(String packageName, int reason) {
7365         synchronized (mPackages) {
7366             PackageParser.Package p = mPackages.get(packageName);
7367             if (p == null) {
7368                 return;
7369             }
7370             p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7371         }
7372     }
7373
7374     // TODO: this is not used nor needed. Delete it.
7375     @Override
7376     public boolean performDexOptIfNeeded(String packageName) {
7377         int dexOptStatus = performDexOptTraced(packageName,
7378                 false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7379         return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7380     }
7381
7382     @Override
7383     public boolean performDexOpt(String packageName,
7384             boolean checkProfiles, int compileReason, boolean force) {
7385         int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7386                 getCompilerFilterForReason(compileReason), force);
7387         return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7388     }
7389
7390     @Override
7391     public boolean performDexOptMode(String packageName,
7392             boolean checkProfiles, String targetCompilerFilter, boolean force) {
7393         int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7394                 targetCompilerFilter, force);
7395         return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7396     }
7397
7398     private int performDexOptTraced(String packageName,
7399                 boolean checkProfiles, String targetCompilerFilter, boolean force) {
7400         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7401         try {
7402             return performDexOptInternal(packageName, checkProfiles,
7403                     targetCompilerFilter, force);
7404         } finally {
7405             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7406         }
7407     }
7408
7409     // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7410     // if the package can now be considered up to date for the given filter.
7411     private int performDexOptInternal(String packageName,
7412                 boolean checkProfiles, String targetCompilerFilter, boolean force) {
7413         PackageParser.Package p;
7414         synchronized (mPackages) {
7415             p = mPackages.get(packageName);
7416             if (p == null) {
7417                 // Package could not be found. Report failure.
7418                 return PackageDexOptimizer.DEX_OPT_FAILED;
7419             }
7420             mPackageUsage.maybeWriteAsync(mPackages);
7421             mCompilerStats.maybeWriteAsync();
7422         }
7423         long callingId = Binder.clearCallingIdentity();
7424         try {
7425             synchronized (mInstallLock) {
7426                 return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7427                         targetCompilerFilter, force);
7428             }
7429         } finally {
7430             Binder.restoreCallingIdentity(callingId);
7431         }
7432     }
7433
7434     public ArraySet<String> getOptimizablePackages() {
7435         ArraySet<String> pkgs = new ArraySet<String>();
7436         synchronized (mPackages) {
7437             for (PackageParser.Package p : mPackages.values()) {
7438                 if (PackageDexOptimizer.canOptimizePackage(p)) {
7439                     pkgs.add(p.packageName);
7440                 }
7441             }
7442         }
7443         return pkgs;
7444     }
7445
7446     private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7447             boolean checkProfiles, String targetCompilerFilter,
7448             boolean force) {
7449         // Select the dex optimizer based on the force parameter.
7450         // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7451         //       allocate an object here.
7452         PackageDexOptimizer pdo = force
7453                 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7454                 : mPackageDexOptimizer;
7455
7456         // Optimize all dependencies first. Note: we ignore the return value and march on
7457         // on errors.
7458         Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7459         final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7460         if (!deps.isEmpty()) {
7461             for (PackageParser.Package depPackage : deps) {
7462                 // TODO: Analyze and investigate if we (should) profile libraries.
7463                 // Currently this will do a full compilation of the library by default.
7464                 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7465                         false /* checkProfiles */,
7466                         getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7467                         getOrCreateCompilerPackageStats(depPackage));
7468             }
7469         }
7470         return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7471                 targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7472     }
7473
7474     Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7475         if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7476             ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7477             Set<String> collectedNames = new HashSet<>();
7478             findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7479
7480             retValue.remove(p);
7481
7482             return retValue;
7483         } else {
7484             return Collections.emptyList();
7485         }
7486     }
7487
7488     private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7489             Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7490         if (!collectedNames.contains(p.packageName)) {
7491             collectedNames.add(p.packageName);
7492             collected.add(p);
7493
7494             if (p.usesLibraries != null) {
7495                 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7496             }
7497             if (p.usesOptionalLibraries != null) {
7498                 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7499                         collectedNames);
7500             }
7501         }
7502     }
7503
7504     private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7505             Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7506         for (String libName : libs) {
7507             PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7508             if (libPkg != null) {
7509                 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7510             }
7511         }
7512     }
7513
7514     private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7515         synchronized (mPackages) {
7516             PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7517             if (lib != null && lib.apk != null) {
7518                 return mPackages.get(lib.apk);
7519             }
7520         }
7521         return null;
7522     }
7523
7524     public void shutdown() {
7525         mPackageUsage.writeNow(mPackages);
7526         mCompilerStats.writeNow();
7527     }
7528
7529     @Override
7530     public void dumpProfiles(String packageName) {
7531         PackageParser.Package pkg;
7532         synchronized (mPackages) {
7533             pkg = mPackages.get(packageName);
7534             if (pkg == null) {
7535                 throw new IllegalArgumentException("Unknown package: " + packageName);
7536             }
7537         }
7538         /* Only the shell, root, or the app user should be able to dump profiles. */
7539         int callingUid = Binder.getCallingUid();
7540         if (callingUid != Process.SHELL_UID &&
7541             callingUid != Process.ROOT_UID &&
7542             callingUid != pkg.applicationInfo.uid) {
7543             throw new SecurityException("dumpProfiles");
7544         }
7545
7546         synchronized (mInstallLock) {
7547             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7548             final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7549             try {
7550                 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7551                 String gid = Integer.toString(sharedGid);
7552                 String codePaths = TextUtils.join(";", allCodePaths);
7553                 mInstaller.dumpProfiles(gid, packageName, codePaths);
7554             } catch (InstallerException e) {
7555                 Slog.w(TAG, "Failed to dump profiles", e);
7556             }
7557             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7558         }
7559     }
7560
7561     @Override
7562     public void forceDexOpt(String packageName) {
7563         enforceSystemOrRoot("forceDexOpt");
7564
7565         PackageParser.Package pkg;
7566         synchronized (mPackages) {
7567             pkg = mPackages.get(packageName);
7568             if (pkg == null) {
7569                 throw new IllegalArgumentException("Unknown package: " + packageName);
7570             }
7571         }
7572
7573         synchronized (mInstallLock) {
7574             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7575
7576             // Whoever is calling forceDexOpt wants a fully compiled package.
7577             // Don't use profiles since that may cause compilation to be skipped.
7578             final int res = performDexOptInternalWithDependenciesLI(pkg,
7579                     false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7580                     true /* force */);
7581
7582             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7583             if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7584                 throw new IllegalStateException("Failed to dexopt: " + res);
7585             }
7586         }
7587     }
7588
7589     private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7590         if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7591             Slog.w(TAG, "Unable to update from " + oldPkg.name
7592                     + " to " + newPkg.packageName
7593                     + ": old package not in system partition");
7594             return false;
7595         } else if (mPackages.get(oldPkg.name) != null) {
7596             Slog.w(TAG, "Unable to update from " + oldPkg.name
7597                     + " to " + newPkg.packageName
7598                     + ": old package still exists");
7599             return false;
7600         }
7601         return true;
7602     }
7603
7604     void removeCodePathLI(File codePath) {
7605         if (codePath.isDirectory()) {
7606             try {
7607                 mInstaller.rmPackageDir(codePath.getAbsolutePath());
7608             } catch (InstallerException e) {
7609                 Slog.w(TAG, "Failed to remove code path", e);
7610             }
7611         } else {
7612             codePath.delete();
7613         }
7614     }
7615
7616     private int[] resolveUserIds(int userId) {
7617         return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7618     }
7619
7620     private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7621         if (pkg == null) {
7622             Slog.wtf(TAG, "Package was null!", new Throwable());
7623             return;
7624         }
7625         clearAppDataLeafLIF(pkg, userId, flags);
7626         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7627         for (int i = 0; i < childCount; i++) {
7628             clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7629         }
7630     }
7631
7632     private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7633         final PackageSetting ps;
7634         synchronized (mPackages) {
7635             ps = mSettings.mPackages.get(pkg.packageName);
7636         }
7637         for (int realUserId : resolveUserIds(userId)) {
7638             final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7639             try {
7640                 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7641                         ceDataInode);
7642             } catch (InstallerException e) {
7643                 Slog.w(TAG, String.valueOf(e));
7644             }
7645         }
7646     }
7647
7648     private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7649         if (pkg == null) {
7650             Slog.wtf(TAG, "Package was null!", new Throwable());
7651             return;
7652         }
7653         destroyAppDataLeafLIF(pkg, userId, flags);
7654         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7655         for (int i = 0; i < childCount; i++) {
7656             destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7657         }
7658     }
7659
7660     private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7661         final PackageSetting ps;
7662         synchronized (mPackages) {
7663             ps = mSettings.mPackages.get(pkg.packageName);
7664         }
7665         for (int realUserId : resolveUserIds(userId)) {
7666             final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7667             try {
7668                 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7669                         ceDataInode);
7670             } catch (InstallerException e) {
7671                 Slog.w(TAG, String.valueOf(e));
7672             }
7673         }
7674     }
7675
7676     private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7677         if (pkg == null) {
7678             Slog.wtf(TAG, "Package was null!", new Throwable());
7679             return;
7680         }
7681         destroyAppProfilesLeafLIF(pkg);
7682         destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7683         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7684         for (int i = 0; i < childCount; i++) {
7685             destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7686             destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7687                     true /* removeBaseMarker */);
7688         }
7689     }
7690
7691     private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7692             boolean removeBaseMarker) {
7693         if (pkg.isForwardLocked()) {
7694             return;
7695         }
7696
7697         for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7698             try {
7699                 path = PackageManagerServiceUtils.realpath(new File(path));
7700             } catch (IOException e) {
7701                 // TODO: Should we return early here ?
7702                 Slog.w(TAG, "Failed to get canonical path", e);
7703                 continue;
7704             }
7705
7706             final String useMarker = path.replace('/', '@');
7707             for (int realUserId : resolveUserIds(userId)) {
7708                 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7709                 if (removeBaseMarker) {
7710                     File foreignUseMark = new File(profileDir, useMarker);
7711                     if (foreignUseMark.exists()) {
7712                         if (!foreignUseMark.delete()) {
7713                             Slog.w(TAG, "Unable to delete foreign user mark for package: "
7714                                     + pkg.packageName);
7715                         }
7716                     }
7717                 }
7718
7719                 File[] markers = profileDir.listFiles();
7720                 if (markers != null) {
7721                     final String searchString = "@" + pkg.packageName + "@";
7722                     // We also delete all markers that contain the package name we're
7723                     // uninstalling. These are associated with secondary dex-files belonging
7724                     // to the package. Reconstructing the path of these dex files is messy
7725                     // in general.
7726                     for (File marker : markers) {
7727                         if (marker.getName().indexOf(searchString) > 0) {
7728                             if (!marker.delete()) {
7729                                 Slog.w(TAG, "Unable to delete foreign user mark for package: "
7730                                     + pkg.packageName);
7731                             }
7732                         }
7733                     }
7734                 }
7735             }
7736         }
7737     }
7738
7739     private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7740         try {
7741             mInstaller.destroyAppProfiles(pkg.packageName);
7742         } catch (InstallerException e) {
7743             Slog.w(TAG, String.valueOf(e));
7744         }
7745     }
7746
7747     private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7748         if (pkg == null) {
7749             Slog.wtf(TAG, "Package was null!", new Throwable());
7750             return;
7751         }
7752         clearAppProfilesLeafLIF(pkg);
7753         // We don't remove the base foreign use marker when clearing profiles because
7754         // we will rename it when the app is updated. Unlike the actual profile contents,
7755         // the foreign use marker is good across installs.
7756         destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7757         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7758         for (int i = 0; i < childCount; i++) {
7759             clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7760         }
7761     }
7762
7763     private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7764         try {
7765             mInstaller.clearAppProfiles(pkg.packageName);
7766         } catch (InstallerException e) {
7767             Slog.w(TAG, String.valueOf(e));
7768         }
7769     }
7770
7771     private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7772             long lastUpdateTime) {
7773         // Set parent install/update time
7774         PackageSetting ps = (PackageSetting) pkg.mExtras;
7775         if (ps != null) {
7776             ps.firstInstallTime = firstInstallTime;
7777             ps.lastUpdateTime = lastUpdateTime;
7778         }
7779         // Set children install/update time
7780         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7781         for (int i = 0; i < childCount; i++) {
7782             PackageParser.Package childPkg = pkg.childPackages.get(i);
7783             ps = (PackageSetting) childPkg.mExtras;
7784             if (ps != null) {
7785                 ps.firstInstallTime = firstInstallTime;
7786                 ps.lastUpdateTime = lastUpdateTime;
7787             }
7788         }
7789     }
7790
7791     private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7792             PackageParser.Package changingLib) {
7793         if (file.path != null) {
7794             usesLibraryFiles.add(file.path);
7795             return;
7796         }
7797         PackageParser.Package p = mPackages.get(file.apk);
7798         if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7799             // If we are doing this while in the middle of updating a library apk,
7800             // then we need to make sure to use that new apk for determining the
7801             // dependencies here.  (We haven't yet finished committing the new apk
7802             // to the package manager state.)
7803             if (p == null || p.packageName.equals(changingLib.packageName)) {
7804                 p = changingLib;
7805             }
7806         }
7807         if (p != null) {
7808             usesLibraryFiles.addAll(p.getAllCodePaths());
7809         }
7810     }
7811
7812     private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7813             PackageParser.Package changingLib) throws PackageManagerException {
7814         if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7815             final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7816             int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7817             for (int i=0; i<N; i++) {
7818                 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7819                 if (file == null) {
7820                     throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7821                             "Package " + pkg.packageName + " requires unavailable shared library "
7822                             + pkg.usesLibraries.get(i) + "; failing!");
7823                 }
7824                 addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7825             }
7826             N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7827             for (int i=0; i<N; i++) {
7828                 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7829                 if (file == null) {
7830                     Slog.w(TAG, "Package " + pkg.packageName
7831                             + " desires unavailable shared library "
7832                             + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7833                 } else {
7834                     addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7835                 }
7836             }
7837             N = usesLibraryFiles.size();
7838             if (N > 0) {
7839                 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7840             } else {
7841                 pkg.usesLibraryFiles = null;
7842             }
7843         }
7844     }
7845
7846     private static boolean hasString(List<String> list, List<String> which) {
7847         if (list == null) {
7848             return false;
7849         }
7850         for (int i=list.size()-1; i>=0; i--) {
7851             for (int j=which.size()-1; j>=0; j--) {
7852                 if (which.get(j).equals(list.get(i))) {
7853                     return true;
7854                 }
7855             }
7856         }
7857         return false;
7858     }
7859
7860     private void updateAllSharedLibrariesLPw() {
7861         for (PackageParser.Package pkg : mPackages.values()) {
7862             try {
7863                 updateSharedLibrariesLPw(pkg, null);
7864             } catch (PackageManagerException e) {
7865                 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7866             }
7867         }
7868     }
7869
7870     private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7871             PackageParser.Package changingPkg) {
7872         ArrayList<PackageParser.Package> res = null;
7873         for (PackageParser.Package pkg : mPackages.values()) {
7874             if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7875                     || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7876                 if (res == null) {
7877                     res = new ArrayList<PackageParser.Package>();
7878                 }
7879                 res.add(pkg);
7880                 try {
7881                     updateSharedLibrariesLPw(pkg, changingPkg);
7882                 } catch (PackageManagerException e) {
7883                     Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7884                 }
7885             }
7886         }
7887         return res;
7888     }
7889
7890     /**
7891      * Derive the value of the {@code cpuAbiOverride} based on the provided
7892      * value and an optional stored value from the package settings.
7893      */
7894     private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7895         String cpuAbiOverride = null;
7896
7897         if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7898             cpuAbiOverride = null;
7899         } else if (abiOverride != null) {
7900             cpuAbiOverride = abiOverride;
7901         } else if (settings != null) {
7902             cpuAbiOverride = settings.cpuAbiOverrideString;
7903         }
7904
7905         return cpuAbiOverride;
7906     }
7907
7908     private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7909             final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7910                     throws PackageManagerException {
7911         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7912         // If the package has children and this is the first dive in the function
7913         // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7914         // whether all packages (parent and children) would be successfully scanned
7915         // before the actual scan since scanning mutates internal state and we want
7916         // to atomically install the package and its children.
7917         if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7918             if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7919                 scanFlags |= SCAN_CHECK_ONLY;
7920             }
7921         } else {
7922             scanFlags &= ~SCAN_CHECK_ONLY;
7923         }
7924
7925         final PackageParser.Package scannedPkg;
7926         try {
7927             // Scan the parent
7928             scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7929             // Scan the children
7930             final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7931             for (int i = 0; i < childCount; i++) {
7932                 PackageParser.Package childPkg = pkg.childPackages.get(i);
7933                 scanPackageLI(childPkg, policyFlags,
7934                         scanFlags, currentTime, user);
7935             }
7936         } finally {
7937             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7938         }
7939
7940         if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7941             return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7942         }
7943
7944         return scannedPkg;
7945     }
7946
7947     private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7948             int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7949         boolean success = false;
7950         try {
7951             final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7952                     currentTime, user);
7953             success = true;
7954             return res;
7955         } finally {
7956             if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7957                 // DELETE_DATA_ON_FAILURES is only used by frozen paths
7958                 destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7959                         StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7960                 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7961             }
7962         }
7963     }
7964
7965     /**
7966      * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7967      */
7968     private static boolean apkHasCode(String fileName) {
7969         StrictJarFile jarFile = null;
7970         try {
7971             jarFile = new StrictJarFile(fileName,
7972                     false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7973             return jarFile.findEntry("classes.dex") != null;
7974         } catch (IOException ignore) {
7975         } finally {
7976             try {
7977                 if (jarFile != null) {
7978                     jarFile.close();
7979                 }
7980             } catch (IOException ignore) {}
7981         }
7982         return false;
7983     }
7984
7985     /**
7986      * Enforces code policy for the package. This ensures that if an APK has
7987      * declared hasCode="true" in its manifest that the APK actually contains
7988      * code.
7989      *
7990      * @throws PackageManagerException If bytecode could not be found when it should exist
7991      */
7992     private static void enforceCodePolicy(PackageParser.Package pkg)
7993             throws PackageManagerException {
7994         final boolean shouldHaveCode =
7995                 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7996         if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7997             throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7998                     "Package " + pkg.baseCodePath + " code is missing");
7999         }
8000
8001         if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8002             for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8003                 final boolean splitShouldHaveCode =
8004                         (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8005                 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8006                     throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8007                             "Package " + pkg.splitCodePaths[i] + " code is missing");
8008                 }
8009             }
8010         }
8011     }
8012
8013     private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8014             final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8015             throws PackageManagerException {
8016         final File scanFile = new File(pkg.codePath);
8017         if (pkg.applicationInfo.getCodePath() == null ||
8018                 pkg.applicationInfo.getResourcePath() == null) {
8019             // Bail out. The resource and code paths haven't been set.
8020             throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8021                     "Code and resource paths haven't been set correctly");
8022         }
8023
8024         // Apply policy
8025         if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8026             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8027             if (pkg.applicationInfo.isDirectBootAware()) {
8028                 // we're direct boot aware; set for all components
8029                 for (PackageParser.Service s : pkg.services) {
8030                     s.info.encryptionAware = s.info.directBootAware = true;
8031                 }
8032                 for (PackageParser.Provider p : pkg.providers) {
8033                     p.info.encryptionAware = p.info.directBootAware = true;
8034                 }
8035                 for (PackageParser.Activity a : pkg.activities) {
8036                     a.info.encryptionAware = a.info.directBootAware = true;
8037                 }
8038                 for (PackageParser.Activity r : pkg.receivers) {
8039                     r.info.encryptionAware = r.info.directBootAware = true;
8040                 }
8041             }
8042         } else {
8043             // Only allow system apps to be flagged as core apps.
8044             pkg.coreApp = false;
8045             // clear flags not applicable to regular apps
8046             pkg.applicationInfo.privateFlags &=
8047                     ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8048             pkg.applicationInfo.privateFlags &=
8049                     ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8050         }
8051         pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8052
8053         if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8054             pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8055         }
8056
8057         if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8058             enforceCodePolicy(pkg);
8059         }
8060
8061         if (mCustomResolverComponentName != null &&
8062                 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8063             setUpCustomResolverActivity(pkg);
8064         }
8065
8066         if (pkg.packageName.equals("android")) {
8067             synchronized (mPackages) {
8068                 if (mAndroidApplication != null) {
8069                     Slog.w(TAG, "*************************************************");
8070                     Slog.w(TAG, "Core android package being redefined.  Skipping.");
8071                     Slog.w(TAG, " file=" + scanFile);
8072                     Slog.w(TAG, "*************************************************");
8073                     throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8074                             "Core android package being redefined.  Skipping.");
8075                 }
8076
8077                 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8078                     // Set up information for our fall-back user intent resolution activity.
8079                     mPlatformPackage = pkg;
8080                     pkg.mVersionCode = mSdkVersion;
8081                     mAndroidApplication = pkg.applicationInfo;
8082
8083                     if (!mResolverReplaced) {
8084                         mResolveActivity.applicationInfo = mAndroidApplication;
8085                         mResolveActivity.name = ResolverActivity.class.getName();
8086                         mResolveActivity.packageName = mAndroidApplication.packageName;
8087                         mResolveActivity.processName = "system:ui";
8088                         mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8089                         mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8090                         mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8091                         mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8092                         mResolveActivity.exported = true;
8093                         mResolveActivity.enabled = true;
8094                         mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8095                         mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8096                                 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8097                                 | ActivityInfo.CONFIG_SCREEN_LAYOUT
8098                                 | ActivityInfo.CONFIG_ORIENTATION
8099                                 | ActivityInfo.CONFIG_KEYBOARD
8100                                 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8101                         mResolveInfo.activityInfo = mResolveActivity;
8102                         mResolveInfo.priority = 0;
8103                         mResolveInfo.preferredOrder = 0;
8104                         mResolveInfo.match = 0;
8105                         mResolveComponentName = new ComponentName(
8106                                 mAndroidApplication.packageName, mResolveActivity.name);
8107                     }
8108                 }
8109             }
8110         }
8111
8112         if (DEBUG_PACKAGE_SCANNING) {
8113             if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8114                 Log.d(TAG, "Scanning package " + pkg.packageName);
8115         }
8116
8117         synchronized (mPackages) {
8118             if (mPackages.containsKey(pkg.packageName)
8119                     || mSharedLibraries.containsKey(pkg.packageName)) {
8120                 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8121                         "Application package " + pkg.packageName
8122                                 + " already installed.  Skipping duplicate.");
8123             }
8124
8125             // If we're only installing presumed-existing packages, require that the
8126             // scanned APK is both already known and at the path previously established
8127             // for it.  Previously unknown packages we pick up normally, but if we have an
8128             // a priori expectation about this package's install presence, enforce it.
8129             // With a singular exception for new system packages. When an OTA contains
8130             // a new system package, we allow the codepath to change from a system location
8131             // to the user-installed location. If we don't allow this change, any newer,
8132             // user-installed version of the application will be ignored.
8133             if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8134                 if (mExpectingBetter.containsKey(pkg.packageName)) {
8135                     logCriticalInfo(Log.WARN,
8136                             "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8137                 } else {
8138                     PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8139                     if (known != null) {
8140                         if (DEBUG_PACKAGE_SCANNING) {
8141                             Log.d(TAG, "Examining " + pkg.codePath
8142                                     + " and requiring known paths " + known.codePathString
8143                                     + " & " + known.resourcePathString);
8144                         }
8145                         if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8146                                 || !pkg.applicationInfo.getResourcePath().equals(
8147                                 known.resourcePathString)) {
8148                             throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8149                                     "Application package " + pkg.packageName
8150                                             + " found at " + pkg.applicationInfo.getCodePath()
8151                                             + " but expected at " + known.codePathString
8152                                             + "; ignoring.");
8153                         }
8154                     }
8155                 }
8156             }
8157         }
8158
8159         // Initialize package source and resource directories
8160         File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8161         File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8162
8163         SharedUserSetting suid = null;
8164         PackageSetting pkgSetting = null;
8165
8166         if (!isSystemApp(pkg)) {
8167             // Only system apps can use these features.
8168             pkg.mOriginalPackages = null;
8169             pkg.mRealPackage = null;
8170             pkg.mAdoptPermissions = null;
8171         }
8172
8173         // Getting the package setting may have a side-effect, so if we
8174         // are only checking if scan would succeed, stash a copy of the
8175         // old setting to restore at the end.
8176         PackageSetting nonMutatedPs = null;
8177
8178         // writer
8179         synchronized (mPackages) {
8180             if (pkg.mSharedUserId != null) {
8181                 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8182                 if (suid == null) {
8183                     throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8184                             "Creating application package " + pkg.packageName
8185                             + " for shared user failed");
8186                 }
8187                 if (DEBUG_PACKAGE_SCANNING) {
8188                     if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8189                         Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8190                                 + "): packages=" + suid.packages);
8191                 }
8192             }
8193
8194             // Check if we are renaming from an original package name.
8195             PackageSetting origPackage = null;
8196             String realName = null;
8197             if (pkg.mOriginalPackages != null) {
8198                 // This package may need to be renamed to a previously
8199                 // installed name.  Let's check on that...
8200                 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8201                 if (pkg.mOriginalPackages.contains(renamed)) {
8202                     // This package had originally been installed as the
8203                     // original name, and we have already taken care of
8204                     // transitioning to the new one.  Just update the new
8205                     // one to continue using the old name.
8206                     realName = pkg.mRealPackage;
8207                     if (!pkg.packageName.equals(renamed)) {
8208                         // Callers into this function may have already taken
8209                         // care of renaming the package; only do it here if
8210                         // it is not already done.
8211                         pkg.setPackageName(renamed);
8212                     }
8213
8214                 } else {
8215                     for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8216                         if ((origPackage = mSettings.peekPackageLPr(
8217                                 pkg.mOriginalPackages.get(i))) != null) {
8218                             // We do have the package already installed under its
8219                             // original name...  should we use it?
8220                             if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8221                                 // New package is not compatible with original.
8222                                 origPackage = null;
8223                                 continue;
8224                             } else if (origPackage.sharedUser != null) {
8225                                 // Make sure uid is compatible between packages.
8226                                 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8227                                     Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8228                                             + " to " + pkg.packageName + ": old uid "
8229                                             + origPackage.sharedUser.name
8230                                             + " differs from " + pkg.mSharedUserId);
8231                                     origPackage = null;
8232                                     continue;
8233                                 }
8234                                 // TODO: Add case when shared user id is added [b/28144775]
8235                             } else {
8236                                 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8237                                         + pkg.packageName + " to old name " + origPackage.name);
8238                             }
8239                             break;
8240                         }
8241                     }
8242                 }
8243             }
8244
8245             if (mTransferedPackages.contains(pkg.packageName)) {
8246                 Slog.w(TAG, "Package " + pkg.packageName
8247                         + " was transferred to another, but its .apk remains");
8248             }
8249
8250             // See comments in nonMutatedPs declaration
8251             if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8252                 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8253                 if (foundPs != null) {
8254                     nonMutatedPs = new PackageSetting(foundPs);
8255                 }
8256             }
8257
8258             // Just create the setting, don't add it yet. For already existing packages
8259             // the PkgSetting exists already and doesn't have to be created.
8260             pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8261                     destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8262                     pkg.applicationInfo.primaryCpuAbi,
8263                     pkg.applicationInfo.secondaryCpuAbi,
8264                     pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8265                     user, false);
8266             if (pkgSetting == null) {
8267                 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8268                         "Creating application package " + pkg.packageName + " failed");
8269             }
8270
8271             if (pkgSetting.origPackage != null) {
8272                 // If we are first transitioning from an original package,
8273                 // fix up the new package's name now.  We need to do this after
8274                 // looking up the package under its new name, so getPackageLP
8275                 // can take care of fiddling things correctly.
8276                 pkg.setPackageName(origPackage.name);
8277
8278                 // File a report about this.
8279                 String msg = "New package " + pkgSetting.realName
8280                         + " renamed to replace old package " + pkgSetting.name;
8281                 reportSettingsProblem(Log.WARN, msg);
8282
8283                 // Make a note of it.
8284                 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8285                     mTransferedPackages.add(origPackage.name);
8286                 }
8287
8288                 // No longer need to retain this.
8289                 pkgSetting.origPackage = null;
8290             }
8291
8292             if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8293                 // Make a note of it.
8294                 mTransferedPackages.add(pkg.packageName);
8295             }
8296
8297             if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8298                 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8299             }
8300
8301             if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8302                 // Check all shared libraries and map to their actual file path.
8303                 // We only do this here for apps not on a system dir, because those
8304                 // are the only ones that can fail an install due to this.  We
8305                 // will take care of the system apps by updating all of their
8306                 // library paths after the scan is done.
8307                 updateSharedLibrariesLPw(pkg, null);
8308             }
8309
8310             if (mFoundPolicyFile) {
8311                 SELinuxMMAC.assignSeinfoValue(pkg);
8312             }
8313
8314             pkg.applicationInfo.uid = pkgSetting.appId;
8315             pkg.mExtras = pkgSetting;
8316             if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8317                 if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8318                     // We just determined the app is signed correctly, so bring
8319                     // over the latest parsed certs.
8320                     pkgSetting.signatures.mSignatures = pkg.mSignatures;
8321                 } else {
8322                     if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8323                         throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8324                                 "Package " + pkg.packageName + " upgrade keys do not match the "
8325                                 + "previously installed version");
8326                     } else {
8327                         pkgSetting.signatures.mSignatures = pkg.mSignatures;
8328                         String msg = "System package " + pkg.packageName
8329                             + " signature changed; retaining data.";
8330                         reportSettingsProblem(Log.WARN, msg);
8331                     }
8332                 }
8333             } else {
8334                 try {
8335                     verifySignaturesLP(pkgSetting, pkg);
8336                     // We just determined the app is signed correctly, so bring
8337                     // over the latest parsed certs.
8338                     pkgSetting.signatures.mSignatures = pkg.mSignatures;
8339                 } catch (PackageManagerException e) {
8340                     if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8341                         throw e;
8342                     }
8343                     // The signature has changed, but this package is in the system
8344                     // image...  let's recover!
8345                     pkgSetting.signatures.mSignatures = pkg.mSignatures;
8346                     // However...  if this package is part of a shared user, but it
8347                     // doesn't match the signature of the shared user, let's fail.
8348                     // What this means is that you can't change the signatures
8349                     // associated with an overall shared user, which doesn't seem all
8350                     // that unreasonable.
8351                     if (pkgSetting.sharedUser != null) {
8352                         if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8353                                               pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8354                             throw new PackageManagerException(
8355                                     INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8356                                             "Signature mismatch for shared user: "
8357                                             + pkgSetting.sharedUser);
8358                         }
8359                     }
8360                     // File a report about this.
8361                     String msg = "System package " + pkg.packageName
8362                         + " signature changed; retaining data.";
8363                     reportSettingsProblem(Log.WARN, msg);
8364                 }
8365             }
8366             // Verify that this new package doesn't have any content providers
8367             // that conflict with existing packages.  Only do this if the
8368             // package isn't already installed, since we don't want to break
8369             // things that are installed.
8370             if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8371                 final int N = pkg.providers.size();
8372                 int i;
8373                 for (i=0; i<N; i++) {
8374                     PackageParser.Provider p = pkg.providers.get(i);
8375                     if (p.info.authority != null) {
8376                         String names[] = p.info.authority.split(";");
8377                         for (int j = 0; j < names.length; j++) {
8378                             if (mProvidersByAuthority.containsKey(names[j])) {
8379                                 PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8380                                 final String otherPackageName =
8381                                         ((other != null && other.getComponentName() != null) ?
8382                                                 other.getComponentName().getPackageName() : "?");
8383                                 throw new PackageManagerException(
8384                                         INSTALL_FAILED_CONFLICTING_PROVIDER,
8385                                                 "Can't install because provider name " + names[j]
8386                                                 + " (in package " + pkg.applicationInfo.packageName
8387                                                 + ") is already used by " + otherPackageName);
8388                             }
8389                         }
8390                     }
8391                 }
8392             }
8393
8394             if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8395                 // This package wants to adopt ownership of permissions from
8396                 // another package.
8397                 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8398                     final String origName = pkg.mAdoptPermissions.get(i);
8399                     final PackageSetting orig = mSettings.peekPackageLPr(origName);
8400                     if (orig != null) {
8401                         if (verifyPackageUpdateLPr(orig, pkg)) {
8402                             Slog.i(TAG, "Adopting permissions from " + origName + " to "
8403                                     + pkg.packageName);
8404                             mSettings.transferPermissionsLPw(origName, pkg.packageName);
8405                         }
8406                     }
8407                 }
8408             }
8409         }
8410
8411         final String pkgName = pkg.packageName;
8412
8413         final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8414         final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8415         pkg.applicationInfo.processName = fixProcessName(
8416                 pkg.applicationInfo.packageName,
8417                 pkg.applicationInfo.processName,
8418                 pkg.applicationInfo.uid);
8419
8420         if (pkg != mPlatformPackage) {
8421             // Get all of our default paths setup
8422             pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8423         }
8424
8425         final String path = scanFile.getPath();
8426         final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8427
8428         if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8429             derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8430
8431             // Some system apps still use directory structure for native libraries
8432             // in which case we might end up not detecting abi solely based on apk
8433             // structure. Try to detect abi based on directory structure.
8434             if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8435                     pkg.applicationInfo.primaryCpuAbi == null) {
8436                 setBundledAppAbisAndRoots(pkg, pkgSetting);
8437                 setNativeLibraryPaths(pkg);
8438             }
8439
8440         } else {
8441             if ((scanFlags & SCAN_MOVE) != 0) {
8442                 // We haven't run dex-opt for this move (since we've moved the compiled output too)
8443                 // but we already have this packages package info in the PackageSetting. We just
8444                 // use that and derive the native library path based on the new codepath.
8445                 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8446                 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8447             }
8448
8449             // Set native library paths again. For moves, the path will be updated based on the
8450             // ABIs we've determined above. For non-moves, the path will be updated based on the
8451             // ABIs we determined during compilation, but the path will depend on the final
8452             // package path (after the rename away from the stage path).
8453             setNativeLibraryPaths(pkg);
8454         }
8455
8456         // This is a special case for the "system" package, where the ABI is
8457         // dictated by the zygote configuration (and init.rc). We should keep track
8458         // of this ABI so that we can deal with "normal" applications that run under
8459         // the same UID correctly.
8460         if (mPlatformPackage == pkg) {
8461             pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8462                     Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8463         }
8464
8465         // If there's a mismatch between the abi-override in the package setting
8466         // and the abiOverride specified for the install. Warn about this because we
8467         // would've already compiled the app without taking the package setting into
8468         // account.
8469         if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8470             if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8471                 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8472                         " for package " + pkg.packageName);
8473             }
8474         }
8475
8476         pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8477         pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8478         pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8479
8480         // Copy the derived override back to the parsed package, so that we can
8481         // update the package settings accordingly.
8482         pkg.cpuAbiOverride = cpuAbiOverride;
8483
8484         if (DEBUG_ABI_SELECTION) {
8485             Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8486                     + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8487                     + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8488         }
8489
8490         // Push the derived path down into PackageSettings so we know what to
8491         // clean up at uninstall time.
8492         pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8493
8494         if (DEBUG_ABI_SELECTION) {
8495             Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8496                     " primary=" + pkg.applicationInfo.primaryCpuAbi +
8497                     " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8498         }
8499
8500         if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8501             // We don't do this here during boot because we can do it all
8502             // at once after scanning all existing packages.
8503             //
8504             // We also do this *before* we perform dexopt on this package, so that
8505             // we can avoid redundant dexopts, and also to make sure we've got the
8506             // code and package path correct.
8507             adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8508                     pkg, true /* boot complete */);
8509         }
8510
8511         if (mFactoryTest && pkg.requestedPermissions.contains(
8512                 android.Manifest.permission.FACTORY_TEST)) {
8513             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8514         }
8515
8516         if (isSystemApp(pkg)) {
8517             pkgSetting.isOrphaned = true;
8518         }
8519
8520         ArrayList<PackageParser.Package> clientLibPkgs = null;
8521
8522         if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8523             if (nonMutatedPs != null) {
8524                 synchronized (mPackages) {
8525                     mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8526                 }
8527             }
8528             return pkg;
8529         }
8530
8531         // Only privileged apps and updated privileged apps can add child packages.
8532         if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8533             if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8534                 throw new PackageManagerException("Only privileged apps and updated "
8535                         + "privileged apps can add child packages. Ignoring package "
8536                         + pkg.packageName);
8537             }
8538             final int childCount = pkg.childPackages.size();
8539             for (int i = 0; i < childCount; i++) {
8540                 PackageParser.Package childPkg = pkg.childPackages.get(i);
8541                 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8542                         childPkg.packageName)) {
8543                     throw new PackageManagerException("Cannot override a child package of "
8544                             + "another disabled system app. Ignoring package " + pkg.packageName);
8545                 }
8546             }
8547         }
8548
8549         // writer
8550         synchronized (mPackages) {
8551             if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8552                 // Only system apps can add new shared libraries.
8553                 if (pkg.libraryNames != null) {
8554                     for (int i=0; i<pkg.libraryNames.size(); i++) {
8555                         String name = pkg.libraryNames.get(i);
8556                         boolean allowed = false;
8557                         if (pkg.isUpdatedSystemApp()) {
8558                             // New library entries can only be added through the
8559                             // system image.  This is important to get rid of a lot
8560                             // of nasty edge cases: for example if we allowed a non-
8561                             // system update of the app to add a library, then uninstalling
8562                             // the update would make the library go away, and assumptions
8563                             // we made such as through app install filtering would now
8564                             // have allowed apps on the device which aren't compatible
8565                             // with it.  Better to just have the restriction here, be
8566                             // conservative, and create many fewer cases that can negatively
8567                             // impact the user experience.
8568                             final PackageSetting sysPs = mSettings
8569                                     .getDisabledSystemPkgLPr(pkg.packageName);
8570                             if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8571                                 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8572                                     if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8573                                         allowed = true;
8574                                         break;
8575                                     }
8576                                 }
8577                             }
8578                         } else {
8579                             allowed = true;
8580                         }
8581                         if (allowed) {
8582                             if (!mSharedLibraries.containsKey(name)) {
8583                                 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8584                             } else if (!name.equals(pkg.packageName)) {
8585                                 Slog.w(TAG, "Package " + pkg.packageName + " library "
8586                                         + name + " already exists; skipping");
8587                             }
8588                         } else {
8589                             Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8590                                     + name + " that is not declared on system image; skipping");
8591                         }
8592                     }
8593                     if ((scanFlags & SCAN_BOOTING) == 0) {
8594                         // If we are not booting, we need to update any applications
8595                         // that are clients of our shared library.  If we are booting,
8596                         // this will all be done once the scan is complete.
8597                         clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8598                     }
8599                 }
8600             }
8601         }
8602
8603         if ((scanFlags & SCAN_BOOTING) != 0) {
8604             // No apps can run during boot scan, so they don't need to be frozen
8605         } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8606             // Caller asked to not kill app, so it's probably not frozen
8607         } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8608             // Caller asked us to ignore frozen check for some reason; they
8609             // probably didn't know the package name
8610         } else {
8611             // We're doing major surgery on this package, so it better be frozen
8612             // right now to keep it from launching
8613             checkPackageFrozen(pkgName);
8614         }
8615
8616         // Also need to kill any apps that are dependent on the library.
8617         if (clientLibPkgs != null) {
8618             for (int i=0; i<clientLibPkgs.size(); i++) {
8619                 PackageParser.Package clientPkg = clientLibPkgs.get(i);
8620                 killApplication(clientPkg.applicationInfo.packageName,
8621                         clientPkg.applicationInfo.uid, "update lib");
8622             }
8623         }
8624
8625         // Make sure we're not adding any bogus keyset info
8626         KeySetManagerService ksms = mSettings.mKeySetManagerService;
8627         ksms.assertScannedPackageValid(pkg);
8628
8629         // writer
8630         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8631
8632         boolean createIdmapFailed = false;
8633         synchronized (mPackages) {
8634             // We don't expect installation to fail beyond this point
8635
8636             if (pkgSetting.pkg != null) {
8637                 // Note that |user| might be null during the initial boot scan. If a codePath
8638                 // for an app has changed during a boot scan, it's due to an app update that's
8639                 // part of the system partition and marker changes must be applied to all users.
8640                 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8641                     (user != null) ? user : UserHandle.ALL);
8642             }
8643
8644             // Add the new setting to mSettings
8645             mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8646             // Add the new setting to mPackages
8647             mPackages.put(pkg.applicationInfo.packageName, pkg);
8648             // Make sure we don't accidentally delete its data.
8649             final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8650             while (iter.hasNext()) {
8651                 PackageCleanItem item = iter.next();
8652                 if (pkgName.equals(item.packageName)) {
8653                     iter.remove();
8654                 }
8655             }
8656
8657             // Take care of first install / last update times.
8658             if (currentTime != 0) {
8659                 if (pkgSetting.firstInstallTime == 0) {
8660                     pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8661                 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8662                     pkgSetting.lastUpdateTime = currentTime;
8663                 }
8664             } else if (pkgSetting.firstInstallTime == 0) {
8665                 // We need *something*.  Take time time stamp of the file.
8666                 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8667             } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8668                 if (scanFileTime != pkgSetting.timeStamp) {
8669                     // A package on the system image has changed; consider this
8670                     // to be an update.
8671                     pkgSetting.lastUpdateTime = scanFileTime;
8672                 }
8673             }
8674
8675             // Add the package's KeySets to the global KeySetManagerService
8676             ksms.addScannedPackageLPw(pkg);
8677
8678             int N = pkg.providers.size();
8679             StringBuilder r = null;
8680             int i;
8681             for (i=0; i<N; i++) {
8682                 PackageParser.Provider p = pkg.providers.get(i);
8683                 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8684                         p.info.processName, pkg.applicationInfo.uid);
8685                 mProviders.addProvider(p);
8686                 p.syncable = p.info.isSyncable;
8687                 if (p.info.authority != null) {
8688                     String names[] = p.info.authority.split(";");
8689                     p.info.authority = null;
8690                     for (int j = 0; j < names.length; j++) {
8691                         if (j == 1 && p.syncable) {
8692                             // We only want the first authority for a provider to possibly be
8693                             // syncable, so if we already added this provider using a different
8694                             // authority clear the syncable flag. We copy the provider before
8695                             // changing it because the mProviders object contains a reference
8696                             // to a provider that we don't want to change.
8697                             // Only do this for the second authority since the resulting provider
8698                             // object can be the same for all future authorities for this provider.
8699                             p = new PackageParser.Provider(p);
8700                             p.syncable = false;
8701                         }
8702                         if (!mProvidersByAuthority.containsKey(names[j])) {
8703                             mProvidersByAuthority.put(names[j], p);
8704                             if (p.info.authority == null) {
8705                                 p.info.authority = names[j];
8706                             } else {
8707                                 p.info.authority = p.info.authority + ";" + names[j];
8708                             }
8709                             if (DEBUG_PACKAGE_SCANNING) {
8710                                 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8711                                     Log.d(TAG, "Registered content provider: " + names[j]
8712                                             + ", className = " + p.info.name + ", isSyncable = "
8713                                             + p.info.isSyncable);
8714                             }
8715                         } else {
8716                             PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8717                             Slog.w(TAG, "Skipping provider name " + names[j] +
8718                                     " (in package " + pkg.applicationInfo.packageName +
8719                                     "): name already used by "
8720                                     + ((other != null && other.getComponentName() != null)
8721                                             ? other.getComponentName().getPackageName() : "?"));
8722                         }
8723                     }
8724                 }
8725                 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8726                     if (r == null) {
8727                         r = new StringBuilder(256);
8728                     } else {
8729                         r.append(' ');
8730                     }
8731                     r.append(p.info.name);
8732                 }
8733             }
8734             if (r != null) {
8735                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8736             }
8737
8738             N = pkg.services.size();
8739             r = null;
8740             for (i=0; i<N; i++) {
8741                 PackageParser.Service s = pkg.services.get(i);
8742                 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8743                         s.info.processName, pkg.applicationInfo.uid);
8744                 mServices.addService(s);
8745                 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8746                     if (r == null) {
8747                         r = new StringBuilder(256);
8748                     } else {
8749                         r.append(' ');
8750                     }
8751                     r.append(s.info.name);
8752                 }
8753             }
8754             if (r != null) {
8755                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8756             }
8757
8758             N = pkg.receivers.size();
8759             r = null;
8760             for (i=0; i<N; i++) {
8761                 PackageParser.Activity a = pkg.receivers.get(i);
8762                 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8763                         a.info.processName, pkg.applicationInfo.uid);
8764                 mReceivers.addActivity(a, "receiver");
8765                 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8766                     if (r == null) {
8767                         r = new StringBuilder(256);
8768                     } else {
8769                         r.append(' ');
8770                     }
8771                     r.append(a.info.name);
8772                 }
8773             }
8774             if (r != null) {
8775                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8776             }
8777
8778             N = pkg.activities.size();
8779             r = null;
8780             for (i=0; i<N; i++) {
8781                 PackageParser.Activity a = pkg.activities.get(i);
8782                 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8783                         a.info.processName, pkg.applicationInfo.uid);
8784                 mActivities.addActivity(a, "activity");
8785                 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8786                     if (r == null) {
8787                         r = new StringBuilder(256);
8788                     } else {
8789                         r.append(' ');
8790                     }
8791                     r.append(a.info.name);
8792                 }
8793             }
8794             if (r != null) {
8795                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8796             }
8797
8798             N = pkg.permissionGroups.size();
8799             r = null;
8800             for (i=0; i<N; i++) {
8801                 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8802                 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8803                 final String curPackageName = cur == null ? null : cur.info.packageName;
8804                 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8805                 if (cur == null || isPackageUpdate) {
8806                     mPermissionGroups.put(pg.info.name, pg);
8807                     if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8808                         if (r == null) {
8809                             r = new StringBuilder(256);
8810                         } else {
8811                             r.append(' ');
8812                         }
8813                         if (isPackageUpdate) {
8814                             r.append("UPD:");
8815                         }
8816                         r.append(pg.info.name);
8817                     }
8818                 } else {
8819                     Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8820                             + pg.info.packageName + " ignored: original from "
8821                             + cur.info.packageName);
8822                     if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8823                         if (r == null) {
8824                             r = new StringBuilder(256);
8825                         } else {
8826                             r.append(' ');
8827                         }
8828                         r.append("DUP:");
8829                         r.append(pg.info.name);
8830                     }
8831                 }
8832             }
8833             if (r != null) {
8834                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8835             }
8836
8837             N = pkg.permissions.size();
8838             r = null;
8839             for (i=0; i<N; i++) {
8840                 PackageParser.Permission p = pkg.permissions.get(i);
8841
8842                 // Assume by default that we did not install this permission into the system.
8843                 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8844
8845                 // Now that permission groups have a special meaning, we ignore permission
8846                 // groups for legacy apps to prevent unexpected behavior. In particular,
8847                 // permissions for one app being granted to someone just becase they happen
8848                 // to be in a group defined by another app (before this had no implications).
8849                 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8850                     p.group = mPermissionGroups.get(p.info.group);
8851                     // Warn for a permission in an unknown group.
8852                     if (p.info.group != null && p.group == null) {
8853                         Slog.w(TAG, "Permission " + p.info.name + " from package "
8854                                 + p.info.packageName + " in an unknown group " + p.info.group);
8855                     }
8856                 }
8857
8858                 ArrayMap<String, BasePermission> permissionMap =
8859                         p.tree ? mSettings.mPermissionTrees
8860                                 : mSettings.mPermissions;
8861                 BasePermission bp = permissionMap.get(p.info.name);
8862
8863                 // Allow system apps to redefine non-system permissions
8864                 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8865                     final boolean currentOwnerIsSystem = (bp.perm != null
8866                             && isSystemApp(bp.perm.owner));
8867                     if (isSystemApp(p.owner)) {
8868                         if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8869                             // It's a built-in permission and no owner, take ownership now
8870                             bp.packageSetting = pkgSetting;
8871                             bp.perm = p;
8872                             bp.uid = pkg.applicationInfo.uid;
8873                             bp.sourcePackage = p.info.packageName;
8874                             p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8875                         } else if (!currentOwnerIsSystem) {
8876                             String msg = "New decl " + p.owner + " of permission  "
8877                                     + p.info.name + " is system; overriding " + bp.sourcePackage;
8878                             reportSettingsProblem(Log.WARN, msg);
8879                             bp = null;
8880                         }
8881                     }
8882                 }
8883
8884                 if (bp == null) {
8885                     bp = new BasePermission(p.info.name, p.info.packageName,
8886                             BasePermission.TYPE_NORMAL);
8887                     permissionMap.put(p.info.name, bp);
8888                 }
8889
8890                 if (bp.perm == null) {
8891                     if (bp.sourcePackage == null
8892                             || bp.sourcePackage.equals(p.info.packageName)) {
8893                         BasePermission tree = findPermissionTreeLP(p.info.name);
8894                         if (tree == null
8895                                 || tree.sourcePackage.equals(p.info.packageName)) {
8896                             bp.packageSetting = pkgSetting;
8897                             bp.perm = p;
8898                             bp.uid = pkg.applicationInfo.uid;
8899                             bp.sourcePackage = p.info.packageName;
8900                             p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8901                             if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8902                                 if (r == null) {
8903                                     r = new StringBuilder(256);
8904                                 } else {
8905                                     r.append(' ');
8906                                 }
8907                                 r.append(p.info.name);
8908                             }
8909                         } else {
8910                             Slog.w(TAG, "Permission " + p.info.name + " from package "
8911                                     + p.info.packageName + " ignored: base tree "
8912                                     + tree.name + " is from package "
8913                                     + tree.sourcePackage);
8914                         }
8915                     } else {
8916                         Slog.w(TAG, "Permission " + p.info.name + " from package "
8917                                 + p.info.packageName + " ignored: original from "
8918                                 + bp.sourcePackage);
8919                     }
8920                 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8921                     if (r == null) {
8922                         r = new StringBuilder(256);
8923                     } else {
8924                         r.append(' ');
8925                     }
8926                     r.append("DUP:");
8927                     r.append(p.info.name);
8928                 }
8929                 if (bp.perm == p) {
8930                     bp.protectionLevel = p.info.protectionLevel;
8931                 }
8932             }
8933
8934             if (r != null) {
8935                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8936             }
8937
8938             N = pkg.instrumentation.size();
8939             r = null;
8940             for (i=0; i<N; i++) {
8941                 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8942                 a.info.packageName = pkg.applicationInfo.packageName;
8943                 a.info.sourceDir = pkg.applicationInfo.sourceDir;
8944                 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8945                 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8946                 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8947                 a.info.dataDir = pkg.applicationInfo.dataDir;
8948                 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8949                 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8950
8951                 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8952                 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8953                 mInstrumentation.put(a.getComponentName(), a);
8954                 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8955                     if (r == null) {
8956                         r = new StringBuilder(256);
8957                     } else {
8958                         r.append(' ');
8959                     }
8960                     r.append(a.info.name);
8961                 }
8962             }
8963             if (r != null) {
8964                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8965             }
8966
8967             if (pkg.protectedBroadcasts != null) {
8968                 N = pkg.protectedBroadcasts.size();
8969                 for (i=0; i<N; i++) {
8970                     mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8971                 }
8972             }
8973
8974             pkgSetting.setTimeStamp(scanFileTime);
8975
8976             // Create idmap files for pairs of (packages, overlay packages).
8977             // Note: "android", ie framework-res.apk, is handled by native layers.
8978             if (pkg.mOverlayTarget != null) {
8979                 // This is an overlay package.
8980                 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8981                     if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8982                         mOverlays.put(pkg.mOverlayTarget,
8983                                 new ArrayMap<String, PackageParser.Package>());
8984                     }
8985                     ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8986                     map.put(pkg.packageName, pkg);
8987                     PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8988                     if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8989                         createIdmapFailed = true;
8990                     }
8991                 }
8992             } else if (mOverlays.containsKey(pkg.packageName) &&
8993                     !pkg.packageName.equals("android")) {
8994                 // This is a regular package, with one or more known overlay packages.
8995                 createIdmapsForPackageLI(pkg);
8996             }
8997         }
8998
8999         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9000
9001         if (createIdmapFailed) {
9002             throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9003                     "scanPackageLI failed to createIdmap");
9004         }
9005         return pkg;
9006     }
9007
9008     private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
9009             PackageParser.Package update, UserHandle user) {
9010         if (existing.applicationInfo == null || update.applicationInfo == null) {
9011             // This isn't due to an app installation.
9012             return;
9013         }
9014
9015         final File oldCodePath = new File(existing.applicationInfo.getCodePath());
9016         final File newCodePath = new File(update.applicationInfo.getCodePath());
9017
9018         // The codePath hasn't changed, so there's nothing for us to do.
9019         if (Objects.equals(oldCodePath, newCodePath)) {
9020             return;
9021         }
9022
9023         File canonicalNewCodePath;
9024         try {
9025             canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9026         } catch (IOException e) {
9027             Slog.w(TAG, "Failed to get canonical path.", e);
9028             return;
9029         }
9030
9031         // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9032         // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9033         // that the last component of the path (i.e, the name) doesn't need canonicalization
9034         // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9035         // but may change in the future. Hopefully this function won't exist at that point.
9036         final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9037                 oldCodePath.getName());
9038
9039         // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9040         // with "@".
9041         String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9042         if (!oldMarkerPrefix.endsWith("@")) {
9043             oldMarkerPrefix += "@";
9044         }
9045         String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9046         if (!newMarkerPrefix.endsWith("@")) {
9047             newMarkerPrefix += "@";
9048         }
9049
9050         List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9051         List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9052         for (String updatedPath : updatedPaths) {
9053             String updatedPathName = new File(updatedPath).getName();
9054             markerSuffixes.add(updatedPathName.replace('/', '@'));
9055         }
9056
9057         for (int userId : resolveUserIds(user.getIdentifier())) {
9058             File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9059
9060             for (String markerSuffix : markerSuffixes) {
9061                 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9062                 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9063                 if (oldForeignUseMark.exists()) {
9064                     try {
9065                         Os.rename(oldForeignUseMark.getAbsolutePath(),
9066                                 newForeignUseMark.getAbsolutePath());
9067                     } catch (ErrnoException e) {
9068                         Slog.w(TAG, "Failed to rename foreign use marker", e);
9069                         oldForeignUseMark.delete();
9070                     }
9071                 }
9072             }
9073         }
9074     }
9075
9076     /**
9077      * Derive the ABI of a non-system package located at {@code scanFile}. This information
9078      * is derived purely on the basis of the contents of {@code scanFile} and
9079      * {@code cpuAbiOverride}.
9080      *
9081      * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9082      */
9083     private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9084                                  String cpuAbiOverride, boolean extractLibs)
9085             throws PackageManagerException {
9086         // TODO: We can probably be smarter about this stuff. For installed apps,
9087         // we can calculate this information at install time once and for all. For
9088         // system apps, we can probably assume that this information doesn't change
9089         // after the first boot scan. As things stand, we do lots of unnecessary work.
9090
9091         // Give ourselves some initial paths; we'll come back for another
9092         // pass once we've determined ABI below.
9093         setNativeLibraryPaths(pkg);
9094
9095         // We would never need to extract libs for forward-locked and external packages,
9096         // since the container service will do it for us. We shouldn't attempt to
9097         // extract libs from system app when it was not updated.
9098         if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9099                 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9100             extractLibs = false;
9101         }
9102
9103         final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9104         final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9105
9106         NativeLibraryHelper.Handle handle = null;
9107         try {
9108             handle = NativeLibraryHelper.Handle.create(pkg);
9109             // TODO(multiArch): This can be null for apps that didn't go through the
9110             // usual installation process. We can calculate it again, like we
9111             // do during install time.
9112             //
9113             // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9114             // unnecessary.
9115             final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9116
9117             // Null out the abis so that they can be recalculated.
9118             pkg.applicationInfo.primaryCpuAbi = null;
9119             pkg.applicationInfo.secondaryCpuAbi = null;
9120             if (isMultiArch(pkg.applicationInfo)) {
9121                 // Warn if we've set an abiOverride for multi-lib packages..
9122                 // By definition, we need to copy both 32 and 64 bit libraries for
9123                 // such packages.
9124                 if (pkg.cpuAbiOverride != null
9125                         && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9126                     Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9127                 }
9128
9129                 int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9130                 int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9131                 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9132                     if (extractLibs) {
9133                         abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9134                                 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9135                                 useIsaSpecificSubdirs);
9136                     } else {
9137                         abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9138                     }
9139                 }
9140
9141                 maybeThrowExceptionForMultiArchCopy(
9142                         "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9143
9144                 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9145                     if (extractLibs) {
9146                         abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9147                                 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9148                                 useIsaSpecificSubdirs);
9149                     } else {
9150                         abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9151                     }
9152                 }
9153
9154                 maybeThrowExceptionForMultiArchCopy(
9155                         "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9156
9157                 if (abi64 >= 0) {
9158                     pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9159                 }
9160
9161                 if (abi32 >= 0) {
9162                     final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9163                     if (abi64 >= 0) {
9164                         if (pkg.use32bitAbi) {
9165                             pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9166                             pkg.applicationInfo.primaryCpuAbi = abi;
9167                         } else {
9168                             pkg.applicationInfo.secondaryCpuAbi = abi;
9169                         }
9170                     } else {
9171                         pkg.applicationInfo.primaryCpuAbi = abi;
9172                     }
9173                 }
9174
9175             } else {
9176                 String[] abiList = (cpuAbiOverride != null) ?
9177                         new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9178
9179                 // Enable gross and lame hacks for apps that are built with old
9180                 // SDK tools. We must scan their APKs for renderscript bitcode and
9181                 // not launch them if it's present. Don't bother checking on devices
9182                 // that don't have 64 bit support.
9183                 boolean needsRenderScriptOverride = false;
9184                 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9185                         NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9186                     abiList = Build.SUPPORTED_32_BIT_ABIS;
9187                     needsRenderScriptOverride = true;
9188                 }
9189
9190                 final int copyRet;
9191                 if (extractLibs) {
9192                     copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9193                             nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9194                 } else {
9195                     copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9196                 }
9197
9198                 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9199                     throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9200                             "Error unpackaging native libs for app, errorCode=" + copyRet);
9201                 }
9202
9203                 if (copyRet >= 0) {
9204                     pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9205                 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9206                     pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9207                 } else if (needsRenderScriptOverride) {
9208                     pkg.applicationInfo.primaryCpuAbi = abiList[0];
9209                 }
9210             }
9211         } catch (IOException ioe) {
9212             Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9213         } finally {
9214             IoUtils.closeQuietly(handle);
9215         }
9216
9217         // Now that we've calculated the ABIs and determined if it's an internal app,
9218         // we will go ahead and populate the nativeLibraryPath.
9219         setNativeLibraryPaths(pkg);
9220     }
9221
9222     /**
9223      * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9224      * i.e, so that all packages can be run inside a single process if required.
9225      *
9226      * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9227      * this function will either try and make the ABI for all packages in {@code packagesForUser}
9228      * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9229      * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9230      * updating a package that belongs to a shared user.
9231      *
9232      * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9233      * adds unnecessary complexity.
9234      */
9235     private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9236             PackageParser.Package scannedPackage, boolean bootComplete) {
9237         String requiredInstructionSet = null;
9238         if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9239             requiredInstructionSet = VMRuntime.getInstructionSet(
9240                      scannedPackage.applicationInfo.primaryCpuAbi);
9241         }
9242
9243         PackageSetting requirer = null;
9244         for (PackageSetting ps : packagesForUser) {
9245             // If packagesForUser contains scannedPackage, we skip it. This will happen
9246             // when scannedPackage is an update of an existing package. Without this check,
9247             // we will never be able to change the ABI of any package belonging to a shared
9248             // user, even if it's compatible with other packages.
9249             if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9250                 if (ps.primaryCpuAbiString == null) {
9251                     continue;
9252                 }
9253
9254                 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9255                 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9256                     // We have a mismatch between instruction sets (say arm vs arm64) warn about
9257                     // this but there's not much we can do.
9258                     String errorMessage = "Instruction set mismatch, "
9259                             + ((requirer == null) ? "[caller]" : requirer)
9260                             + " requires " + requiredInstructionSet + " whereas " + ps
9261                             + " requires " + instructionSet;
9262                     Slog.w(TAG, errorMessage);
9263                 }
9264
9265                 if (requiredInstructionSet == null) {
9266                     requiredInstructionSet = instructionSet;
9267                     requirer = ps;
9268                 }
9269             }
9270         }
9271
9272         if (requiredInstructionSet != null) {
9273             String adjustedAbi;
9274             if (requirer != null) {
9275                 // requirer != null implies that either scannedPackage was null or that scannedPackage
9276                 // did not require an ABI, in which case we have to adjust scannedPackage to match
9277                 // the ABI of the set (which is the same as requirer's ABI)
9278                 adjustedAbi = requirer.primaryCpuAbiString;
9279                 if (scannedPackage != null) {
9280                     scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9281                 }
9282             } else {
9283                 // requirer == null implies that we're updating all ABIs in the set to
9284                 // match scannedPackage.
9285                 adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9286             }
9287
9288             for (PackageSetting ps : packagesForUser) {
9289                 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9290                     if (ps.primaryCpuAbiString != null) {
9291                         continue;
9292                     }
9293
9294                     ps.primaryCpuAbiString = adjustedAbi;
9295                     if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9296                             !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9297                         ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9298                         Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9299                                 + " (requirer="
9300                                 + (requirer == null ? "null" : requirer.pkg.packageName)
9301                                 + ", scannedPackage="
9302                                 + (scannedPackage != null ? scannedPackage.packageName : "null")
9303                                 + ")");
9304                         try {
9305                             mInstaller.rmdex(ps.codePathString,
9306                                     getDexCodeInstructionSet(getPreferredInstructionSet()));
9307                         } catch (InstallerException ignored) {
9308                         }
9309                     }
9310                 }
9311             }
9312         }
9313     }
9314
9315     private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9316         synchronized (mPackages) {
9317             mResolverReplaced = true;
9318             // Set up information for custom user intent resolution activity.
9319             mResolveActivity.applicationInfo = pkg.applicationInfo;
9320             mResolveActivity.name = mCustomResolverComponentName.getClassName();
9321             mResolveActivity.packageName = pkg.applicationInfo.packageName;
9322             mResolveActivity.processName = pkg.applicationInfo.packageName;
9323             mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9324             mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9325                     ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9326             mResolveActivity.theme = 0;
9327             mResolveActivity.exported = true;
9328             mResolveActivity.enabled = true;
9329             mResolveInfo.activityInfo = mResolveActivity;
9330             mResolveInfo.priority = 0;
9331             mResolveInfo.preferredOrder = 0;
9332             mResolveInfo.match = 0;
9333             mResolveComponentName = mCustomResolverComponentName;
9334             Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9335                     mResolveComponentName);
9336         }
9337     }
9338
9339     private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9340         final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9341
9342         // Set up information for ephemeral installer activity
9343         mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9344         mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9345         mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9346         mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9347         mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9348         mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
9349                 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9350         mEphemeralInstallerActivity.theme = 0;
9351         mEphemeralInstallerActivity.exported = true;
9352         mEphemeralInstallerActivity.enabled = true;
9353         mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9354         mEphemeralInstallerInfo.priority = 0;
9355         mEphemeralInstallerInfo.preferredOrder = 1;
9356         mEphemeralInstallerInfo.isDefault = true;
9357         mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
9358                 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
9359
9360         if (DEBUG_EPHEMERAL) {
9361             Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9362         }
9363     }
9364
9365     private static String calculateBundledApkRoot(final String codePathString) {
9366         final File codePath = new File(codePathString);
9367         final File codeRoot;
9368         if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9369             codeRoot = Environment.getRootDirectory();
9370         } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9371             codeRoot = Environment.getOemDirectory();
9372         } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9373             codeRoot = Environment.getVendorDirectory();
9374         } else {
9375             // Unrecognized code path; take its top real segment as the apk root:
9376             // e.g. /something/app/blah.apk => /something
9377             try {
9378                 File f = codePath.getCanonicalFile();
9379                 File parent = f.getParentFile();    // non-null because codePath is a file
9380                 File tmp;
9381                 while ((tmp = parent.getParentFile()) != null) {
9382                     f = parent;
9383                     parent = tmp;
9384                 }
9385                 codeRoot = f;
9386                 Slog.w(TAG, "Unrecognized code path "
9387                         + codePath + " - using " + codeRoot);
9388             } catch (IOException e) {
9389                 // Can't canonicalize the code path -- shenanigans?
9390                 Slog.w(TAG, "Can't canonicalize code path " + codePath);
9391                 return Environment.getRootDirectory().getPath();
9392             }
9393         }
9394         return codeRoot.getPath();
9395     }
9396
9397     /**
9398      * Derive and set the location of native libraries for the given package,
9399      * which varies depending on where and how the package was installed.
9400      */
9401     private void setNativeLibraryPaths(PackageParser.Package pkg) {
9402         final ApplicationInfo info = pkg.applicationInfo;
9403         final String codePath = pkg.codePath;
9404         final File codeFile = new File(codePath);
9405         final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9406         final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9407
9408         info.nativeLibraryRootDir = null;
9409         info.nativeLibraryRootRequiresIsa = false;
9410         info.nativeLibraryDir = null;
9411         info.secondaryNativeLibraryDir = null;
9412
9413         if (isApkFile(codeFile)) {
9414             // Monolithic install
9415             if (bundledApp) {
9416                 // If "/system/lib64/apkname" exists, assume that is the per-package
9417                 // native library directory to use; otherwise use "/system/lib/apkname".
9418                 final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9419                 final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9420                         getPrimaryInstructionSet(info));
9421
9422                 // This is a bundled system app so choose the path based on the ABI.
9423                 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9424                 // is just the default path.
9425                 final String apkName = deriveCodePathName(codePath);
9426                 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9427                 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9428                         apkName).getAbsolutePath();
9429
9430                 if (info.secondaryCpuAbi != null) {
9431                     final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9432                     info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9433                             secondaryLibDir, apkName).getAbsolutePath();
9434                 }
9435             } else if (asecApp) {
9436                 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9437                         .getAbsolutePath();
9438             } else {
9439                 final String apkName = deriveCodePathName(codePath);
9440                 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9441                         .getAbsolutePath();
9442             }
9443
9444             info.nativeLibraryRootRequiresIsa = false;
9445             info.nativeLibraryDir = info.nativeLibraryRootDir;
9446         } else {
9447             // Cluster install
9448             info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9449             info.nativeLibraryRootRequiresIsa = true;
9450
9451             info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9452                     getPrimaryInstructionSet(info)).getAbsolutePath();
9453
9454             if (info.secondaryCpuAbi != null) {
9455                 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9456                         VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9457             }
9458         }
9459     }
9460
9461     /**
9462      * Calculate the abis and roots for a bundled app. These can uniquely
9463      * be determined from the contents of the system partition, i.e whether
9464      * it contains 64 or 32 bit shared libraries etc. We do not validate any
9465      * of this information, and instead assume that the system was built
9466      * sensibly.
9467      */
9468     private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9469                                            PackageSetting pkgSetting) {
9470         final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9471
9472         // If "/system/lib64/apkname" exists, assume that is the per-package
9473         // native library directory to use; otherwise use "/system/lib/apkname".
9474         final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9475         setBundledAppAbi(pkg, apkRoot, apkName);
9476         // pkgSetting might be null during rescan following uninstall of updates
9477         // to a bundled app, so accommodate that possibility.  The settings in
9478         // that case will be established later from the parsed package.
9479         //
9480         // If the settings aren't null, sync them up with what we've just derived.
9481         // note that apkRoot isn't stored in the package settings.
9482         if (pkgSetting != null) {
9483             pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9484             pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9485         }
9486     }
9487
9488     /**
9489      * Deduces the ABI of a bundled app and sets the relevant fields on the
9490      * parsed pkg object.
9491      *
9492      * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9493      *        under which system libraries are installed.
9494      * @param apkName the name of the installed package.
9495      */
9496     private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9497         final File codeFile = new File(pkg.codePath);
9498
9499         final boolean has64BitLibs;
9500         final boolean has32BitLibs;
9501         if (isApkFile(codeFile)) {
9502             // Monolithic install
9503             has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9504             has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9505         } else {
9506             // Cluster install
9507             final File rootDir = new File(codeFile, LIB_DIR_NAME);
9508             if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9509                     && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9510                 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9511                 has64BitLibs = (new File(rootDir, isa)).exists();
9512             } else {
9513                 has64BitLibs = false;
9514             }
9515             if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9516                     && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9517                 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9518                 has32BitLibs = (new File(rootDir, isa)).exists();
9519             } else {
9520                 has32BitLibs = false;
9521             }
9522         }
9523
9524         if (has64BitLibs && !has32BitLibs) {
9525             // The package has 64 bit libs, but not 32 bit libs. Its primary
9526             // ABI should be 64 bit. We can safely assume here that the bundled
9527             // native libraries correspond to the most preferred ABI in the list.
9528
9529             pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9530             pkg.applicationInfo.secondaryCpuAbi = null;
9531         } else if (has32BitLibs && !has64BitLibs) {
9532             // The package has 32 bit libs but not 64 bit libs. Its primary
9533             // ABI should be 32 bit.
9534
9535             pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9536             pkg.applicationInfo.secondaryCpuAbi = null;
9537         } else if (has32BitLibs && has64BitLibs) {
9538             // The application has both 64 and 32 bit bundled libraries. We check
9539             // here that the app declares multiArch support, and warn if it doesn't.
9540             //
9541             // We will be lenient here and record both ABIs. The primary will be the
9542             // ABI that's higher on the list, i.e, a device that's configured to prefer
9543             // 64 bit apps will see a 64 bit primary ABI,
9544
9545             if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9546                 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9547             }
9548
9549             if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9550                 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9551                 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9552             } else {
9553                 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9554                 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9555             }
9556         } else {
9557             pkg.applicationInfo.primaryCpuAbi = null;
9558             pkg.applicationInfo.secondaryCpuAbi = null;
9559         }
9560     }
9561
9562     private void killApplication(String pkgName, int appId, String reason) {
9563         killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9564     }
9565
9566     private void killApplication(String pkgName, int appId, int userId, String reason) {
9567         // Request the ActivityManager to kill the process(only for existing packages)
9568         // so that we do not end up in a confused state while the user is still using the older
9569         // version of the application while the new one gets installed.
9570         final long token = Binder.clearCallingIdentity();
9571         try {
9572             IActivityManager am = ActivityManagerNative.getDefault();
9573             if (am != null) {
9574                 try {
9575                     am.killApplication(pkgName, appId, userId, reason);
9576                 } catch (RemoteException e) {
9577                 }
9578             }
9579         } finally {
9580             Binder.restoreCallingIdentity(token);
9581         }
9582     }
9583
9584     private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9585         // Remove the parent package setting
9586         PackageSetting ps = (PackageSetting) pkg.mExtras;
9587         if (ps != null) {
9588             removePackageLI(ps, chatty);
9589         }
9590         // Remove the child package setting
9591         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9592         for (int i = 0; i < childCount; i++) {
9593             PackageParser.Package childPkg = pkg.childPackages.get(i);
9594             ps = (PackageSetting) childPkg.mExtras;
9595             if (ps != null) {
9596                 removePackageLI(ps, chatty);
9597             }
9598         }
9599     }
9600
9601     void removePackageLI(PackageSetting ps, boolean chatty) {
9602         if (DEBUG_INSTALL) {
9603             if (chatty)
9604                 Log.d(TAG, "Removing package " + ps.name);
9605         }
9606
9607         // writer
9608         synchronized (mPackages) {
9609             mPackages.remove(ps.name);
9610             final PackageParser.Package pkg = ps.pkg;
9611             if (pkg != null) {
9612                 cleanPackageDataStructuresLILPw(pkg, chatty);
9613             }
9614         }
9615     }
9616
9617     void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9618         if (DEBUG_INSTALL) {
9619             if (chatty)
9620                 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9621         }
9622
9623         // writer
9624         synchronized (mPackages) {
9625             // Remove the parent package
9626             mPackages.remove(pkg.applicationInfo.packageName);
9627             cleanPackageDataStructuresLILPw(pkg, chatty);
9628
9629             // Remove the child packages
9630             final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9631             for (int i = 0; i < childCount; i++) {
9632                 PackageParser.Package childPkg = pkg.childPackages.get(i);
9633                 mPackages.remove(childPkg.applicationInfo.packageName);
9634                 cleanPackageDataStructuresLILPw(childPkg, chatty);
9635             }
9636         }
9637     }
9638
9639     void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9640         int N = pkg.providers.size();
9641         StringBuilder r = null;
9642         int i;
9643         for (i=0; i<N; i++) {
9644             PackageParser.Provider p = pkg.providers.get(i);
9645             mProviders.removeProvider(p);
9646             if (p.info.authority == null) {
9647
9648                 /* There was another ContentProvider with this authority when
9649                  * this app was installed so this authority is null,
9650                  * Ignore it as we don't have to unregister the provider.
9651                  */
9652                 continue;
9653             }
9654             String names[] = p.info.authority.split(";");
9655             for (int j = 0; j < names.length; j++) {
9656                 if (mProvidersByAuthority.get(names[j]) == p) {
9657                     mProvidersByAuthority.remove(names[j]);
9658                     if (DEBUG_REMOVE) {
9659                         if (chatty)
9660                             Log.d(TAG, "Unregistered content provider: " + names[j]
9661                                     + ", className = " + p.info.name + ", isSyncable = "
9662                                     + p.info.isSyncable);
9663                     }
9664                 }
9665             }
9666             if (DEBUG_REMOVE && chatty) {
9667                 if (r == null) {
9668                     r = new StringBuilder(256);
9669                 } else {
9670                     r.append(' ');
9671                 }
9672                 r.append(p.info.name);
9673             }
9674         }
9675         if (r != null) {
9676             if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9677         }
9678
9679         N = pkg.services.size();
9680         r = null;
9681         for (i=0; i<N; i++) {
9682             PackageParser.Service s = pkg.services.get(i);
9683             mServices.removeService(s);
9684             if (chatty) {
9685                 if (r == null) {
9686                     r = new StringBuilder(256);
9687                 } else {
9688                     r.append(' ');
9689                 }
9690                 r.append(s.info.name);
9691             }
9692         }
9693         if (r != null) {
9694             if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9695         }
9696
9697         N = pkg.receivers.size();
9698         r = null;
9699         for (i=0; i<N; i++) {
9700             PackageParser.Activity a = pkg.receivers.get(i);
9701             mReceivers.removeActivity(a, "receiver");
9702             if (DEBUG_REMOVE && chatty) {
9703                 if (r == null) {
9704                     r = new StringBuilder(256);
9705                 } else {
9706                     r.append(' ');
9707                 }
9708                 r.append(a.info.name);
9709             }
9710         }
9711         if (r != null) {
9712             if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9713         }
9714
9715         N = pkg.activities.size();
9716         r = null;
9717         for (i=0; i<N; i++) {
9718             PackageParser.Activity a = pkg.activities.get(i);
9719             mActivities.removeActivity(a, "activity");
9720             if (DEBUG_REMOVE && chatty) {
9721                 if (r == null) {
9722                     r = new StringBuilder(256);
9723                 } else {
9724                     r.append(' ');
9725                 }
9726                 r.append(a.info.name);
9727             }
9728         }
9729         if (r != null) {
9730             if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9731         }
9732
9733         N = pkg.permissions.size();
9734         r = null;
9735         for (i=0; i<N; i++) {
9736             PackageParser.Permission p = pkg.permissions.get(i);
9737             BasePermission bp = mSettings.mPermissions.get(p.info.name);
9738             if (bp == null) {
9739                 bp = mSettings.mPermissionTrees.get(p.info.name);
9740             }
9741             if (bp != null && bp.perm == p) {
9742                 bp.perm = null;
9743                 if (DEBUG_REMOVE && chatty) {
9744                     if (r == null) {
9745                         r = new StringBuilder(256);
9746                     } else {
9747                         r.append(' ');
9748                     }
9749                     r.append(p.info.name);
9750                 }
9751             }
9752             if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9753                 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9754                 if (appOpPkgs != null) {
9755                     appOpPkgs.remove(pkg.packageName);
9756                 }
9757             }
9758         }
9759         if (r != null) {
9760             if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9761         }
9762
9763         N = pkg.requestedPermissions.size();
9764         r = null;
9765         for (i=0; i<N; i++) {
9766             String perm = pkg.requestedPermissions.get(i);
9767             BasePermission bp = mSettings.mPermissions.get(perm);
9768             if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9769                 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9770                 if (appOpPkgs != null) {
9771                     appOpPkgs.remove(pkg.packageName);
9772                     if (appOpPkgs.isEmpty()) {
9773                         mAppOpPermissionPackages.remove(perm);
9774                     }
9775                 }
9776             }
9777         }
9778         if (r != null) {
9779             if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9780         }
9781
9782         N = pkg.instrumentation.size();
9783         r = null;
9784         for (i=0; i<N; i++) {
9785             PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9786             mInstrumentation.remove(a.getComponentName());
9787             if (DEBUG_REMOVE && chatty) {
9788                 if (r == null) {
9789                     r = new StringBuilder(256);
9790                 } else {
9791                     r.append(' ');
9792                 }
9793                 r.append(a.info.name);
9794             }
9795         }
9796         if (r != null) {
9797             if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9798         }
9799
9800         r = null;
9801         if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9802             // Only system apps can hold shared libraries.
9803             if (pkg.libraryNames != null) {
9804                 for (i=0; i<pkg.libraryNames.size(); i++) {
9805                     String name = pkg.libraryNames.get(i);
9806                     SharedLibraryEntry cur = mSharedLibraries.get(name);
9807                     if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9808                         mSharedLibraries.remove(name);
9809                         if (DEBUG_REMOVE && chatty) {
9810                             if (r == null) {
9811                                 r = new StringBuilder(256);
9812                             } else {
9813                                 r.append(' ');
9814                             }
9815                             r.append(name);
9816                         }
9817                     }
9818                 }
9819             }
9820         }
9821         if (r != null) {
9822             if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9823         }
9824     }
9825
9826     private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9827         for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9828             if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9829                 return true;
9830             }
9831         }
9832         return false;
9833     }
9834
9835     static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9836     static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9837     static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9838
9839     private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9840         // Update the parent permissions
9841         updatePermissionsLPw(pkg.packageName, pkg, flags);
9842         // Update the child permissions
9843         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9844         for (int i = 0; i < childCount; i++) {
9845             PackageParser.Package childPkg = pkg.childPackages.get(i);
9846             updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9847         }
9848     }
9849
9850     private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9851             int flags) {
9852         final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9853         updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9854     }
9855
9856     private void updatePermissionsLPw(String changingPkg,
9857             PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9858         // Make sure there are no dangling permission trees.
9859         Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9860         while (it.hasNext()) {
9861             final BasePermission bp = it.next();
9862             if (bp.packageSetting == null) {
9863                 // We may not yet have parsed the package, so just see if
9864                 // we still know about its settings.
9865                 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9866             }
9867             if (bp.packageSetting == null) {
9868                 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9869                         + " from package " + bp.sourcePackage);
9870                 it.remove();
9871             } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9872                 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9873                     Slog.i(TAG, "Removing old permission tree: " + bp.name
9874                             + " from package " + bp.sourcePackage);
9875                     flags |= UPDATE_PERMISSIONS_ALL;
9876                     it.remove();
9877                 }
9878             }
9879         }
9880
9881         // Make sure all dynamic permissions have been assigned to a package,
9882         // and make sure there are no dangling permissions.
9883         it = mSettings.mPermissions.values().iterator();
9884         while (it.hasNext()) {
9885             final BasePermission bp = it.next();
9886             if (bp.type == BasePermission.TYPE_DYNAMIC) {
9887                 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9888                         + bp.name + " pkg=" + bp.sourcePackage
9889                         + " info=" + bp.pendingInfo);
9890                 if (bp.packageSetting == null && bp.pendingInfo != null) {
9891                     final BasePermission tree = findPermissionTreeLP(bp.name);
9892                     if (tree != null && tree.perm != null) {
9893                         bp.packageSetting = tree.packageSetting;
9894                         bp.perm = new PackageParser.Permission(tree.perm.owner,
9895                                 new PermissionInfo(bp.pendingInfo));
9896                         bp.perm.info.packageName = tree.perm.info.packageName;
9897                         bp.perm.info.name = bp.name;
9898                         bp.uid = tree.uid;
9899                     }
9900                 }
9901             }
9902             if (bp.packageSetting == null) {
9903                 // We may not yet have parsed the package, so just see if
9904                 // we still know about its settings.
9905                 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9906             }
9907             if (bp.packageSetting == null) {
9908                 Slog.w(TAG, "Removing dangling permission: " + bp.name
9909                         + " from package " + bp.sourcePackage);
9910                 it.remove();
9911             } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9912                 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9913                     Slog.i(TAG, "Removing old permission: " + bp.name
9914                             + " from package " + bp.sourcePackage);
9915                     flags |= UPDATE_PERMISSIONS_ALL;
9916                     it.remove();
9917                 }
9918             }
9919         }
9920
9921         // Now update the permissions for all packages, in particular
9922         // replace the granted permissions of the system packages.
9923         if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9924             for (PackageParser.Package pkg : mPackages.values()) {
9925                 if (pkg != pkgInfo) {
9926                     // Only replace for packages on requested volume
9927                     final String volumeUuid = getVolumeUuidForPackage(pkg);
9928                     final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9929                             && Objects.equals(replaceVolumeUuid, volumeUuid);
9930                     grantPermissionsLPw(pkg, replace, changingPkg);
9931                 }
9932             }
9933         }
9934
9935         if (pkgInfo != null) {
9936             // Only replace for packages on requested volume
9937             final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9938             final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9939                     && Objects.equals(replaceVolumeUuid, volumeUuid);
9940             grantPermissionsLPw(pkgInfo, replace, changingPkg);
9941         }
9942     }
9943
9944     private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9945             String packageOfInterest) {
9946         // IMPORTANT: There are two types of permissions: install and runtime.
9947         // Install time permissions are granted when the app is installed to
9948         // all device users and users added in the future. Runtime permissions
9949         // are granted at runtime explicitly to specific users. Normal and signature
9950         // protected permissions are install time permissions. Dangerous permissions
9951         // are install permissions if the app's target SDK is Lollipop MR1 or older,
9952         // otherwise they are runtime permissions. This function does not manage
9953         // runtime permissions except for the case an app targeting Lollipop MR1
9954         // being upgraded to target a newer SDK, in which case dangerous permissions
9955         // are transformed from install time to runtime ones.
9956
9957         final PackageSetting ps = (PackageSetting) pkg.mExtras;
9958         if (ps == null) {
9959             return;
9960         }
9961
9962         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9963
9964         PermissionsState permissionsState = ps.getPermissionsState();
9965         PermissionsState origPermissions = permissionsState;
9966
9967         final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9968
9969         boolean runtimePermissionsRevoked = false;
9970         int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9971
9972         boolean changedInstallPermission = false;
9973
9974         if (replace) {
9975             ps.installPermissionsFixed = false;
9976             if (!ps.isSharedUser()) {
9977                 origPermissions = new PermissionsState(permissionsState);
9978                 permissionsState.reset();
9979             } else {
9980                 // We need to know only about runtime permission changes since the
9981                 // calling code always writes the install permissions state but
9982                 // the runtime ones are written only if changed. The only cases of
9983                 // changed runtime permissions here are promotion of an install to
9984                 // runtime and revocation of a runtime from a shared user.
9985                 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9986                         ps.sharedUser, UserManagerService.getInstance().getUserIds());
9987                 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9988                     runtimePermissionsRevoked = true;
9989                 }
9990             }
9991         }
9992
9993         permissionsState.setGlobalGids(mGlobalGids);
9994
9995         final int N = pkg.requestedPermissions.size();
9996         for (int i=0; i<N; i++) {
9997             final String name = pkg.requestedPermissions.get(i);
9998             final BasePermission bp = mSettings.mPermissions.get(name);
9999
10000             if (DEBUG_INSTALL) {
10001                 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
10002             }
10003
10004             if (bp == null || bp.packageSetting == null) {
10005                 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10006                     Slog.w(TAG, "Unknown permission " + name
10007                             + " in package " + pkg.packageName);
10008                 }
10009                 continue;
10010             }
10011
10012             final String perm = bp.name;
10013             boolean allowedSig = false;
10014             int grant = GRANT_DENIED;
10015
10016             // Keep track of app op permissions.
10017             if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10018                 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
10019                 if (pkgs == null) {
10020                     pkgs = new ArraySet<>();
10021                     mAppOpPermissionPackages.put(bp.name, pkgs);
10022                 }
10023                 pkgs.add(pkg.packageName);
10024             }
10025
10026             final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10027             final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10028                     >= Build.VERSION_CODES.M;
10029             switch (level) {
10030                 case PermissionInfo.PROTECTION_NORMAL: {
10031                     // For all apps normal permissions are install time ones.
10032                     grant = GRANT_INSTALL;
10033                 } break;
10034
10035                 case PermissionInfo.PROTECTION_DANGEROUS: {
10036                     // If a permission review is required for legacy apps we represent
10037                     // their permissions as always granted runtime ones since we need
10038                     // to keep the review required permission flag per user while an
10039                     // install permission's state is shared across all users.
10040                     if (!appSupportsRuntimePermissions && !mPermissionReviewRequired
10041                             && !Build.PERMISSIONS_REVIEW_REQUIRED) {
10042                         // For legacy apps dangerous permissions are install time ones.
10043                         grant = GRANT_INSTALL;
10044                     } else if (origPermissions.hasInstallPermission(bp.name)) {
10045                         // For legacy apps that became modern, install becomes runtime.
10046                         grant = GRANT_UPGRADE;
10047                     } else if (mPromoteSystemApps
10048                             && isSystemApp(ps)
10049                             && mExistingSystemPackages.contains(ps.name)) {
10050                         // For legacy system apps, install becomes runtime.
10051                         // We cannot check hasInstallPermission() for system apps since those
10052                         // permissions were granted implicitly and not persisted pre-M.
10053                         grant = GRANT_UPGRADE;
10054                     } else {
10055                         // For modern apps keep runtime permissions unchanged.
10056                         grant = GRANT_RUNTIME;
10057                     }
10058                 } break;
10059
10060                 case PermissionInfo.PROTECTION_SIGNATURE: {
10061                     // For all apps signature permissions are install time ones.
10062                     allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10063                     if (allowedSig) {
10064                         grant = GRANT_INSTALL;
10065                     }
10066                 } break;
10067             }
10068
10069             if (DEBUG_INSTALL) {
10070                 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10071             }
10072
10073             if (grant != GRANT_DENIED) {
10074                 if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10075                     // If this is an existing, non-system package, then
10076                     // we can't add any new permissions to it.
10077                     if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10078                         // Except...  if this is a permission that was added
10079                         // to the platform (note: need to only do this when
10080                         // updating the platform).
10081                         if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10082                             grant = GRANT_DENIED;
10083                         }
10084                     }
10085                 }
10086
10087                 switch (grant) {
10088                     case GRANT_INSTALL: {
10089                         // Revoke this as runtime permission to handle the case of
10090                         // a runtime permission being downgraded to an install one.
10091                         // Also in permission review mode we keep dangerous permissions
10092                         // for legacy apps
10093                         for (int userId : UserManagerService.getInstance().getUserIds()) {
10094                             if (origPermissions.getRuntimePermissionState(
10095                                     bp.name, userId) != null) {
10096                                 // Revoke the runtime permission and clear the flags.
10097                                 origPermissions.revokeRuntimePermission(bp, userId);
10098                                 origPermissions.updatePermissionFlags(bp, userId,
10099                                       PackageManager.MASK_PERMISSION_FLAGS, 0);
10100                                 // If we revoked a permission permission, we have to write.
10101                                 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10102                                         changedRuntimePermissionUserIds, userId);
10103                             }
10104                         }
10105                         // Grant an install permission.
10106                         if (permissionsState.grantInstallPermission(bp) !=
10107                                 PermissionsState.PERMISSION_OPERATION_FAILURE) {
10108                             changedInstallPermission = true;
10109                         }
10110                     } break;
10111
10112                     case GRANT_RUNTIME: {
10113                         // Grant previously granted runtime permissions.
10114                         for (int userId : UserManagerService.getInstance().getUserIds()) {
10115                             PermissionState permissionState = origPermissions
10116                                     .getRuntimePermissionState(bp.name, userId);
10117                             int flags = permissionState != null
10118                                     ? permissionState.getFlags() : 0;
10119                             if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10120                                 // Don't propagate the permission in a permission review mode if
10121                                 // the former was revoked, i.e. marked to not propagate on upgrade.
10122                                 // Note that in a permission review mode install permissions are
10123                                 // represented as constantly granted runtime ones since we need to
10124                                 // keep a per user state associated with the permission. Also the
10125                                 // revoke on upgrade flag is no longer applicable and is reset.
10126                                 final boolean revokeOnUpgrade = (flags & PackageManager
10127                                         .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
10128                                 if (revokeOnUpgrade) {
10129                                     flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
10130                                     // Since we changed the flags, we have to write.
10131                                     changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10132                                             changedRuntimePermissionUserIds, userId);
10133                                 }
10134                                 if (!mPermissionReviewRequired || !revokeOnUpgrade) {
10135                                     if (permissionsState.grantRuntimePermission(bp, userId) ==
10136                                             PermissionsState.PERMISSION_OPERATION_FAILURE) {
10137                                         // If we cannot put the permission as it was,
10138                                         // we have to write.
10139                                         changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10140                                                 changedRuntimePermissionUserIds, userId);
10141                                     }
10142                                 }
10143
10144                                 // If the app supports runtime permissions no need for a review.
10145                                 if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
10146                                         && appSupportsRuntimePermissions
10147                                         && (flags & PackageManager
10148                                                 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10149                                     flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10150                                     // Since we changed the flags, we have to write.
10151                                     changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10152                                             changedRuntimePermissionUserIds, userId);
10153                                 }
10154                             } else if ((mPermissionReviewRequired
10155                                         || Build.PERMISSIONS_REVIEW_REQUIRED)
10156                                     && !appSupportsRuntimePermissions) {
10157                                 // For legacy apps that need a permission review, every new
10158                                 // runtime permission is granted but it is pending a review.
10159                                 // We also need to review only platform defined runtime
10160                                 // permissions as these are the only ones the platform knows
10161                                 // how to disable the API to simulate revocation as legacy
10162                                 // apps don't expect to run with revoked permissions.
10163                                 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10164                                     if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10165                                         flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10166                                         // We changed the flags, hence have to write.
10167                                         changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10168                                                 changedRuntimePermissionUserIds, userId);
10169                                     }
10170                                 }
10171                                 if (permissionsState.grantRuntimePermission(bp, userId)
10172                                         != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10173                                     // We changed the permission, hence have to write.
10174                                     changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10175                                             changedRuntimePermissionUserIds, userId);
10176                                 }
10177                             }
10178                             // Propagate the permission flags.
10179                             permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10180                         }
10181                     } break;
10182
10183                     case GRANT_UPGRADE: {
10184                         // Grant runtime permissions for a previously held install permission.
10185                         PermissionState permissionState = origPermissions
10186                                 .getInstallPermissionState(bp.name);
10187                         final int flags = permissionState != null ? permissionState.getFlags() : 0;
10188
10189                         if (origPermissions.revokeInstallPermission(bp)
10190                                 != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10191                             // We will be transferring the permission flags, so clear them.
10192                             origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10193                                     PackageManager.MASK_PERMISSION_FLAGS, 0);
10194                             changedInstallPermission = true;
10195                         }
10196
10197                         // If the permission is not to be promoted to runtime we ignore it and
10198                         // also its other flags as they are not applicable to install permissions.
10199                         if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10200                             for (int userId : currentUserIds) {
10201                                 if (permissionsState.grantRuntimePermission(bp, userId) !=
10202                                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
10203                                     // Transfer the permission flags.
10204                                     permissionsState.updatePermissionFlags(bp, userId,
10205                                             flags, flags);
10206                                     // If we granted the permission, we have to write.
10207                                     changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10208                                             changedRuntimePermissionUserIds, userId);
10209                                 }
10210                             }
10211                         }
10212                     } break;
10213
10214                     default: {
10215                         if (packageOfInterest == null
10216                                 || packageOfInterest.equals(pkg.packageName)) {
10217                             Slog.w(TAG, "Not granting permission " + perm
10218                                     + " to package " + pkg.packageName
10219                                     + " because it was previously installed without");
10220                         }
10221                     } break;
10222                 }
10223             } else {
10224                 if (permissionsState.revokeInstallPermission(bp) !=
10225                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
10226                     // Also drop the permission flags.
10227                     permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10228                             PackageManager.MASK_PERMISSION_FLAGS, 0);
10229                     changedInstallPermission = true;
10230                     Slog.i(TAG, "Un-granting permission " + perm
10231                             + " from package " + pkg.packageName
10232                             + " (protectionLevel=" + bp.protectionLevel
10233                             + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10234                             + ")");
10235                 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10236                     // Don't print warning for app op permissions, since it is fine for them
10237                     // not to be granted, there is a UI for the user to decide.
10238                     if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10239                         Slog.w(TAG, "Not granting permission " + perm
10240                                 + " to package " + pkg.packageName
10241                                 + " (protectionLevel=" + bp.protectionLevel
10242                                 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10243                                 + ")");
10244                     }
10245                 }
10246             }
10247         }
10248
10249         if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10250                 !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10251             // This is the first that we have heard about this package, so the
10252             // permissions we have now selected are fixed until explicitly
10253             // changed.
10254             ps.installPermissionsFixed = true;
10255         }
10256
10257         // Persist the runtime permissions state for users with changes. If permissions
10258         // were revoked because no app in the shared user declares them we have to
10259         // write synchronously to avoid losing runtime permissions state.
10260         for (int userId : changedRuntimePermissionUserIds) {
10261             mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10262         }
10263
10264         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10265     }
10266
10267     private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10268         boolean allowed = false;
10269         final int NP = PackageParser.NEW_PERMISSIONS.length;
10270         for (int ip=0; ip<NP; ip++) {
10271             final PackageParser.NewPermissionInfo npi
10272                     = PackageParser.NEW_PERMISSIONS[ip];
10273             if (npi.name.equals(perm)
10274                     && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10275                 allowed = true;
10276                 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10277                         + pkg.packageName);
10278                 break;
10279             }
10280         }
10281         return allowed;
10282     }
10283
10284     private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10285             BasePermission bp, PermissionsState origPermissions) {
10286         boolean allowed;
10287         allowed = (compareSignatures(
10288                 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10289                         == PackageManager.SIGNATURE_MATCH)
10290                 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10291                         == PackageManager.SIGNATURE_MATCH);
10292         if (!allowed && (bp.protectionLevel
10293                 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10294             if (isSystemApp(pkg)) {
10295                 // For updated system applications, a system permission
10296                 // is granted only if it had been defined by the original application.
10297                 if (pkg.isUpdatedSystemApp()) {
10298                     final PackageSetting sysPs = mSettings
10299                             .getDisabledSystemPkgLPr(pkg.packageName);
10300                     if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10301                         // If the original was granted this permission, we take
10302                         // that grant decision as read and propagate it to the
10303                         // update.
10304                         if (sysPs.isPrivileged()) {
10305                             allowed = true;
10306                         }
10307                     } else {
10308                         // The system apk may have been updated with an older
10309                         // version of the one on the data partition, but which
10310                         // granted a new system permission that it didn't have
10311                         // before.  In this case we do want to allow the app to
10312                         // now get the new permission if the ancestral apk is
10313                         // privileged to get it.
10314                         if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10315                             for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10316                                 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10317                                     allowed = true;
10318                                     break;
10319                                 }
10320                             }
10321                         }
10322                         // Also if a privileged parent package on the system image or any of
10323                         // its children requested a privileged permission, the updated child
10324                         // packages can also get the permission.
10325                         if (pkg.parentPackage != null) {
10326                             final PackageSetting disabledSysParentPs = mSettings
10327                                     .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10328                             if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10329                                     && disabledSysParentPs.isPrivileged()) {
10330                                 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10331                                     allowed = true;
10332                                 } else if (disabledSysParentPs.pkg.childPackages != null) {
10333                                     final int count = disabledSysParentPs.pkg.childPackages.size();
10334                                     for (int i = 0; i < count; i++) {
10335                                         PackageParser.Package disabledSysChildPkg =
10336                                                 disabledSysParentPs.pkg.childPackages.get(i);
10337                                         if (isPackageRequestingPermission(disabledSysChildPkg,
10338                                                 perm)) {
10339                                             allowed = true;
10340                                             break;
10341                                         }
10342                                     }
10343                                 }
10344                             }
10345                         }
10346                     }
10347                 } else {
10348                     allowed = isPrivilegedApp(pkg);
10349                 }
10350             }
10351         }
10352         if (!allowed) {
10353             if (!allowed && (bp.protectionLevel
10354                     & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10355                     && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10356                 // If this was a previously normal/dangerous permission that got moved
10357                 // to a system permission as part of the runtime permission redesign, then
10358                 // we still want to blindly grant it to old apps.
10359                 allowed = true;
10360             }
10361             if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10362                     && pkg.packageName.equals(mRequiredInstallerPackage)) {
10363                 // If this permission is to be granted to the system installer and
10364                 // this app is an installer, then it gets the permission.
10365                 allowed = true;
10366             }
10367             if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10368                     && pkg.packageName.equals(mRequiredVerifierPackage)) {
10369                 // If this permission is to be granted to the system verifier and
10370                 // this app is a verifier, then it gets the permission.
10371                 allowed = true;
10372             }
10373             if (!allowed && (bp.protectionLevel
10374                     & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10375                     && isSystemApp(pkg)) {
10376                 // Any pre-installed system app is allowed to get this permission.
10377                 allowed = true;
10378             }
10379             if (!allowed && (bp.protectionLevel
10380                     & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10381                 // For development permissions, a development permission
10382                 // is granted only if it was already granted.
10383                 allowed = origPermissions.hasInstallPermission(perm);
10384             }
10385             if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10386                     && pkg.packageName.equals(mSetupWizardPackage)) {
10387                 // If this permission is to be granted to the system setup wizard and
10388                 // this app is a setup wizard, then it gets the permission.
10389                 allowed = true;
10390             }
10391         }
10392         return allowed;
10393     }
10394
10395     private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10396         final int permCount = pkg.requestedPermissions.size();
10397         for (int j = 0; j < permCount; j++) {
10398             String requestedPermission = pkg.requestedPermissions.get(j);
10399             if (permission.equals(requestedPermission)) {
10400                 return true;
10401             }
10402         }
10403         return false;
10404     }
10405
10406     final class ActivityIntentResolver
10407             extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10408         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10409                 boolean defaultOnly, int userId) {
10410             if (!sUserManager.exists(userId)) return null;
10411             mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10412             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10413         }
10414
10415         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10416                 int userId) {
10417             if (!sUserManager.exists(userId)) return null;
10418             mFlags = flags;
10419             return super.queryIntent(intent, resolvedType,
10420                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10421         }
10422
10423         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10424                 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10425             if (!sUserManager.exists(userId)) return null;
10426             if (packageActivities == null) {
10427                 return null;
10428             }
10429             mFlags = flags;
10430             final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10431             final int N = packageActivities.size();
10432             ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10433                 new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10434
10435             ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10436             for (int i = 0; i < N; ++i) {
10437                 intentFilters = packageActivities.get(i).intents;
10438                 if (intentFilters != null && intentFilters.size() > 0) {
10439                     PackageParser.ActivityIntentInfo[] array =
10440                             new PackageParser.ActivityIntentInfo[intentFilters.size()];
10441                     intentFilters.toArray(array);
10442                     listCut.add(array);
10443                 }
10444             }
10445             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10446         }
10447
10448         /**
10449          * Finds a privileged activity that matches the specified activity names.
10450          */
10451         private PackageParser.Activity findMatchingActivity(
10452                 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10453             for (PackageParser.Activity sysActivity : activityList) {
10454                 if (sysActivity.info.name.equals(activityInfo.name)) {
10455                     return sysActivity;
10456                 }
10457                 if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10458                     return sysActivity;
10459                 }
10460                 if (sysActivity.info.targetActivity != null) {
10461                     if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10462                         return sysActivity;
10463                     }
10464                     if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10465                         return sysActivity;
10466                     }
10467                 }
10468             }
10469             return null;
10470         }
10471
10472         public class IterGenerator<E> {
10473             public Iterator<E> generate(ActivityIntentInfo info) {
10474                 return null;
10475             }
10476         }
10477
10478         public class ActionIterGenerator extends IterGenerator<String> {
10479             @Override
10480             public Iterator<String> generate(ActivityIntentInfo info) {
10481                 return info.actionsIterator();
10482             }
10483         }
10484
10485         public class CategoriesIterGenerator extends IterGenerator<String> {
10486             @Override
10487             public Iterator<String> generate(ActivityIntentInfo info) {
10488                 return info.categoriesIterator();
10489             }
10490         }
10491
10492         public class SchemesIterGenerator extends IterGenerator<String> {
10493             @Override
10494             public Iterator<String> generate(ActivityIntentInfo info) {
10495                 return info.schemesIterator();
10496             }
10497         }
10498
10499         public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10500             @Override
10501             public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10502                 return info.authoritiesIterator();
10503             }
10504         }
10505
10506         /**
10507          * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10508          * MODIFIED. Do not pass in a list that should not be changed.
10509          */
10510         private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10511                 IterGenerator<T> generator, Iterator<T> searchIterator) {
10512             // loop through the set of actions; every one must be found in the intent filter
10513             while (searchIterator.hasNext()) {
10514                 // we must have at least one filter in the list to consider a match
10515                 if (intentList.size() == 0) {
10516                     break;
10517                 }
10518
10519                 final T searchAction = searchIterator.next();
10520
10521                 // loop through the set of intent filters
10522                 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10523                 while (intentIter.hasNext()) {
10524                     final ActivityIntentInfo intentInfo = intentIter.next();
10525                     boolean selectionFound = false;
10526
10527                     // loop through the intent filter's selection criteria; at least one
10528                     // of them must match the searched criteria
10529                     final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10530                     while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10531                         final T intentSelection = intentSelectionIter.next();
10532                         if (intentSelection != null && intentSelection.equals(searchAction)) {
10533                             selectionFound = true;
10534                             break;
10535                         }
10536                     }
10537
10538                     // the selection criteria wasn't found in this filter's set; this filter
10539                     // is not a potential match
10540                     if (!selectionFound) {
10541                         intentIter.remove();
10542                     }
10543                 }
10544             }
10545         }
10546
10547         private boolean isProtectedAction(ActivityIntentInfo filter) {
10548             final Iterator<String> actionsIter = filter.actionsIterator();
10549             while (actionsIter != null && actionsIter.hasNext()) {
10550                 final String filterAction = actionsIter.next();
10551                 if (PROTECTED_ACTIONS.contains(filterAction)) {
10552                     return true;
10553                 }
10554             }
10555             return false;
10556         }
10557
10558         /**
10559          * Adjusts the priority of the given intent filter according to policy.
10560          * <p>
10561          * <ul>
10562          * <li>The priority for non privileged applications is capped to '0'</li>
10563          * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10564          * <li>The priority for unbundled updates to privileged applications is capped to the
10565          *      priority defined on the system partition</li>
10566          * </ul>
10567          * <p>
10568          * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10569          * allowed to obtain any priority on any action.
10570          */
10571         private void adjustPriority(
10572                 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10573             // nothing to do; priority is fine as-is
10574             if (intent.getPriority() <= 0) {
10575                 return;
10576             }
10577
10578             final ActivityInfo activityInfo = intent.activity.info;
10579             final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10580
10581             final boolean privilegedApp =
10582                     ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10583             if (!privilegedApp) {
10584                 // non-privileged applications can never define a priority >0
10585                 Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10586                         + " package: " + applicationInfo.packageName
10587                         + " activity: " + intent.activity.className
10588                         + " origPrio: " + intent.getPriority());
10589                 intent.setPriority(0);
10590                 return;
10591             }
10592
10593             if (systemActivities == null) {
10594                 // the system package is not disabled; we're parsing the system partition
10595                 if (isProtectedAction(intent)) {
10596                     if (mDeferProtectedFilters) {
10597                         // We can't deal with these just yet. No component should ever obtain a
10598                         // >0 priority for a protected actions, with ONE exception -- the setup
10599                         // wizard. The setup wizard, however, cannot be known until we're able to
10600                         // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10601                         // until all intent filters have been processed. Chicken, meet egg.
10602                         // Let the filter temporarily have a high priority and rectify the
10603                         // priorities after all system packages have been scanned.
10604                         mProtectedFilters.add(intent);
10605                         if (DEBUG_FILTERS) {
10606                             Slog.i(TAG, "Protected action; save for later;"
10607                                     + " package: " + applicationInfo.packageName
10608                                     + " activity: " + intent.activity.className
10609                                     + " origPrio: " + intent.getPriority());
10610                         }
10611                         return;
10612                     } else {
10613                         if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10614                             Slog.i(TAG, "No setup wizard;"
10615                                 + " All protected intents capped to priority 0");
10616                         }
10617                         if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10618                             if (DEBUG_FILTERS) {
10619                                 Slog.i(TAG, "Found setup wizard;"
10620                                     + " allow priority " + intent.getPriority() + ";"
10621                                     + " package: " + intent.activity.info.packageName
10622                                     + " activity: " + intent.activity.className
10623                                     + " priority: " + intent.getPriority());
10624                             }
10625                             // setup wizard gets whatever it wants
10626                             return;
10627                         }
10628                         Slog.w(TAG, "Protected action; cap priority to 0;"
10629                                 + " package: " + intent.activity.info.packageName
10630                                 + " activity: " + intent.activity.className
10631                                 + " origPrio: " + intent.getPriority());
10632                         intent.setPriority(0);
10633                         return;
10634                     }
10635                 }
10636                 // privileged apps on the system image get whatever priority they request
10637                 return;
10638             }
10639
10640             // privileged app unbundled update ... try to find the same activity
10641             final PackageParser.Activity foundActivity =
10642                     findMatchingActivity(systemActivities, activityInfo);
10643             if (foundActivity == null) {
10644                 // this is a new activity; it cannot obtain >0 priority
10645                 if (DEBUG_FILTERS) {
10646                     Slog.i(TAG, "New activity; cap priority to 0;"
10647                             + " package: " + applicationInfo.packageName
10648                             + " activity: " + intent.activity.className
10649                             + " origPrio: " + intent.getPriority());
10650                 }
10651                 intent.setPriority(0);
10652                 return;
10653             }
10654
10655             // found activity, now check for filter equivalence
10656
10657             // a shallow copy is enough; we modify the list, not its contents
10658             final List<ActivityIntentInfo> intentListCopy =
10659                     new ArrayList<>(foundActivity.intents);
10660             final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10661
10662             // find matching action subsets
10663             final Iterator<String> actionsIterator = intent.actionsIterator();
10664             if (actionsIterator != null) {
10665                 getIntentListSubset(
10666                         intentListCopy, new ActionIterGenerator(), actionsIterator);
10667                 if (intentListCopy.size() == 0) {
10668                     // no more intents to match; we're not equivalent
10669                     if (DEBUG_FILTERS) {
10670                         Slog.i(TAG, "Mismatched action; cap priority to 0;"
10671                                 + " package: " + applicationInfo.packageName
10672                                 + " activity: " + intent.activity.className
10673                                 + " origPrio: " + intent.getPriority());
10674                     }
10675                     intent.setPriority(0);
10676                     return;
10677                 }
10678             }
10679
10680             // find matching category subsets
10681             final Iterator<String> categoriesIterator = intent.categoriesIterator();
10682             if (categoriesIterator != null) {
10683                 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10684                         categoriesIterator);
10685                 if (intentListCopy.size() == 0) {
10686                     // no more intents to match; we're not equivalent
10687                     if (DEBUG_FILTERS) {
10688                         Slog.i(TAG, "Mismatched category; cap priority to 0;"
10689                                 + " package: " + applicationInfo.packageName
10690                                 + " activity: " + intent.activity.className
10691                                 + " origPrio: " + intent.getPriority());
10692                     }
10693                     intent.setPriority(0);
10694                     return;
10695                 }
10696             }
10697
10698             // find matching schemes subsets
10699             final Iterator<String> schemesIterator = intent.schemesIterator();
10700             if (schemesIterator != null) {
10701                 getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10702                         schemesIterator);
10703                 if (intentListCopy.size() == 0) {
10704                     // no more intents to match; we're not equivalent
10705                     if (DEBUG_FILTERS) {
10706                         Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10707                                 + " package: " + applicationInfo.packageName
10708                                 + " activity: " + intent.activity.className
10709                                 + " origPrio: " + intent.getPriority());
10710                     }
10711                     intent.setPriority(0);
10712                     return;
10713                 }
10714             }
10715
10716             // find matching authorities subsets
10717             final Iterator<IntentFilter.AuthorityEntry>
10718                     authoritiesIterator = intent.authoritiesIterator();
10719             if (authoritiesIterator != null) {
10720                 getIntentListSubset(intentListCopy,
10721                         new AuthoritiesIterGenerator(),
10722                         authoritiesIterator);
10723                 if (intentListCopy.size() == 0) {
10724                     // no more intents to match; we're not equivalent
10725                     if (DEBUG_FILTERS) {
10726                         Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10727                                 + " package: " + applicationInfo.packageName
10728                                 + " activity: " + intent.activity.className
10729                                 + " origPrio: " + intent.getPriority());
10730                     }
10731                     intent.setPriority(0);
10732                     return;
10733                 }
10734             }
10735
10736             // we found matching filter(s); app gets the max priority of all intents
10737             int cappedPriority = 0;
10738             for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10739                 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10740             }
10741             if (intent.getPriority() > cappedPriority) {
10742                 if (DEBUG_FILTERS) {
10743                     Slog.i(TAG, "Found matching filter(s);"
10744                             + " cap priority to " + cappedPriority + ";"
10745                             + " package: " + applicationInfo.packageName
10746                             + " activity: " + intent.activity.className
10747                             + " origPrio: " + intent.getPriority());
10748                 }
10749                 intent.setPriority(cappedPriority);
10750                 return;
10751             }
10752             // all this for nothing; the requested priority was <= what was on the system
10753         }
10754
10755         public final void addActivity(PackageParser.Activity a, String type) {
10756             mActivities.put(a.getComponentName(), a);
10757             if (DEBUG_SHOW_INFO)
10758                 Log.v(
10759                 TAG, "  " + type + " " +
10760                 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10761             if (DEBUG_SHOW_INFO)
10762                 Log.v(TAG, "    Class=" + a.info.name);
10763             final int NI = a.intents.size();
10764             for (int j=0; j<NI; j++) {
10765                 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10766                 if ("activity".equals(type)) {
10767                     final PackageSetting ps =
10768                             mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10769                     final List<PackageParser.Activity> systemActivities =
10770                             ps != null && ps.pkg != null ? ps.pkg.activities : null;
10771                     adjustPriority(systemActivities, intent);
10772                 }
10773                 if (DEBUG_SHOW_INFO) {
10774                     Log.v(TAG, "    IntentFilter:");
10775                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10776                 }
10777                 if (!intent.debugCheck()) {
10778                     Log.w(TAG, "==> For Activity " + a.info.name);
10779                 }
10780                 addFilter(intent);
10781             }
10782         }
10783
10784         public final void removeActivity(PackageParser.Activity a, String type) {
10785             mActivities.remove(a.getComponentName());
10786             if (DEBUG_SHOW_INFO) {
10787                 Log.v(TAG, "  " + type + " "
10788                         + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10789                                 : a.info.name) + ":");
10790                 Log.v(TAG, "    Class=" + a.info.name);
10791             }
10792             final int NI = a.intents.size();
10793             for (int j=0; j<NI; j++) {
10794                 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10795                 if (DEBUG_SHOW_INFO) {
10796                     Log.v(TAG, "    IntentFilter:");
10797                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10798                 }
10799                 removeFilter(intent);
10800             }
10801         }
10802
10803         @Override
10804         protected boolean allowFilterResult(
10805                 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10806             ActivityInfo filterAi = filter.activity.info;
10807             for (int i=dest.size()-1; i>=0; i--) {
10808                 ActivityInfo destAi = dest.get(i).activityInfo;
10809                 if (destAi.name == filterAi.name
10810                         && destAi.packageName == filterAi.packageName) {
10811                     return false;
10812                 }
10813             }
10814             return true;
10815         }
10816
10817         @Override
10818         protected ActivityIntentInfo[] newArray(int size) {
10819             return new ActivityIntentInfo[size];
10820         }
10821
10822         @Override
10823         protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10824             if (!sUserManager.exists(userId)) return true;
10825             PackageParser.Package p = filter.activity.owner;
10826             if (p != null) {
10827                 PackageSetting ps = (PackageSetting)p.mExtras;
10828                 if (ps != null) {
10829                     // System apps are never considered stopped for purposes of
10830                     // filtering, because there may be no way for the user to
10831                     // actually re-launch them.
10832                     return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10833                             && ps.getStopped(userId);
10834                 }
10835             }
10836             return false;
10837         }
10838
10839         @Override
10840         protected boolean isPackageForFilter(String packageName,
10841                 PackageParser.ActivityIntentInfo info) {
10842             return packageName.equals(info.activity.owner.packageName);
10843         }
10844
10845         @Override
10846         protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10847                 int match, int userId) {
10848             if (!sUserManager.exists(userId)) return null;
10849             if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10850                 return null;
10851             }
10852             final PackageParser.Activity activity = info.activity;
10853             PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10854             if (ps == null) {
10855                 return null;
10856             }
10857             ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10858                     ps.readUserState(userId), userId);
10859             if (ai == null) {
10860                 return null;
10861             }
10862             final ResolveInfo res = new ResolveInfo();
10863             res.activityInfo = ai;
10864             if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10865                 res.filter = info;
10866             }
10867             if (info != null) {
10868                 res.handleAllWebDataURI = info.handleAllWebDataURI();
10869             }
10870             res.priority = info.getPriority();
10871             res.preferredOrder = activity.owner.mPreferredOrder;
10872             //System.out.println("Result: " + res.activityInfo.className +
10873             //                   " = " + res.priority);
10874             res.match = match;
10875             res.isDefault = info.hasDefault;
10876             res.labelRes = info.labelRes;
10877             res.nonLocalizedLabel = info.nonLocalizedLabel;
10878             if (userNeedsBadging(userId)) {
10879                 res.noResourceId = true;
10880             } else {
10881                 res.icon = info.icon;
10882             }
10883             res.iconResourceId = info.icon;
10884             res.system = res.activityInfo.applicationInfo.isSystemApp();
10885             return res;
10886         }
10887
10888         @Override
10889         protected void sortResults(List<ResolveInfo> results) {
10890             Collections.sort(results, mResolvePrioritySorter);
10891         }
10892
10893         @Override
10894         protected void dumpFilter(PrintWriter out, String prefix,
10895                 PackageParser.ActivityIntentInfo filter) {
10896             out.print(prefix); out.print(
10897                     Integer.toHexString(System.identityHashCode(filter.activity)));
10898                     out.print(' ');
10899                     filter.activity.printComponentShortName(out);
10900                     out.print(" filter ");
10901                     out.println(Integer.toHexString(System.identityHashCode(filter)));
10902         }
10903
10904         @Override
10905         protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10906             return filter.activity;
10907         }
10908
10909         protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10910             PackageParser.Activity activity = (PackageParser.Activity)label;
10911             out.print(prefix); out.print(
10912                     Integer.toHexString(System.identityHashCode(activity)));
10913                     out.print(' ');
10914                     activity.printComponentShortName(out);
10915             if (count > 1) {
10916                 out.print(" ("); out.print(count); out.print(" filters)");
10917             }
10918             out.println();
10919         }
10920
10921         // Keys are String (activity class name), values are Activity.
10922         private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10923                 = new ArrayMap<ComponentName, PackageParser.Activity>();
10924         private int mFlags;
10925     }
10926
10927     private final class ServiceIntentResolver
10928             extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10929         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10930                 boolean defaultOnly, int userId) {
10931             mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10932             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10933         }
10934
10935         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10936                 int userId) {
10937             if (!sUserManager.exists(userId)) return null;
10938             mFlags = flags;
10939             return super.queryIntent(intent, resolvedType,
10940                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10941         }
10942
10943         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10944                 int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10945             if (!sUserManager.exists(userId)) return null;
10946             if (packageServices == null) {
10947                 return null;
10948             }
10949             mFlags = flags;
10950             final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10951             final int N = packageServices.size();
10952             ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10953                 new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10954
10955             ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10956             for (int i = 0; i < N; ++i) {
10957                 intentFilters = packageServices.get(i).intents;
10958                 if (intentFilters != null && intentFilters.size() > 0) {
10959                     PackageParser.ServiceIntentInfo[] array =
10960                             new PackageParser.ServiceIntentInfo[intentFilters.size()];
10961                     intentFilters.toArray(array);
10962                     listCut.add(array);
10963                 }
10964             }
10965             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10966         }
10967
10968         public final void addService(PackageParser.Service s) {
10969             mServices.put(s.getComponentName(), s);
10970             if (DEBUG_SHOW_INFO) {
10971                 Log.v(TAG, "  "
10972                         + (s.info.nonLocalizedLabel != null
10973                         ? s.info.nonLocalizedLabel : s.info.name) + ":");
10974                 Log.v(TAG, "    Class=" + s.info.name);
10975             }
10976             final int NI = s.intents.size();
10977             int j;
10978             for (j=0; j<NI; j++) {
10979                 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10980                 if (DEBUG_SHOW_INFO) {
10981                     Log.v(TAG, "    IntentFilter:");
10982                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10983                 }
10984                 if (!intent.debugCheck()) {
10985                     Log.w(TAG, "==> For Service " + s.info.name);
10986                 }
10987                 addFilter(intent);
10988             }
10989         }
10990
10991         public final void removeService(PackageParser.Service s) {
10992             mServices.remove(s.getComponentName());
10993             if (DEBUG_SHOW_INFO) {
10994                 Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10995                         ? s.info.nonLocalizedLabel : s.info.name) + ":");
10996                 Log.v(TAG, "    Class=" + s.info.name);
10997             }
10998             final int NI = s.intents.size();
10999             int j;
11000             for (j=0; j<NI; j++) {
11001                 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
11002                 if (DEBUG_SHOW_INFO) {
11003                     Log.v(TAG, "    IntentFilter:");
11004                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11005                 }
11006                 removeFilter(intent);
11007             }
11008         }
11009
11010         @Override
11011         protected boolean allowFilterResult(
11012                 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
11013             ServiceInfo filterSi = filter.service.info;
11014             for (int i=dest.size()-1; i>=0; i--) {
11015                 ServiceInfo destAi = dest.get(i).serviceInfo;
11016                 if (destAi.name == filterSi.name
11017                         && destAi.packageName == filterSi.packageName) {
11018                     return false;
11019                 }
11020             }
11021             return true;
11022         }
11023
11024         @Override
11025         protected PackageParser.ServiceIntentInfo[] newArray(int size) {
11026             return new PackageParser.ServiceIntentInfo[size];
11027         }
11028
11029         @Override
11030         protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
11031             if (!sUserManager.exists(userId)) return true;
11032             PackageParser.Package p = filter.service.owner;
11033             if (p != null) {
11034                 PackageSetting ps = (PackageSetting)p.mExtras;
11035                 if (ps != null) {
11036                     // System apps are never considered stopped for purposes of
11037                     // filtering, because there may be no way for the user to
11038                     // actually re-launch them.
11039                     return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11040                             && ps.getStopped(userId);
11041                 }
11042             }
11043             return false;
11044         }
11045
11046         @Override
11047         protected boolean isPackageForFilter(String packageName,
11048                 PackageParser.ServiceIntentInfo info) {
11049             return packageName.equals(info.service.owner.packageName);
11050         }
11051
11052         @Override
11053         protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11054                 int match, int userId) {
11055             if (!sUserManager.exists(userId)) return null;
11056             final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11057             if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11058                 return null;
11059             }
11060             final PackageParser.Service service = info.service;
11061             PackageSetting ps = (PackageSetting) service.owner.mExtras;
11062             if (ps == null) {
11063                 return null;
11064             }
11065             ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11066                     ps.readUserState(userId), userId);
11067             if (si == null) {
11068                 return null;
11069             }
11070             final ResolveInfo res = new ResolveInfo();
11071             res.serviceInfo = si;
11072             if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11073                 res.filter = filter;
11074             }
11075             res.priority = info.getPriority();
11076             res.preferredOrder = service.owner.mPreferredOrder;
11077             res.match = match;
11078             res.isDefault = info.hasDefault;
11079             res.labelRes = info.labelRes;
11080             res.nonLocalizedLabel = info.nonLocalizedLabel;
11081             res.icon = info.icon;
11082             res.system = res.serviceInfo.applicationInfo.isSystemApp();
11083             return res;
11084         }
11085
11086         @Override
11087         protected void sortResults(List<ResolveInfo> results) {
11088             Collections.sort(results, mResolvePrioritySorter);
11089         }
11090
11091         @Override
11092         protected void dumpFilter(PrintWriter out, String prefix,
11093                 PackageParser.ServiceIntentInfo filter) {
11094             out.print(prefix); out.print(
11095                     Integer.toHexString(System.identityHashCode(filter.service)));
11096                     out.print(' ');
11097                     filter.service.printComponentShortName(out);
11098                     out.print(" filter ");
11099                     out.println(Integer.toHexString(System.identityHashCode(filter)));
11100         }
11101
11102         @Override
11103         protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11104             return filter.service;
11105         }
11106
11107         protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11108             PackageParser.Service service = (PackageParser.Service)label;
11109             out.print(prefix); out.print(
11110                     Integer.toHexString(System.identityHashCode(service)));
11111                     out.print(' ');
11112                     service.printComponentShortName(out);
11113             if (count > 1) {
11114                 out.print(" ("); out.print(count); out.print(" filters)");
11115             }
11116             out.println();
11117         }
11118
11119 //        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11120 //            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11121 //            final List<ResolveInfo> retList = Lists.newArrayList();
11122 //            while (i.hasNext()) {
11123 //                final ResolveInfo resolveInfo = (ResolveInfo) i;
11124 //                if (isEnabledLP(resolveInfo.serviceInfo)) {
11125 //                    retList.add(resolveInfo);
11126 //                }
11127 //            }
11128 //            return retList;
11129 //        }
11130
11131         // Keys are String (activity class name), values are Activity.
11132         private final ArrayMap<ComponentName, PackageParser.Service> mServices
11133                 = new ArrayMap<ComponentName, PackageParser.Service>();
11134         private int mFlags;
11135     };
11136
11137     private final class ProviderIntentResolver
11138             extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11139         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11140                 boolean defaultOnly, int userId) {
11141             mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11142             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11143         }
11144
11145         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11146                 int userId) {
11147             if (!sUserManager.exists(userId))
11148                 return null;
11149             mFlags = flags;
11150             return super.queryIntent(intent, resolvedType,
11151                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11152         }
11153
11154         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11155                 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11156             if (!sUserManager.exists(userId))
11157                 return null;
11158             if (packageProviders == null) {
11159                 return null;
11160             }
11161             mFlags = flags;
11162             final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11163             final int N = packageProviders.size();
11164             ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11165                     new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11166
11167             ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11168             for (int i = 0; i < N; ++i) {
11169                 intentFilters = packageProviders.get(i).intents;
11170                 if (intentFilters != null && intentFilters.size() > 0) {
11171                     PackageParser.ProviderIntentInfo[] array =
11172                             new PackageParser.ProviderIntentInfo[intentFilters.size()];
11173                     intentFilters.toArray(array);
11174                     listCut.add(array);
11175                 }
11176             }
11177             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11178         }
11179
11180         public final void addProvider(PackageParser.Provider p) {
11181             if (mProviders.containsKey(p.getComponentName())) {
11182                 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11183                 return;
11184             }
11185
11186             mProviders.put(p.getComponentName(), p);
11187             if (DEBUG_SHOW_INFO) {
11188                 Log.v(TAG, "  "
11189                         + (p.info.nonLocalizedLabel != null
11190                                 ? p.info.nonLocalizedLabel : p.info.name) + ":");
11191                 Log.v(TAG, "    Class=" + p.info.name);
11192             }
11193             final int NI = p.intents.size();
11194             int j;
11195             for (j = 0; j < NI; j++) {
11196                 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11197                 if (DEBUG_SHOW_INFO) {
11198                     Log.v(TAG, "    IntentFilter:");
11199                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11200                 }
11201                 if (!intent.debugCheck()) {
11202                     Log.w(TAG, "==> For Provider " + p.info.name);
11203                 }
11204                 addFilter(intent);
11205             }
11206         }
11207
11208         public final void removeProvider(PackageParser.Provider p) {
11209             mProviders.remove(p.getComponentName());
11210             if (DEBUG_SHOW_INFO) {
11211                 Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11212                         ? p.info.nonLocalizedLabel : p.info.name) + ":");
11213                 Log.v(TAG, "    Class=" + p.info.name);
11214             }
11215             final int NI = p.intents.size();
11216             int j;
11217             for (j = 0; j < NI; j++) {
11218                 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11219                 if (DEBUG_SHOW_INFO) {
11220                     Log.v(TAG, "    IntentFilter:");
11221                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11222                 }
11223                 removeFilter(intent);
11224             }
11225         }
11226
11227         @Override
11228         protected boolean allowFilterResult(
11229                 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11230             ProviderInfo filterPi = filter.provider.info;
11231             for (int i = dest.size() - 1; i >= 0; i--) {
11232                 ProviderInfo destPi = dest.get(i).providerInfo;
11233                 if (destPi.name == filterPi.name
11234                         && destPi.packageName == filterPi.packageName) {
11235                     return false;
11236                 }
11237             }
11238             return true;
11239         }
11240
11241         @Override
11242         protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11243             return new PackageParser.ProviderIntentInfo[size];
11244         }
11245
11246         @Override
11247         protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11248             if (!sUserManager.exists(userId))
11249                 return true;
11250             PackageParser.Package p = filter.provider.owner;
11251             if (p != null) {
11252                 PackageSetting ps = (PackageSetting) p.mExtras;
11253                 if (ps != null) {
11254                     // System apps are never considered stopped for purposes of
11255                     // filtering, because there may be no way for the user to
11256                     // actually re-launch them.
11257                     return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11258                             && ps.getStopped(userId);
11259                 }
11260             }
11261             return false;
11262         }
11263
11264         @Override
11265         protected boolean isPackageForFilter(String packageName,
11266                 PackageParser.ProviderIntentInfo info) {
11267             return packageName.equals(info.provider.owner.packageName);
11268         }
11269
11270         @Override
11271         protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11272                 int match, int userId) {
11273             if (!sUserManager.exists(userId))
11274                 return null;
11275             final PackageParser.ProviderIntentInfo info = filter;
11276             if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11277                 return null;
11278             }
11279             final PackageParser.Provider provider = info.provider;
11280             PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11281             if (ps == null) {
11282                 return null;
11283             }
11284             ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11285                     ps.readUserState(userId), userId);
11286             if (pi == null) {
11287                 return null;
11288             }
11289             final ResolveInfo res = new ResolveInfo();
11290             res.providerInfo = pi;
11291             if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11292                 res.filter = filter;
11293             }
11294             res.priority = info.getPriority();
11295             res.preferredOrder = provider.owner.mPreferredOrder;
11296             res.match = match;
11297             res.isDefault = info.hasDefault;
11298             res.labelRes = info.labelRes;
11299             res.nonLocalizedLabel = info.nonLocalizedLabel;
11300             res.icon = info.icon;
11301             res.system = res.providerInfo.applicationInfo.isSystemApp();
11302             return res;
11303         }
11304
11305         @Override
11306         protected void sortResults(List<ResolveInfo> results) {
11307             Collections.sort(results, mResolvePrioritySorter);
11308         }
11309
11310         @Override
11311         protected void dumpFilter(PrintWriter out, String prefix,
11312                 PackageParser.ProviderIntentInfo filter) {
11313             out.print(prefix);
11314             out.print(
11315                     Integer.toHexString(System.identityHashCode(filter.provider)));
11316             out.print(' ');
11317             filter.provider.printComponentShortName(out);
11318             out.print(" filter ");
11319             out.println(Integer.toHexString(System.identityHashCode(filter)));
11320         }
11321
11322         @Override
11323         protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11324             return filter.provider;
11325         }
11326
11327         protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11328             PackageParser.Provider provider = (PackageParser.Provider)label;
11329             out.print(prefix); out.print(
11330                     Integer.toHexString(System.identityHashCode(provider)));
11331                     out.print(' ');
11332                     provider.printComponentShortName(out);
11333             if (count > 1) {
11334                 out.print(" ("); out.print(count); out.print(" filters)");
11335             }
11336             out.println();
11337         }
11338
11339         private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11340                 = new ArrayMap<ComponentName, PackageParser.Provider>();
11341         private int mFlags;
11342     }
11343
11344     private static final class EphemeralIntentResolver
11345             extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11346         /**
11347          * The result that has the highest defined order. Ordering applies on a
11348          * per-package basis. Mapping is from package name to Pair of order and
11349          * EphemeralResolveInfo.
11350          * <p>
11351          * NOTE: This is implemented as a field variable for convenience and efficiency.
11352          * By having a field variable, we're able to track filter ordering as soon as
11353          * a non-zero order is defined. Otherwise, multiple loops across the result set
11354          * would be needed to apply ordering. If the intent resolver becomes re-entrant,
11355          * this needs to be contained entirely within {@link #filterResults()}.
11356          */
11357         final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
11358
11359         @Override
11360         protected EphemeralResolveIntentInfo[] newArray(int size) {
11361             return new EphemeralResolveIntentInfo[size];
11362         }
11363
11364         @Override
11365         protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11366             return true;
11367         }
11368
11369         @Override
11370         protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11371                 int userId) {
11372             if (!sUserManager.exists(userId)) {
11373                 return null;
11374             }
11375             final String packageName = info.getEphemeralResolveInfo().getPackageName();
11376             final Integer order = info.getOrder();
11377             final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
11378                     mOrderResult.get(packageName);
11379             // ordering is enabled and this item's order isn't high enough
11380             if (lastOrderResult != null && lastOrderResult.first >= order) {
11381                 return null;
11382             }
11383             final EphemeralResolveInfo res = info.getEphemeralResolveInfo();
11384             if (order > 0) {
11385                 // non-zero order, enable ordering
11386                 mOrderResult.put(packageName, new Pair<>(order, res));
11387             }
11388             return res;
11389         }
11390
11391         @Override
11392         protected void filterResults(List<EphemeralResolveInfo> results) {
11393             // only do work if ordering is enabled [most of the time it won't be]
11394             if (mOrderResult.size() == 0) {
11395                 return;
11396             }
11397             int resultSize = results.size();
11398             for (int i = 0; i < resultSize; i++) {
11399                 final EphemeralResolveInfo info = results.get(i);
11400                 final String packageName = info.getPackageName();
11401                 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
11402                 if (savedInfo == null) {
11403                     // package doesn't having ordering
11404                     continue;
11405                 }
11406                 if (savedInfo.second == info) {
11407                     // circled back to the highest ordered item; remove from order list
11408                     mOrderResult.remove(savedInfo);
11409                     if (mOrderResult.size() == 0) {
11410                         // no more ordered items
11411                         break;
11412                     }
11413                     continue;
11414                 }
11415                 // item has a worse order, remove it from the result list
11416                 results.remove(i);
11417                 resultSize--;
11418                 i--;
11419             }
11420         }
11421     }
11422
11423     private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11424             new Comparator<ResolveInfo>() {
11425         public int compare(ResolveInfo r1, ResolveInfo r2) {
11426             int v1 = r1.priority;
11427             int v2 = r2.priority;
11428             //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11429             if (v1 != v2) {
11430                 return (v1 > v2) ? -1 : 1;
11431             }
11432             v1 = r1.preferredOrder;
11433             v2 = r2.preferredOrder;
11434             if (v1 != v2) {
11435                 return (v1 > v2) ? -1 : 1;
11436             }
11437             if (r1.isDefault != r2.isDefault) {
11438                 return r1.isDefault ? -1 : 1;
11439             }
11440             v1 = r1.match;
11441             v2 = r2.match;
11442             //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11443             if (v1 != v2) {
11444                 return (v1 > v2) ? -1 : 1;
11445             }
11446             if (r1.system != r2.system) {
11447                 return r1.system ? -1 : 1;
11448             }
11449             if (r1.activityInfo != null) {
11450                 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11451             }
11452             if (r1.serviceInfo != null) {
11453                 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11454             }
11455             if (r1.providerInfo != null) {
11456                 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11457             }
11458             return 0;
11459         }
11460     };
11461
11462     private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11463             new Comparator<ProviderInfo>() {
11464         public int compare(ProviderInfo p1, ProviderInfo p2) {
11465             final int v1 = p1.initOrder;
11466             final int v2 = p2.initOrder;
11467             return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11468         }
11469     };
11470
11471     final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11472             final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11473             final int[] userIds) {
11474         mHandler.post(new Runnable() {
11475             @Override
11476             public void run() {
11477                 try {
11478                     final IActivityManager am = ActivityManagerNative.getDefault();
11479                     if (am == null) return;
11480                     final int[] resolvedUserIds;
11481                     if (userIds == null) {
11482                         resolvedUserIds = am.getRunningUserIds();
11483                     } else {
11484                         resolvedUserIds = userIds;
11485                     }
11486                     for (int id : resolvedUserIds) {
11487                         final Intent intent = new Intent(action,
11488                                 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
11489                         if (extras != null) {
11490                             intent.putExtras(extras);
11491                         }
11492                         if (targetPkg != null) {
11493                             intent.setPackage(targetPkg);
11494                         }
11495                         // Modify the UID when posting to other users
11496                         int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11497                         if (uid > 0 && UserHandle.getUserId(uid) != id) {
11498                             uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11499                             intent.putExtra(Intent.EXTRA_UID, uid);
11500                         }
11501                         intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11502                         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11503                         if (DEBUG_BROADCASTS) {
11504                             RuntimeException here = new RuntimeException("here");
11505                             here.fillInStackTrace();
11506                             Slog.d(TAG, "Sending to user " + id + ": "
11507                                     + intent.toShortString(false, true, false, false)
11508                                     + " " + intent.getExtras(), here);
11509                         }
11510                         am.broadcastIntent(null, intent, null, finishedReceiver,
11511                                 0, null, null, null, android.app.AppOpsManager.OP_NONE,
11512                                 null, finishedReceiver != null, false, id);
11513                     }
11514                 } catch (RemoteException ex) {
11515                 }
11516             }
11517         });
11518     }
11519
11520     /**
11521      * Check if the external storage media is available. This is true if there
11522      * is a mounted external storage medium or if the external storage is
11523      * emulated.
11524      */
11525     private boolean isExternalMediaAvailable() {
11526         return mMediaMounted || Environment.isExternalStorageEmulated();
11527     }
11528
11529     @Override
11530     public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11531         // writer
11532         synchronized (mPackages) {
11533             if (!isExternalMediaAvailable()) {
11534                 // If the external storage is no longer mounted at this point,
11535                 // the caller may not have been able to delete all of this
11536                 // packages files and can not delete any more.  Bail.
11537                 return null;
11538             }
11539             final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11540             if (lastPackage != null) {
11541                 pkgs.remove(lastPackage);
11542             }
11543             if (pkgs.size() > 0) {
11544                 return pkgs.get(0);
11545             }
11546         }
11547         return null;
11548     }
11549
11550     void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11551         final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11552                 userId, andCode ? 1 : 0, packageName);
11553         if (mSystemReady) {
11554             msg.sendToTarget();
11555         } else {
11556             if (mPostSystemReadyMessages == null) {
11557                 mPostSystemReadyMessages = new ArrayList<>();
11558             }
11559             mPostSystemReadyMessages.add(msg);
11560         }
11561     }
11562
11563     void startCleaningPackages() {
11564         // reader
11565         if (!isExternalMediaAvailable()) {
11566             return;
11567         }
11568         synchronized (mPackages) {
11569             if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11570                 return;
11571             }
11572         }
11573         Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11574         intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11575         IActivityManager am = ActivityManagerNative.getDefault();
11576         if (am != null) {
11577             try {
11578                 am.startService(null, intent, null, mContext.getOpPackageName(),
11579                         UserHandle.USER_SYSTEM);
11580             } catch (RemoteException e) {
11581             }
11582         }
11583     }
11584
11585     @Override
11586     public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11587             int installFlags, String installerPackageName, int userId) {
11588         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11589
11590         final int callingUid = Binder.getCallingUid();
11591         enforceCrossUserPermission(callingUid, userId,
11592                 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11593
11594         if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11595             try {
11596                 if (observer != null) {
11597                     observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11598                 }
11599             } catch (RemoteException re) {
11600             }
11601             return;
11602         }
11603
11604         if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11605             installFlags |= PackageManager.INSTALL_FROM_ADB;
11606
11607         } else {
11608             // Caller holds INSTALL_PACKAGES permission, so we're less strict
11609             // about installerPackageName.
11610
11611             installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11612             installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11613         }
11614
11615         UserHandle user;
11616         if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11617             user = UserHandle.ALL;
11618         } else {
11619             user = new UserHandle(userId);
11620         }
11621
11622         // Only system components can circumvent runtime permissions when installing.
11623         if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11624                 && mContext.checkCallingOrSelfPermission(Manifest.permission
11625                 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11626             throw new SecurityException("You need the "
11627                     + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11628                     + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11629         }
11630
11631         final File originFile = new File(originPath);
11632         final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11633
11634         final Message msg = mHandler.obtainMessage(INIT_COPY);
11635         final VerificationInfo verificationInfo = new VerificationInfo(
11636                 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11637         final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11638                 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11639                 null /*packageAbiOverride*/, null /*grantedPermissions*/,
11640                 null /*certificates*/);
11641         params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11642         msg.obj = params;
11643
11644         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11645                 System.identityHashCode(msg.obj));
11646         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11647                 System.identityHashCode(msg.obj));
11648
11649         mHandler.sendMessage(msg);
11650     }
11651
11652     void installStage(String packageName, File stagedDir, String stagedCid,
11653             IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11654             String installerPackageName, int installerUid, UserHandle user,
11655             Certificate[][] certificates) {
11656         if (DEBUG_EPHEMERAL) {
11657             if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11658                 Slog.d(TAG, "Ephemeral install of " + packageName);
11659             }
11660         }
11661         final VerificationInfo verificationInfo = new VerificationInfo(
11662                 sessionParams.originatingUri, sessionParams.referrerUri,
11663                 sessionParams.originatingUid, installerUid);
11664
11665         final OriginInfo origin;
11666         if (stagedDir != null) {
11667             origin = OriginInfo.fromStagedFile(stagedDir);
11668         } else {
11669             origin = OriginInfo.fromStagedContainer(stagedCid);
11670         }
11671
11672         final Message msg = mHandler.obtainMessage(INIT_COPY);
11673         final InstallParams params = new InstallParams(origin, null, observer,
11674                 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11675                 verificationInfo, user, sessionParams.abiOverride,
11676                 sessionParams.grantedRuntimePermissions, certificates);
11677         params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11678         msg.obj = params;
11679
11680         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11681                 System.identityHashCode(msg.obj));
11682         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11683                 System.identityHashCode(msg.obj));
11684
11685         mHandler.sendMessage(msg);
11686     }
11687
11688     private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11689             int userId) {
11690         final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11691         sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11692     }
11693
11694     private void sendPackageAddedForUser(String packageName, boolean isSystem,
11695             int appId, int userId) {
11696         Bundle extras = new Bundle(1);
11697         extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11698
11699         sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11700                 packageName, extras, 0, null, null, new int[] {userId});
11701         try {
11702             IActivityManager am = ActivityManagerNative.getDefault();
11703             if (isSystem && am.isUserRunning(userId, 0)) {
11704                 // The just-installed/enabled app is bundled on the system, so presumed
11705                 // to be able to run automatically without needing an explicit launch.
11706                 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11707                 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11708                         .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11709                         .setPackage(packageName);
11710                 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11711                         android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11712             }
11713         } catch (RemoteException e) {
11714             // shouldn't happen
11715             Slog.w(TAG, "Unable to bootstrap installed package", e);
11716         }
11717     }
11718
11719     @Override
11720     public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11721             int userId) {
11722         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11723         PackageSetting pkgSetting;
11724         final int uid = Binder.getCallingUid();
11725         enforceCrossUserPermission(uid, userId,
11726                 true /* requireFullPermission */, true /* checkShell */,
11727                 "setApplicationHiddenSetting for user " + userId);
11728
11729         if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11730             Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11731             return false;
11732         }
11733
11734         long callingId = Binder.clearCallingIdentity();
11735         try {
11736             boolean sendAdded = false;
11737             boolean sendRemoved = false;
11738             // writer
11739             synchronized (mPackages) {
11740                 pkgSetting = mSettings.mPackages.get(packageName);
11741                 if (pkgSetting == null) {
11742                     return false;
11743                 }
11744                 // Do not allow "android" is being disabled
11745                 if ("android".equals(packageName)) {
11746                     Slog.w(TAG, "Cannot hide package: android");
11747                     return false;
11748                 }
11749                 // Only allow protected packages to hide themselves.
11750                 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11751                         && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11752                     Slog.w(TAG, "Not hiding protected package: " + packageName);
11753                     return false;
11754                 }
11755
11756                 if (pkgSetting.getHidden(userId) != hidden) {
11757                     pkgSetting.setHidden(hidden, userId);
11758                     mSettings.writePackageRestrictionsLPr(userId);
11759                     if (hidden) {
11760                         sendRemoved = true;
11761                     } else {
11762                         sendAdded = true;
11763                     }
11764                 }
11765             }
11766             if (sendAdded) {
11767                 sendPackageAddedForUser(packageName, pkgSetting, userId);
11768                 return true;
11769             }
11770             if (sendRemoved) {
11771                 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11772                         "hiding pkg");
11773                 sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11774                 return true;
11775             }
11776         } finally {
11777             Binder.restoreCallingIdentity(callingId);
11778         }
11779         return false;
11780     }
11781
11782     private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11783             int userId) {
11784         final PackageRemovedInfo info = new PackageRemovedInfo();
11785         info.removedPackage = packageName;
11786         info.removedUsers = new int[] {userId};
11787         info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11788         info.sendPackageRemovedBroadcasts(true /*killApp*/);
11789     }
11790
11791     private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11792         if (pkgList.length > 0) {
11793             Bundle extras = new Bundle(1);
11794             extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11795
11796             sendPackageBroadcast(
11797                     suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11798                             : Intent.ACTION_PACKAGES_UNSUSPENDED,
11799                     null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11800                     new int[] {userId});
11801         }
11802     }
11803
11804     /**
11805      * Returns true if application is not found or there was an error. Otherwise it returns
11806      * the hidden state of the package for the given user.
11807      */
11808     @Override
11809     public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11810         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11811         enforceCrossUserPermission(Binder.getCallingUid(), userId,
11812                 true /* requireFullPermission */, false /* checkShell */,
11813                 "getApplicationHidden for user " + userId);
11814         PackageSetting pkgSetting;
11815         long callingId = Binder.clearCallingIdentity();
11816         try {
11817             // writer
11818             synchronized (mPackages) {
11819                 pkgSetting = mSettings.mPackages.get(packageName);
11820                 if (pkgSetting == null) {
11821                     return true;
11822                 }
11823                 return pkgSetting.getHidden(userId);
11824             }
11825         } finally {
11826             Binder.restoreCallingIdentity(callingId);
11827         }
11828     }
11829
11830     /**
11831      * @hide
11832      */
11833     @Override
11834     public int installExistingPackageAsUser(String packageName, int userId) {
11835         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11836                 null);
11837         PackageSetting pkgSetting;
11838         final int uid = Binder.getCallingUid();
11839         enforceCrossUserPermission(uid, userId,
11840                 true /* requireFullPermission */, true /* checkShell */,
11841                 "installExistingPackage for user " + userId);
11842         if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11843             return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11844         }
11845
11846         long callingId = Binder.clearCallingIdentity();
11847         try {
11848             boolean installed = false;
11849
11850             // writer
11851             synchronized (mPackages) {
11852                 pkgSetting = mSettings.mPackages.get(packageName);
11853                 if (pkgSetting == null) {
11854                     return PackageManager.INSTALL_FAILED_INVALID_URI;
11855                 }
11856                 if (!pkgSetting.getInstalled(userId)) {
11857                     pkgSetting.setInstalled(true, userId);
11858                     pkgSetting.setHidden(false, userId);
11859                     mSettings.writePackageRestrictionsLPr(userId);
11860                     installed = true;
11861                 }
11862             }
11863
11864             if (installed) {
11865                 if (pkgSetting.pkg != null) {
11866                     synchronized (mInstallLock) {
11867                         // We don't need to freeze for a brand new install
11868                         prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11869                     }
11870                 }
11871                 sendPackageAddedForUser(packageName, pkgSetting, userId);
11872             }
11873         } finally {
11874             Binder.restoreCallingIdentity(callingId);
11875         }
11876
11877         return PackageManager.INSTALL_SUCCEEDED;
11878     }
11879
11880     boolean isUserRestricted(int userId, String restrictionKey) {
11881         Bundle restrictions = sUserManager.getUserRestrictions(userId);
11882         if (restrictions.getBoolean(restrictionKey, false)) {
11883             Log.w(TAG, "User is restricted: " + restrictionKey);
11884             return true;
11885         }
11886         return false;
11887     }
11888
11889     @Override
11890     public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11891             int userId) {
11892         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11893         enforceCrossUserPermission(Binder.getCallingUid(), userId,
11894                 true /* requireFullPermission */, true /* checkShell */,
11895                 "setPackagesSuspended for user " + userId);
11896
11897         if (ArrayUtils.isEmpty(packageNames)) {
11898             return packageNames;
11899         }
11900
11901         // List of package names for whom the suspended state has changed.
11902         List<String> changedPackages = new ArrayList<>(packageNames.length);
11903         // List of package names for whom the suspended state is not set as requested in this
11904         // method.
11905         List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11906         long callingId = Binder.clearCallingIdentity();
11907         try {
11908             for (int i = 0; i < packageNames.length; i++) {
11909                 String packageName = packageNames[i];
11910                 boolean changed = false;
11911                 final int appId;
11912                 synchronized (mPackages) {
11913                     final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11914                     if (pkgSetting == null) {
11915                         Slog.w(TAG, "Could not find package setting for package \"" + packageName
11916                                 + "\". Skipping suspending/un-suspending.");
11917                         unactionedPackages.add(packageName);
11918                         continue;
11919                     }
11920                     appId = pkgSetting.appId;
11921                     if (pkgSetting.getSuspended(userId) != suspended) {
11922                         if (!canSuspendPackageForUserLocked(packageName, userId)) {
11923                             unactionedPackages.add(packageName);
11924                             continue;
11925                         }
11926                         pkgSetting.setSuspended(suspended, userId);
11927                         mSettings.writePackageRestrictionsLPr(userId);
11928                         changed = true;
11929                         changedPackages.add(packageName);
11930                     }
11931                 }
11932
11933                 if (changed && suspended) {
11934                     killApplication(packageName, UserHandle.getUid(userId, appId),
11935                             "suspending package");
11936                 }
11937             }
11938         } finally {
11939             Binder.restoreCallingIdentity(callingId);
11940         }
11941
11942         if (!changedPackages.isEmpty()) {
11943             sendPackagesSuspendedForUser(changedPackages.toArray(
11944                     new String[changedPackages.size()]), userId, suspended);
11945         }
11946
11947         return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11948     }
11949
11950     @Override
11951     public boolean isPackageSuspendedForUser(String packageName, int userId) {
11952         enforceCrossUserPermission(Binder.getCallingUid(), userId,
11953                 true /* requireFullPermission */, false /* checkShell */,
11954                 "isPackageSuspendedForUser for user " + userId);
11955         synchronized (mPackages) {
11956             final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11957             if (pkgSetting == null) {
11958                 throw new IllegalArgumentException("Unknown target package: " + packageName);
11959             }
11960             return pkgSetting.getSuspended(userId);
11961         }
11962     }
11963
11964     private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11965         if (isPackageDeviceAdmin(packageName, userId)) {
11966             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11967                     + "\": has an active device admin");
11968             return false;
11969         }
11970
11971         String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11972         if (packageName.equals(activeLauncherPackageName)) {
11973             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11974                     + "\": contains the active launcher");
11975             return false;
11976         }
11977
11978         if (packageName.equals(mRequiredInstallerPackage)) {
11979             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11980                     + "\": required for package installation");
11981             return false;
11982         }
11983
11984         if (packageName.equals(mRequiredUninstallerPackage)) {
11985             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11986                     + "\": required for package uninstallation");
11987             return false;
11988         }
11989
11990         if (packageName.equals(mRequiredVerifierPackage)) {
11991             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11992                     + "\": required for package verification");
11993             return false;
11994         }
11995
11996         if (packageName.equals(getDefaultDialerPackageName(userId))) {
11997             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11998                     + "\": is the default dialer");
11999             return false;
12000         }
12001
12002         if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
12003             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
12004                     + "\": protected package");
12005             return false;
12006         }
12007
12008         return true;
12009     }
12010
12011     private String getActiveLauncherPackageName(int userId) {
12012         Intent intent = new Intent(Intent.ACTION_MAIN);
12013         intent.addCategory(Intent.CATEGORY_HOME);
12014         ResolveInfo resolveInfo = resolveIntent(
12015                 intent,
12016                 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
12017                 PackageManager.MATCH_DEFAULT_ONLY,
12018                 userId);
12019
12020         return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
12021     }
12022
12023     private String getDefaultDialerPackageName(int userId) {
12024         synchronized (mPackages) {
12025             return mSettings.getDefaultDialerPackageNameLPw(userId);
12026         }
12027     }
12028
12029     @Override
12030     public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
12031         mContext.enforceCallingOrSelfPermission(
12032                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12033                 "Only package verification agents can verify applications");
12034
12035         final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12036         final PackageVerificationResponse response = new PackageVerificationResponse(
12037                 verificationCode, Binder.getCallingUid());
12038         msg.arg1 = id;
12039         msg.obj = response;
12040         mHandler.sendMessage(msg);
12041     }
12042
12043     @Override
12044     public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
12045             long millisecondsToDelay) {
12046         mContext.enforceCallingOrSelfPermission(
12047                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12048                 "Only package verification agents can extend verification timeouts");
12049
12050         final PackageVerificationState state = mPendingVerification.get(id);
12051         final PackageVerificationResponse response = new PackageVerificationResponse(
12052                 verificationCodeAtTimeout, Binder.getCallingUid());
12053
12054         if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
12055             millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
12056         }
12057         if (millisecondsToDelay < 0) {
12058             millisecondsToDelay = 0;
12059         }
12060         if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
12061                 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
12062             verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
12063         }
12064
12065         if ((state != null) && !state.timeoutExtended()) {
12066             state.extendTimeout();
12067
12068             final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
12069             msg.arg1 = id;
12070             msg.obj = response;
12071             mHandler.sendMessageDelayed(msg, millisecondsToDelay);
12072         }
12073     }
12074
12075     private void broadcastPackageVerified(int verificationId, Uri packageUri,
12076             int verificationCode, UserHandle user) {
12077         final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
12078         intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
12079         intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12080         intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12081         intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
12082
12083         mContext.sendBroadcastAsUser(intent, user,
12084                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
12085     }
12086
12087     private ComponentName matchComponentForVerifier(String packageName,
12088             List<ResolveInfo> receivers) {
12089         ActivityInfo targetReceiver = null;
12090
12091         final int NR = receivers.size();
12092         for (int i = 0; i < NR; i++) {
12093             final ResolveInfo info = receivers.get(i);
12094             if (info.activityInfo == null) {
12095                 continue;
12096             }
12097
12098             if (packageName.equals(info.activityInfo.packageName)) {
12099                 targetReceiver = info.activityInfo;
12100                 break;
12101             }
12102         }
12103
12104         if (targetReceiver == null) {
12105             return null;
12106         }
12107
12108         return new ComponentName(targetReceiver.packageName, targetReceiver.name);
12109     }
12110
12111     private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
12112             List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
12113         if (pkgInfo.verifiers.length == 0) {
12114             return null;
12115         }
12116
12117         final int N = pkgInfo.verifiers.length;
12118         final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
12119         for (int i = 0; i < N; i++) {
12120             final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
12121
12122             final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
12123                     receivers);
12124             if (comp == null) {
12125                 continue;
12126             }
12127
12128             final int verifierUid = getUidForVerifier(verifierInfo);
12129             if (verifierUid == -1) {
12130                 continue;
12131             }
12132
12133             if (DEBUG_VERIFY) {
12134                 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12135                         + " with the correct signature");
12136             }
12137             sufficientVerifiers.add(comp);
12138             verificationState.addSufficientVerifier(verifierUid);
12139         }
12140
12141         return sufficientVerifiers;
12142     }
12143
12144     private int getUidForVerifier(VerifierInfo verifierInfo) {
12145         synchronized (mPackages) {
12146             final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12147             if (pkg == null) {
12148                 return -1;
12149             } else if (pkg.mSignatures.length != 1) {
12150                 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12151                         + " has more than one signature; ignoring");
12152                 return -1;
12153             }
12154
12155             /*
12156              * If the public key of the package's signature does not match
12157              * our expected public key, then this is a different package and
12158              * we should skip.
12159              */
12160
12161             final byte[] expectedPublicKey;
12162             try {
12163                 final Signature verifierSig = pkg.mSignatures[0];
12164                 final PublicKey publicKey = verifierSig.getPublicKey();
12165                 expectedPublicKey = publicKey.getEncoded();
12166             } catch (CertificateException e) {
12167                 return -1;
12168             }
12169
12170             final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12171
12172             if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12173                 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12174                         + " does not have the expected public key; ignoring");
12175                 return -1;
12176             }
12177
12178             return pkg.applicationInfo.uid;
12179         }
12180     }
12181
12182     @Override
12183     public void finishPackageInstall(int token, boolean didLaunch) {
12184         enforceSystemOrRoot("Only the system is allowed to finish installs");
12185
12186         if (DEBUG_INSTALL) {
12187             Slog.v(TAG, "BM finishing package install for " + token);
12188         }
12189         Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12190
12191         final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12192         mHandler.sendMessage(msg);
12193     }
12194
12195     /**
12196      * Get the verification agent timeout.
12197      *
12198      * @return verification timeout in milliseconds
12199      */
12200     private long getVerificationTimeout() {
12201         return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12202                 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12203                 DEFAULT_VERIFICATION_TIMEOUT);
12204     }
12205
12206     /**
12207      * Get the default verification agent response code.
12208      *
12209      * @return default verification response code
12210      */
12211     private int getDefaultVerificationResponse() {
12212         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12213                 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12214                 DEFAULT_VERIFICATION_RESPONSE);
12215     }
12216
12217     /**
12218      * Check whether or not package verification has been enabled.
12219      *
12220      * @return true if verification should be performed
12221      */
12222     private boolean isVerificationEnabled(int userId, int installFlags) {
12223         if (!DEFAULT_VERIFY_ENABLE) {
12224             return false;
12225         }
12226         // Ephemeral apps don't get the full verification treatment
12227         if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12228             if (DEBUG_EPHEMERAL) {
12229                 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12230             }
12231             return false;
12232         }
12233
12234         boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12235
12236         // Check if installing from ADB
12237         if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12238             // Do not run verification in a test harness environment
12239             if (ActivityManager.isRunningInTestHarness()) {
12240                 return false;
12241             }
12242             if (ensureVerifyAppsEnabled) {
12243                 return true;
12244             }
12245             // Check if the developer does not want package verification for ADB installs
12246             if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12247                     android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12248                 return false;
12249             }
12250         }
12251
12252         if (ensureVerifyAppsEnabled) {
12253             return true;
12254         }
12255
12256         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12257                 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12258     }
12259
12260     @Override
12261     public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12262             throws RemoteException {
12263         mContext.enforceCallingOrSelfPermission(
12264                 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12265                 "Only intentfilter verification agents can verify applications");
12266
12267         final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12268         final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12269                 Binder.getCallingUid(), verificationCode, failedDomains);
12270         msg.arg1 = id;
12271         msg.obj = response;
12272         mHandler.sendMessage(msg);
12273     }
12274
12275     @Override
12276     public int getIntentVerificationStatus(String packageName, int userId) {
12277         synchronized (mPackages) {
12278             return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12279         }
12280     }
12281
12282     @Override
12283     public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12284         mContext.enforceCallingOrSelfPermission(
12285                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12286
12287         boolean result = false;
12288         synchronized (mPackages) {
12289             result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12290         }
12291         if (result) {
12292             scheduleWritePackageRestrictionsLocked(userId);
12293         }
12294         return result;
12295     }
12296
12297     @Override
12298     public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12299             String packageName) {
12300         synchronized (mPackages) {
12301             return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12302         }
12303     }
12304
12305     @Override
12306     public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12307         if (TextUtils.isEmpty(packageName)) {
12308             return ParceledListSlice.emptyList();
12309         }
12310         synchronized (mPackages) {
12311             PackageParser.Package pkg = mPackages.get(packageName);
12312             if (pkg == null || pkg.activities == null) {
12313                 return ParceledListSlice.emptyList();
12314             }
12315             final int count = pkg.activities.size();
12316             ArrayList<IntentFilter> result = new ArrayList<>();
12317             for (int n=0; n<count; n++) {
12318                 PackageParser.Activity activity = pkg.activities.get(n);
12319                 if (activity.intents != null && activity.intents.size() > 0) {
12320                     result.addAll(activity.intents);
12321                 }
12322             }
12323             return new ParceledListSlice<>(result);
12324         }
12325     }
12326
12327     @Override
12328     public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12329         mContext.enforceCallingOrSelfPermission(
12330                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12331
12332         synchronized (mPackages) {
12333             boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12334             if (packageName != null) {
12335                 result |= updateIntentVerificationStatus(packageName,
12336                         PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12337                         userId);
12338                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12339                         packageName, userId);
12340             }
12341             return result;
12342         }
12343     }
12344
12345     @Override
12346     public String getDefaultBrowserPackageName(int userId) {
12347         synchronized (mPackages) {
12348             return mSettings.getDefaultBrowserPackageNameLPw(userId);
12349         }
12350     }
12351
12352     /**
12353      * Get the "allow unknown sources" setting.
12354      *
12355      * @return the current "allow unknown sources" setting
12356      */
12357     private int getUnknownSourcesSettings() {
12358         return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12359                 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12360                 -1);
12361     }
12362
12363     @Override
12364     public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12365         final int uid = Binder.getCallingUid();
12366         // writer
12367         synchronized (mPackages) {
12368             PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12369             if (targetPackageSetting == null) {
12370                 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12371             }
12372
12373             PackageSetting installerPackageSetting;
12374             if (installerPackageName != null) {
12375                 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12376                 if (installerPackageSetting == null) {
12377                     throw new IllegalArgumentException("Unknown installer package: "
12378                             + installerPackageName);
12379                 }
12380             } else {
12381                 installerPackageSetting = null;
12382             }
12383
12384             Signature[] callerSignature;
12385             Object obj = mSettings.getUserIdLPr(uid);
12386             if (obj != null) {
12387                 if (obj instanceof SharedUserSetting) {
12388                     callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12389                 } else if (obj instanceof PackageSetting) {
12390                     callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12391                 } else {
12392                     throw new SecurityException("Bad object " + obj + " for uid " + uid);
12393                 }
12394             } else {
12395                 throw new SecurityException("Unknown calling UID: " + uid);
12396             }
12397
12398             // Verify: can't set installerPackageName to a package that is
12399             // not signed with the same cert as the caller.
12400             if (installerPackageSetting != null) {
12401                 if (compareSignatures(callerSignature,
12402                         installerPackageSetting.signatures.mSignatures)
12403                         != PackageManager.SIGNATURE_MATCH) {
12404                     throw new SecurityException(
12405                             "Caller does not have same cert as new installer package "
12406                             + installerPackageName);
12407                 }
12408             }
12409
12410             // Verify: if target already has an installer package, it must
12411             // be signed with the same cert as the caller.
12412             if (targetPackageSetting.installerPackageName != null) {
12413                 PackageSetting setting = mSettings.mPackages.get(
12414                         targetPackageSetting.installerPackageName);
12415                 // If the currently set package isn't valid, then it's always
12416                 // okay to change it.
12417                 if (setting != null) {
12418                     if (compareSignatures(callerSignature,
12419                             setting.signatures.mSignatures)
12420                             != PackageManager.SIGNATURE_MATCH) {
12421                         throw new SecurityException(
12422                                 "Caller does not have same cert as old installer package "
12423                                 + targetPackageSetting.installerPackageName);
12424                     }
12425                 }
12426             }
12427
12428             // Okay!
12429             targetPackageSetting.installerPackageName = installerPackageName;
12430             if (installerPackageName != null) {
12431                 mSettings.mInstallerPackages.add(installerPackageName);
12432             }
12433             scheduleWriteSettingsLocked();
12434         }
12435     }
12436
12437     private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12438         // Queue up an async operation since the package installation may take a little while.
12439         mHandler.post(new Runnable() {
12440             public void run() {
12441                 mHandler.removeCallbacks(this);
12442                  // Result object to be returned
12443                 PackageInstalledInfo res = new PackageInstalledInfo();
12444                 res.setReturnCode(currentStatus);
12445                 res.uid = -1;
12446                 res.pkg = null;
12447                 res.removedInfo = null;
12448                 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12449                     args.doPreInstall(res.returnCode);
12450                     synchronized (mInstallLock) {
12451                         installPackageTracedLI(args, res);
12452                     }
12453                     args.doPostInstall(res.returnCode, res.uid);
12454                 }
12455
12456                 // A restore should be performed at this point if (a) the install
12457                 // succeeded, (b) the operation is not an update, and (c) the new
12458                 // package has not opted out of backup participation.
12459                 final boolean update = res.removedInfo != null
12460                         && res.removedInfo.removedPackage != null;
12461                 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12462                 boolean doRestore = !update
12463                         && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12464
12465                 // Set up the post-install work request bookkeeping.  This will be used
12466                 // and cleaned up by the post-install event handling regardless of whether
12467                 // there's a restore pass performed.  Token values are >= 1.
12468                 int token;
12469                 if (mNextInstallToken < 0) mNextInstallToken = 1;
12470                 token = mNextInstallToken++;
12471
12472                 PostInstallData data = new PostInstallData(args, res);
12473                 mRunningInstalls.put(token, data);
12474                 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12475
12476                 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12477                     // Pass responsibility to the Backup Manager.  It will perform a
12478                     // restore if appropriate, then pass responsibility back to the
12479                     // Package Manager to run the post-install observer callbacks
12480                     // and broadcasts.
12481                     IBackupManager bm = IBackupManager.Stub.asInterface(
12482                             ServiceManager.getService(Context.BACKUP_SERVICE));
12483                     if (bm != null) {
12484                         if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12485                                 + " to BM for possible restore");
12486                         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12487                         try {
12488                             // TODO: http://b/22388012
12489                             if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12490                                 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12491                             } else {
12492                                 doRestore = false;
12493                             }
12494                         } catch (RemoteException e) {
12495                             // can't happen; the backup manager is local
12496                         } catch (Exception e) {
12497                             Slog.e(TAG, "Exception trying to enqueue restore", e);
12498                             doRestore = false;
12499                         }
12500                     } else {
12501                         Slog.e(TAG, "Backup Manager not found!");
12502                         doRestore = false;
12503                     }
12504                 }
12505
12506                 if (!doRestore) {
12507                     // No restore possible, or the Backup Manager was mysteriously not
12508                     // available -- just fire the post-install work request directly.
12509                     if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12510
12511                     Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12512
12513                     Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12514                     mHandler.sendMessage(msg);
12515                 }
12516             }
12517         });
12518     }
12519
12520     /**
12521      * Callback from PackageSettings whenever an app is first transitioned out of the
12522      * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12523      * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12524      * here whether the app is the target of an ongoing install, and only send the
12525      * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12526      * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12527      * handling.
12528      */
12529     void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12530         // Serialize this with the rest of the install-process message chain.  In the
12531         // restore-at-install case, this Runnable will necessarily run before the
12532         // POST_INSTALL message is processed, so the contents of mRunningInstalls
12533         // are coherent.  In the non-restore case, the app has already completed install
12534         // and been launched through some other means, so it is not in a problematic
12535         // state for observers to see the FIRST_LAUNCH signal.
12536         mHandler.post(new Runnable() {
12537             @Override
12538             public void run() {
12539                 for (int i = 0; i < mRunningInstalls.size(); i++) {
12540                     final PostInstallData data = mRunningInstalls.valueAt(i);
12541                     if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12542                         continue;
12543                     }
12544                     if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12545                         // right package; but is it for the right user?
12546                         for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12547                             if (userId == data.res.newUsers[uIndex]) {
12548                                 if (DEBUG_BACKUP) {
12549                                     Slog.i(TAG, "Package " + pkgName
12550                                             + " being restored so deferring FIRST_LAUNCH");
12551                                 }
12552                                 return;
12553                             }
12554                         }
12555                     }
12556                 }
12557                 // didn't find it, so not being restored
12558                 if (DEBUG_BACKUP) {
12559                     Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12560                 }
12561                 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12562             }
12563         });
12564     }
12565
12566     private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12567         sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12568                 installerPkg, null, userIds);
12569     }
12570
12571     private abstract class HandlerParams {
12572         private static final int MAX_RETRIES = 4;
12573
12574         /**
12575          * Number of times startCopy() has been attempted and had a non-fatal
12576          * error.
12577          */
12578         private int mRetries = 0;
12579
12580         /** User handle for the user requesting the information or installation. */
12581         private final UserHandle mUser;
12582         String traceMethod;
12583         int traceCookie;
12584
12585         HandlerParams(UserHandle user) {
12586             mUser = user;
12587         }
12588
12589         UserHandle getUser() {
12590             return mUser;
12591         }
12592
12593         HandlerParams setTraceMethod(String traceMethod) {
12594             this.traceMethod = traceMethod;
12595             return this;
12596         }
12597
12598         HandlerParams setTraceCookie(int traceCookie) {
12599             this.traceCookie = traceCookie;
12600             return this;
12601         }
12602
12603         final boolean startCopy() {
12604             boolean res;
12605             try {
12606                 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12607
12608                 if (++mRetries > MAX_RETRIES) {
12609                     Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12610                     mHandler.sendEmptyMessage(MCS_GIVE_UP);
12611                     handleServiceError();
12612                     return false;
12613                 } else {
12614                     handleStartCopy();
12615                     res = true;
12616                 }
12617             } catch (RemoteException e) {
12618                 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12619                 mHandler.sendEmptyMessage(MCS_RECONNECT);
12620                 res = false;
12621             }
12622             handleReturnCode();
12623             return res;
12624         }
12625
12626         final void serviceError() {
12627             if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12628             handleServiceError();
12629             handleReturnCode();
12630         }
12631
12632         abstract void handleStartCopy() throws RemoteException;
12633         abstract void handleServiceError();
12634         abstract void handleReturnCode();
12635     }
12636
12637     class MeasureParams extends HandlerParams {
12638         private final PackageStats mStats;
12639         private boolean mSuccess;
12640
12641         private final IPackageStatsObserver mObserver;
12642
12643         public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12644             super(new UserHandle(stats.userHandle));
12645             mObserver = observer;
12646             mStats = stats;
12647         }
12648
12649         @Override
12650         public String toString() {
12651             return "MeasureParams{"
12652                 + Integer.toHexString(System.identityHashCode(this))
12653                 + " " + mStats.packageName + "}";
12654         }
12655
12656         @Override
12657         void handleStartCopy() throws RemoteException {
12658             synchronized (mInstallLock) {
12659                 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12660             }
12661
12662             if (mSuccess) {
12663                 boolean mounted = false;
12664                 try {
12665                     final String status = Environment.getExternalStorageState();
12666                     mounted = (Environment.MEDIA_MOUNTED.equals(status)
12667                             || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12668                 } catch (Exception e) {
12669                 }
12670
12671                 if (mounted) {
12672                     final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12673
12674                     mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12675                             userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12676
12677                     mStats.externalDataSize = calculateDirectorySize(mContainerService,
12678                             userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12679
12680                     // Always subtract cache size, since it's a subdirectory
12681                     mStats.externalDataSize -= mStats.externalCacheSize;
12682
12683                     mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12684                             userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12685
12686                     mStats.externalObbSize = calculateDirectorySize(mContainerService,
12687                             userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12688                 }
12689             }
12690         }
12691
12692         @Override
12693         void handleReturnCode() {
12694             if (mObserver != null) {
12695                 try {
12696                     mObserver.onGetStatsCompleted(mStats, mSuccess);
12697                 } catch (RemoteException e) {
12698                     Slog.i(TAG, "Observer no longer exists.");
12699                 }
12700             }
12701         }
12702
12703         @Override
12704         void handleServiceError() {
12705             Slog.e(TAG, "Could not measure application " + mStats.packageName
12706                             + " external storage");
12707         }
12708     }
12709
12710     private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12711             throws RemoteException {
12712         long result = 0;
12713         for (File path : paths) {
12714             result += mcs.calculateDirectorySize(path.getAbsolutePath());
12715         }
12716         return result;
12717     }
12718
12719     private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12720         for (File path : paths) {
12721             try {
12722                 mcs.clearDirectory(path.getAbsolutePath());
12723             } catch (RemoteException e) {
12724             }
12725         }
12726     }
12727
12728     static class OriginInfo {
12729         /**
12730          * Location where install is coming from, before it has been
12731          * copied/renamed into place. This could be a single monolithic APK
12732          * file, or a cluster directory. This location may be untrusted.
12733          */
12734         final File file;
12735         final String cid;
12736
12737         /**
12738          * Flag indicating that {@link #file} or {@link #cid} has already been
12739          * staged, meaning downstream users don't need to defensively copy the
12740          * contents.
12741          */
12742         final boolean staged;
12743
12744         /**
12745          * Flag indicating that {@link #file} or {@link #cid} is an already
12746          * installed app that is being moved.
12747          */
12748         final boolean existing;
12749
12750         final String resolvedPath;
12751         final File resolvedFile;
12752
12753         static OriginInfo fromNothing() {
12754             return new OriginInfo(null, null, false, false);
12755         }
12756
12757         static OriginInfo fromUntrustedFile(File file) {
12758             return new OriginInfo(file, null, false, false);
12759         }
12760
12761         static OriginInfo fromExistingFile(File file) {
12762             return new OriginInfo(file, null, false, true);
12763         }
12764
12765         static OriginInfo fromStagedFile(File file) {
12766             return new OriginInfo(file, null, true, false);
12767         }
12768
12769         static OriginInfo fromStagedContainer(String cid) {
12770             return new OriginInfo(null, cid, true, false);
12771         }
12772
12773         private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12774             this.file = file;
12775             this.cid = cid;
12776             this.staged = staged;
12777             this.existing = existing;
12778
12779             if (cid != null) {
12780                 resolvedPath = PackageHelper.getSdDir(cid);
12781                 resolvedFile = new File(resolvedPath);
12782             } else if (file != null) {
12783                 resolvedPath = file.getAbsolutePath();
12784                 resolvedFile = file;
12785             } else {
12786                 resolvedPath = null;
12787                 resolvedFile = null;
12788             }
12789         }
12790     }
12791
12792     static class MoveInfo {
12793         final int moveId;
12794         final String fromUuid;
12795         final String toUuid;
12796         final String packageName;
12797         final String dataAppName;
12798         final int appId;
12799         final String seinfo;
12800         final int targetSdkVersion;
12801
12802         public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12803                 String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12804             this.moveId = moveId;
12805             this.fromUuid = fromUuid;
12806             this.toUuid = toUuid;
12807             this.packageName = packageName;
12808             this.dataAppName = dataAppName;
12809             this.appId = appId;
12810             this.seinfo = seinfo;
12811             this.targetSdkVersion = targetSdkVersion;
12812         }
12813     }
12814
12815     static class VerificationInfo {
12816         /** A constant used to indicate that a uid value is not present. */
12817         public static final int NO_UID = -1;
12818
12819         /** URI referencing where the package was downloaded from. */
12820         final Uri originatingUri;
12821
12822         /** HTTP referrer URI associated with the originatingURI. */
12823         final Uri referrer;
12824
12825         /** UID of the application that the install request originated from. */
12826         final int originatingUid;
12827
12828         /** UID of application requesting the install */
12829         final int installerUid;
12830
12831         VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12832             this.originatingUri = originatingUri;
12833             this.referrer = referrer;
12834             this.originatingUid = originatingUid;
12835             this.installerUid = installerUid;
12836         }
12837     }
12838
12839     class InstallParams extends HandlerParams {
12840         final OriginInfo origin;
12841         final MoveInfo move;
12842         final IPackageInstallObserver2 observer;
12843         int installFlags;
12844         final String installerPackageName;
12845         final String volumeUuid;
12846         private InstallArgs mArgs;
12847         private int mRet;
12848         final String packageAbiOverride;
12849         final String[] grantedRuntimePermissions;
12850         final VerificationInfo verificationInfo;
12851         final Certificate[][] certificates;
12852
12853         InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12854                 int installFlags, String installerPackageName, String volumeUuid,
12855                 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12856                 String[] grantedPermissions, Certificate[][] certificates) {
12857             super(user);
12858             this.origin = origin;
12859             this.move = move;
12860             this.observer = observer;
12861             this.installFlags = installFlags;
12862             this.installerPackageName = installerPackageName;
12863             this.volumeUuid = volumeUuid;
12864             this.verificationInfo = verificationInfo;
12865             this.packageAbiOverride = packageAbiOverride;
12866             this.grantedRuntimePermissions = grantedPermissions;
12867             this.certificates = certificates;
12868         }
12869
12870         @Override
12871         public String toString() {
12872             return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12873                     + " file=" + origin.file + " cid=" + origin.cid + "}";
12874         }
12875
12876         private int installLocationPolicy(PackageInfoLite pkgLite) {
12877             String packageName = pkgLite.packageName;
12878             int installLocation = pkgLite.installLocation;
12879             boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12880             // reader
12881             synchronized (mPackages) {
12882                 // Currently installed package which the new package is attempting to replace or
12883                 // null if no such package is installed.
12884                 PackageParser.Package installedPkg = mPackages.get(packageName);
12885                 // Package which currently owns the data which the new package will own if installed.
12886                 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12887                 // will be null whereas dataOwnerPkg will contain information about the package
12888                 // which was uninstalled while keeping its data.
12889                 PackageParser.Package dataOwnerPkg = installedPkg;
12890                 if (dataOwnerPkg  == null) {
12891                     PackageSetting ps = mSettings.mPackages.get(packageName);
12892                     if (ps != null) {
12893                         dataOwnerPkg = ps.pkg;
12894                     }
12895                 }
12896
12897                 if (dataOwnerPkg != null) {
12898                     // If installed, the package will get access to data left on the device by its
12899                     // predecessor. As a security measure, this is permited only if this is not a
12900                     // version downgrade or if the predecessor package is marked as debuggable and
12901                     // a downgrade is explicitly requested.
12902                     //
12903                     // On debuggable platform builds, downgrades are permitted even for
12904                     // non-debuggable packages to make testing easier. Debuggable platform builds do
12905                     // not offer security guarantees and thus it's OK to disable some security
12906                     // mechanisms to make debugging/testing easier on those builds. However, even on
12907                     // debuggable builds downgrades of packages are permitted only if requested via
12908                     // installFlags. This is because we aim to keep the behavior of debuggable
12909                     // platform builds as close as possible to the behavior of non-debuggable
12910                     // platform builds.
12911                     final boolean downgradeRequested =
12912                             (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12913                     final boolean packageDebuggable =
12914                                 (dataOwnerPkg.applicationInfo.flags
12915                                         & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12916                     final boolean downgradePermitted =
12917                             (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12918                     if (!downgradePermitted) {
12919                         try {
12920                             checkDowngrade(dataOwnerPkg, pkgLite);
12921                         } catch (PackageManagerException e) {
12922                             Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12923                             return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12924                         }
12925                     }
12926                 }
12927
12928                 if (installedPkg != null) {
12929                     if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12930                         // Check for updated system application.
12931                         if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12932                             if (onSd) {
12933                                 Slog.w(TAG, "Cannot install update to system app on sdcard");
12934                                 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12935                             }
12936                             return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12937                         } else {
12938                             if (onSd) {
12939                                 // Install flag overrides everything.
12940                                 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12941                             }
12942                             // If current upgrade specifies particular preference
12943                             if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12944                                 // Application explicitly specified internal.
12945                                 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12946                             } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12947                                 // App explictly prefers external. Let policy decide
12948                             } else {
12949                                 // Prefer previous location
12950                                 if (isExternal(installedPkg)) {
12951                                     return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12952                                 }
12953                                 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12954                             }
12955                         }
12956                     } else {
12957                         // Invalid install. Return error code
12958                         return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12959                     }
12960                 }
12961             }
12962             // All the special cases have been taken care of.
12963             // Return result based on recommended install location.
12964             if (onSd) {
12965                 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12966             }
12967             return pkgLite.recommendedInstallLocation;
12968         }
12969
12970         /*
12971          * Invoke remote method to get package information and install
12972          * location values. Override install location based on default
12973          * policy if needed and then create install arguments based
12974          * on the install location.
12975          */
12976         public void handleStartCopy() throws RemoteException {
12977             int ret = PackageManager.INSTALL_SUCCEEDED;
12978
12979             // If we're already staged, we've firmly committed to an install location
12980             if (origin.staged) {
12981                 if (origin.file != null) {
12982                     installFlags |= PackageManager.INSTALL_INTERNAL;
12983                     installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12984                 } else if (origin.cid != null) {
12985                     installFlags |= PackageManager.INSTALL_EXTERNAL;
12986                     installFlags &= ~PackageManager.INSTALL_INTERNAL;
12987                 } else {
12988                     throw new IllegalStateException("Invalid stage location");
12989                 }
12990             }
12991
12992             final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12993             final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12994             final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12995             PackageInfoLite pkgLite = null;
12996
12997             if (onInt && onSd) {
12998                 // Check if both bits are set.
12999                 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
13000                 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13001             } else if (onSd && ephemeral) {
13002                 Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
13003                 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13004             } else {
13005                 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
13006                         packageAbiOverride);
13007
13008                 if (DEBUG_EPHEMERAL && ephemeral) {
13009                     Slog.v(TAG, "pkgLite for install: " + pkgLite);
13010                 }
13011
13012                 /*
13013                  * If we have too little free space, try to free cache
13014                  * before giving up.
13015                  */
13016                 if (!origin.staged && pkgLite.recommendedInstallLocation
13017                         == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13018                     // TODO: focus freeing disk space on the target device
13019                     final StorageManager storage = StorageManager.from(mContext);
13020                     final long lowThreshold = storage.getStorageLowBytes(
13021                             Environment.getDataDirectory());
13022
13023                     final long sizeBytes = mContainerService.calculateInstalledSize(
13024                             origin.resolvedPath, isForwardLocked(), packageAbiOverride);
13025
13026                     try {
13027                         mInstaller.freeCache(null, sizeBytes + lowThreshold);
13028                         pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
13029                                 installFlags, packageAbiOverride);
13030                     } catch (InstallerException e) {
13031                         Slog.w(TAG, "Failed to free cache", e);
13032                     }
13033
13034                     /*
13035                      * The cache free must have deleted the file we
13036                      * downloaded to install.
13037                      *
13038                      * TODO: fix the "freeCache" call to not delete
13039                      *       the file we care about.
13040                      */
13041                     if (pkgLite.recommendedInstallLocation
13042                             == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13043                         pkgLite.recommendedInstallLocation
13044                             = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
13045                     }
13046                 }
13047             }
13048
13049             if (ret == PackageManager.INSTALL_SUCCEEDED) {
13050                 int loc = pkgLite.recommendedInstallLocation;
13051                 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
13052                     ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
13053                 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
13054                     ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
13055                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
13056                     ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13057                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
13058                     ret = PackageManager.INSTALL_FAILED_INVALID_APK;
13059                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
13060                     ret = PackageManager.INSTALL_FAILED_INVALID_URI;
13061                 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
13062                     ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
13063                 } else {
13064                     // Override with defaults if needed.
13065                     loc = installLocationPolicy(pkgLite);
13066                     if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
13067                         ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
13068                     } else if (!onSd && !onInt) {
13069                         // Override install location with flags
13070                         if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
13071                             // Set the flag to install on external media.
13072                             installFlags |= PackageManager.INSTALL_EXTERNAL;
13073                             installFlags &= ~PackageManager.INSTALL_INTERNAL;
13074                         } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
13075                             if (DEBUG_EPHEMERAL) {
13076                                 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
13077                             }
13078                             installFlags |= PackageManager.INSTALL_EPHEMERAL;
13079                             installFlags &= ~(PackageManager.INSTALL_EXTERNAL
13080                                     |PackageManager.INSTALL_INTERNAL);
13081                         } else {
13082                             // Make sure the flag for installing on external
13083                             // media is unset
13084                             installFlags |= PackageManager.INSTALL_INTERNAL;
13085                             installFlags &= ~PackageManager.INSTALL_EXTERNAL;
13086                         }
13087                     }
13088                 }
13089             }
13090
13091             final InstallArgs args = createInstallArgs(this);
13092             mArgs = args;
13093
13094             if (ret == PackageManager.INSTALL_SUCCEEDED) {
13095                 // TODO: http://b/22976637
13096                 // Apps installed for "all" users use the device owner to verify the app
13097                 UserHandle verifierUser = getUser();
13098                 if (verifierUser == UserHandle.ALL) {
13099                     verifierUser = UserHandle.SYSTEM;
13100                 }
13101
13102                 /*
13103                  * Determine if we have any installed package verifiers. If we
13104                  * do, then we'll defer to them to verify the packages.
13105                  */
13106                 final int requiredUid = mRequiredVerifierPackage == null ? -1
13107                         : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
13108                                 verifierUser.getIdentifier());
13109                 if (!origin.existing && requiredUid != -1
13110                         && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
13111                     final Intent verification = new Intent(
13112                             Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
13113                     verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
13114                     verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
13115                             PACKAGE_MIME_TYPE);
13116                     verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13117
13118                     // Query all live verifiers based on current user state
13119                     final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
13120                             PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
13121
13122                     if (DEBUG_VERIFY) {
13123                         Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
13124                                 + verification.toString() + " with " + pkgLite.verifiers.length
13125                                 + " optional verifiers");
13126                     }
13127
13128                     final int verificationId = mPendingVerificationToken++;
13129
13130                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13131
13132                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13133                             installerPackageName);
13134
13135                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13136                             installFlags);
13137
13138                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13139                             pkgLite.packageName);
13140
13141                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13142                             pkgLite.versionCode);
13143
13144                     if (verificationInfo != null) {
13145                         if (verificationInfo.originatingUri != null) {
13146                             verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13147                                     verificationInfo.originatingUri);
13148                         }
13149                         if (verificationInfo.referrer != null) {
13150                             verification.putExtra(Intent.EXTRA_REFERRER,
13151                                     verificationInfo.referrer);
13152                         }
13153                         if (verificationInfo.originatingUid >= 0) {
13154                             verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13155                                     verificationInfo.originatingUid);
13156                         }
13157                         if (verificationInfo.installerUid >= 0) {
13158                             verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13159                                     verificationInfo.installerUid);
13160                         }
13161                     }
13162
13163                     final PackageVerificationState verificationState = new PackageVerificationState(
13164                             requiredUid, args);
13165
13166                     mPendingVerification.append(verificationId, verificationState);
13167
13168                     final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13169                             receivers, verificationState);
13170
13171                     /*
13172                      * If any sufficient verifiers were listed in the package
13173                      * manifest, attempt to ask them.
13174                      */
13175                     if (sufficientVerifiers != null) {
13176                         final int N = sufficientVerifiers.size();
13177                         if (N == 0) {
13178                             Slog.i(TAG, "Additional verifiers required, but none installed.");
13179                             ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13180                         } else {
13181                             for (int i = 0; i < N; i++) {
13182                                 final ComponentName verifierComponent = sufficientVerifiers.get(i);
13183
13184                                 final Intent sufficientIntent = new Intent(verification);
13185                                 sufficientIntent.setComponent(verifierComponent);
13186                                 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13187                             }
13188                         }
13189                     }
13190
13191                     final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13192                             mRequiredVerifierPackage, receivers);
13193                     if (ret == PackageManager.INSTALL_SUCCEEDED
13194                             && mRequiredVerifierPackage != null) {
13195                         Trace.asyncTraceBegin(
13196                                 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13197                         /*
13198                          * Send the intent to the required verification agent,
13199                          * but only start the verification timeout after the
13200                          * target BroadcastReceivers have run.
13201                          */
13202                         verification.setComponent(requiredVerifierComponent);
13203                         mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13204                                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13205                                 new BroadcastReceiver() {
13206                                     @Override
13207                                     public void onReceive(Context context, Intent intent) {
13208                                         final Message msg = mHandler
13209                                                 .obtainMessage(CHECK_PENDING_VERIFICATION);
13210                                         msg.arg1 = verificationId;
13211                                         mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13212                                     }
13213                                 }, null, 0, null, null);
13214
13215                         /*
13216                          * We don't want the copy to proceed until verification
13217                          * succeeds, so null out this field.
13218                          */
13219                         mArgs = null;
13220                     }
13221                 } else {
13222                     /*
13223                      * No package verification is enabled, so immediately start
13224                      * the remote call to initiate copy using temporary file.
13225                      */
13226                     ret = args.copyApk(mContainerService, true);
13227                 }
13228             }
13229
13230             mRet = ret;
13231         }
13232
13233         @Override
13234         void handleReturnCode() {
13235             // If mArgs is null, then MCS couldn't be reached. When it
13236             // reconnects, it will try again to install. At that point, this
13237             // will succeed.
13238             if (mArgs != null) {
13239                 processPendingInstall(mArgs, mRet);
13240             }
13241         }
13242
13243         @Override
13244         void handleServiceError() {
13245             mArgs = createInstallArgs(this);
13246             mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13247         }
13248
13249         public boolean isForwardLocked() {
13250             return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13251         }
13252     }
13253
13254     /**
13255      * Used during creation of InstallArgs
13256      *
13257      * @param installFlags package installation flags
13258      * @return true if should be installed on external storage
13259      */
13260     private static boolean installOnExternalAsec(int installFlags) {
13261         if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13262             return false;
13263         }
13264         if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13265             return true;
13266         }
13267         return false;
13268     }
13269
13270     /**
13271      * Used during creation of InstallArgs
13272      *
13273      * @param installFlags package installation flags
13274      * @return true if should be installed as forward locked
13275      */
13276     private static boolean installForwardLocked(int installFlags) {
13277         return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13278     }
13279
13280     private InstallArgs createInstallArgs(InstallParams params) {
13281         if (params.move != null) {
13282             return new MoveInstallArgs(params);
13283         } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13284             return new AsecInstallArgs(params);
13285         } else {
13286             return new FileInstallArgs(params);
13287         }
13288     }
13289
13290     /**
13291      * Create args that describe an existing installed package. Typically used
13292      * when cleaning up old installs, or used as a move source.
13293      */
13294     private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13295             String resourcePath, String[] instructionSets) {
13296         final boolean isInAsec;
13297         if (installOnExternalAsec(installFlags)) {
13298             /* Apps on SD card are always in ASEC containers. */
13299             isInAsec = true;
13300         } else if (installForwardLocked(installFlags)
13301                 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13302             /*
13303              * Forward-locked apps are only in ASEC containers if they're the
13304              * new style
13305              */
13306             isInAsec = true;
13307         } else {
13308             isInAsec = false;
13309         }
13310
13311         if (isInAsec) {
13312             return new AsecInstallArgs(codePath, instructionSets,
13313                     installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13314         } else {
13315             return new FileInstallArgs(codePath, resourcePath, instructionSets);
13316         }
13317     }
13318
13319     static abstract class InstallArgs {
13320         /** @see InstallParams#origin */
13321         final OriginInfo origin;
13322         /** @see InstallParams#move */
13323         final MoveInfo move;
13324
13325         final IPackageInstallObserver2 observer;
13326         // Always refers to PackageManager flags only
13327         final int installFlags;
13328         final String installerPackageName;
13329         final String volumeUuid;
13330         final UserHandle user;
13331         final String abiOverride;
13332         final String[] installGrantPermissions;
13333         /** If non-null, drop an async trace when the install completes */
13334         final String traceMethod;
13335         final int traceCookie;
13336         final Certificate[][] certificates;
13337
13338         // The list of instruction sets supported by this app. This is currently
13339         // only used during the rmdex() phase to clean up resources. We can get rid of this
13340         // if we move dex files under the common app path.
13341         /* nullable */ String[] instructionSets;
13342
13343         InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13344                 int installFlags, String installerPackageName, String volumeUuid,
13345                 UserHandle user, String[] instructionSets,
13346                 String abiOverride, String[] installGrantPermissions,
13347                 String traceMethod, int traceCookie, Certificate[][] certificates) {
13348             this.origin = origin;
13349             this.move = move;
13350             this.installFlags = installFlags;
13351             this.observer = observer;
13352             this.installerPackageName = installerPackageName;
13353             this.volumeUuid = volumeUuid;
13354             this.user = user;
13355             this.instructionSets = instructionSets;
13356             this.abiOverride = abiOverride;
13357             this.installGrantPermissions = installGrantPermissions;
13358             this.traceMethod = traceMethod;
13359             this.traceCookie = traceCookie;
13360             this.certificates = certificates;
13361         }
13362
13363         abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13364         abstract int doPreInstall(int status);
13365
13366         /**
13367          * Rename package into final resting place. All paths on the given
13368          * scanned package should be updated to reflect the rename.
13369          */
13370         abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13371         abstract int doPostInstall(int status, int uid);
13372
13373         /** @see PackageSettingBase#codePathString */
13374         abstract String getCodePath();
13375         /** @see PackageSettingBase#resourcePathString */
13376         abstract String getResourcePath();
13377
13378         // Need installer lock especially for dex file removal.
13379         abstract void cleanUpResourcesLI();
13380         abstract boolean doPostDeleteLI(boolean delete);
13381
13382         /**
13383          * Called before the source arguments are copied. This is used mostly
13384          * for MoveParams when it needs to read the source file to put it in the
13385          * destination.
13386          */
13387         int doPreCopy() {
13388             return PackageManager.INSTALL_SUCCEEDED;
13389         }
13390
13391         /**
13392          * Called after the source arguments are copied. This is used mostly for
13393          * MoveParams when it needs to read the source file to put it in the
13394          * destination.
13395          */
13396         int doPostCopy(int uid) {
13397             return PackageManager.INSTALL_SUCCEEDED;
13398         }
13399
13400         protected boolean isFwdLocked() {
13401             return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13402         }
13403
13404         protected boolean isExternalAsec() {
13405             return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13406         }
13407
13408         protected boolean isEphemeral() {
13409             return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13410         }
13411
13412         UserHandle getUser() {
13413             return user;
13414         }
13415     }
13416
13417     private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13418         if (!allCodePaths.isEmpty()) {
13419             if (instructionSets == null) {
13420                 throw new IllegalStateException("instructionSet == null");
13421             }
13422             String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13423             for (String codePath : allCodePaths) {
13424                 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13425                     try {
13426                         mInstaller.rmdex(codePath, dexCodeInstructionSet);
13427                     } catch (InstallerException ignored) {
13428                     }
13429                 }
13430             }
13431         }
13432     }
13433
13434     /**
13435      * Logic to handle installation of non-ASEC applications, including copying
13436      * and renaming logic.
13437      */
13438     class FileInstallArgs extends InstallArgs {
13439         private File codeFile;
13440         private File resourceFile;
13441
13442         // Example topology:
13443         // /data/app/com.example/base.apk
13444         // /data/app/com.example/split_foo.apk
13445         // /data/app/com.example/lib/arm/libfoo.so
13446         // /data/app/com.example/lib/arm64/libfoo.so
13447         // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13448
13449         /** New install */
13450         FileInstallArgs(InstallParams params) {
13451             super(params.origin, params.move, params.observer, params.installFlags,
13452                     params.installerPackageName, params.volumeUuid,
13453                     params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13454                     params.grantedRuntimePermissions,
13455                     params.traceMethod, params.traceCookie, params.certificates);
13456             if (isFwdLocked()) {
13457                 throw new IllegalArgumentException("Forward locking only supported in ASEC");
13458             }
13459         }
13460
13461         /** Existing install */
13462         FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13463             super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13464                     null, null, null, 0, null /*certificates*/);
13465             this.codeFile = (codePath != null) ? new File(codePath) : null;
13466             this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13467         }
13468
13469         int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13470             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13471             try {
13472                 return doCopyApk(imcs, temp);
13473             } finally {
13474                 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13475             }
13476         }
13477
13478         private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13479             if (origin.staged) {
13480                 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13481                 codeFile = origin.file;
13482                 resourceFile = origin.file;
13483                 return PackageManager.INSTALL_SUCCEEDED;
13484             }
13485
13486             try {
13487                 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13488                 final File tempDir =
13489                         mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13490                 codeFile = tempDir;
13491                 resourceFile = tempDir;
13492             } catch (IOException e) {
13493                 Slog.w(TAG, "Failed to create copy file: " + e);
13494                 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13495             }
13496
13497             final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13498                 @Override
13499                 public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13500                     if (!FileUtils.isValidExtFilename(name)) {
13501                         throw new IllegalArgumentException("Invalid filename: " + name);
13502                     }
13503                     try {
13504                         final File file = new File(codeFile, name);
13505                         final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13506                                 O_RDWR | O_CREAT, 0644);
13507                         Os.chmod(file.getAbsolutePath(), 0644);
13508                         return new ParcelFileDescriptor(fd);
13509                     } catch (ErrnoException e) {
13510                         throw new RemoteException("Failed to open: " + e.getMessage());
13511                     }
13512                 }
13513             };
13514
13515             int ret = PackageManager.INSTALL_SUCCEEDED;
13516             ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13517             if (ret != PackageManager.INSTALL_SUCCEEDED) {
13518                 Slog.e(TAG, "Failed to copy package");
13519                 return ret;
13520             }
13521
13522             final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13523             NativeLibraryHelper.Handle handle = null;
13524             try {
13525                 handle = NativeLibraryHelper.Handle.create(codeFile);
13526                 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13527                         abiOverride);
13528             } catch (IOException e) {
13529                 Slog.e(TAG, "Copying native libraries failed", e);
13530                 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13531             } finally {
13532                 IoUtils.closeQuietly(handle);
13533             }
13534
13535             return ret;
13536         }
13537
13538         int doPreInstall(int status) {
13539             if (status != PackageManager.INSTALL_SUCCEEDED) {
13540                 cleanUp();
13541             }
13542             return status;
13543         }
13544
13545         boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13546             if (status != PackageManager.INSTALL_SUCCEEDED) {
13547                 cleanUp();
13548                 return false;
13549             }
13550
13551             final File targetDir = codeFile.getParentFile();
13552             final File beforeCodeFile = codeFile;
13553             final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13554
13555             if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13556             try {
13557                 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13558             } catch (ErrnoException e) {
13559                 Slog.w(TAG, "Failed to rename", e);
13560                 return false;
13561             }
13562
13563             if (!SELinux.restoreconRecursive(afterCodeFile)) {
13564                 Slog.w(TAG, "Failed to restorecon");
13565                 return false;
13566             }
13567
13568             // Reflect the rename internally
13569             codeFile = afterCodeFile;
13570             resourceFile = afterCodeFile;
13571
13572             // Reflect the rename in scanned details
13573             pkg.setCodePath(afterCodeFile.getAbsolutePath());
13574             pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13575                     afterCodeFile, pkg.baseCodePath));
13576             pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13577                     afterCodeFile, pkg.splitCodePaths));
13578
13579             // Reflect the rename in app info
13580             pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13581             pkg.setApplicationInfoCodePath(pkg.codePath);
13582             pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13583             pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13584             pkg.setApplicationInfoResourcePath(pkg.codePath);
13585             pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13586             pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13587
13588             return true;
13589         }
13590
13591         int doPostInstall(int status, int uid) {
13592             if (status != PackageManager.INSTALL_SUCCEEDED) {
13593                 cleanUp();
13594             }
13595             return status;
13596         }
13597
13598         @Override
13599         String getCodePath() {
13600             return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13601         }
13602
13603         @Override
13604         String getResourcePath() {
13605             return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13606         }
13607
13608         private boolean cleanUp() {
13609             if (codeFile == null || !codeFile.exists()) {
13610                 return false;
13611             }
13612
13613             removeCodePathLI(codeFile);
13614
13615             if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13616                 resourceFile.delete();
13617             }
13618
13619             return true;
13620         }
13621
13622         void cleanUpResourcesLI() {
13623             // Try enumerating all code paths before deleting
13624             List<String> allCodePaths = Collections.EMPTY_LIST;
13625             if (codeFile != null && codeFile.exists()) {
13626                 try {
13627                     final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13628                     allCodePaths = pkg.getAllCodePaths();
13629                 } catch (PackageParserException e) {
13630                     // Ignored; we tried our best
13631                 }
13632             }
13633
13634             cleanUp();
13635             removeDexFiles(allCodePaths, instructionSets);
13636         }
13637
13638         boolean doPostDeleteLI(boolean delete) {
13639             // XXX err, shouldn't we respect the delete flag?
13640             cleanUpResourcesLI();
13641             return true;
13642         }
13643     }
13644
13645     private boolean isAsecExternal(String cid) {
13646         final String asecPath = PackageHelper.getSdFilesystem(cid);
13647         return !asecPath.startsWith(mAsecInternalPath);
13648     }
13649
13650     private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13651             PackageManagerException {
13652         if (copyRet < 0) {
13653             if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13654                     copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13655                 throw new PackageManagerException(copyRet, message);
13656             }
13657         }
13658     }
13659
13660     /**
13661      * Extract the MountService "container ID" from the full code path of an
13662      * .apk.
13663      */
13664     static String cidFromCodePath(String fullCodePath) {
13665         int eidx = fullCodePath.lastIndexOf("/");
13666         String subStr1 = fullCodePath.substring(0, eidx);
13667         int sidx = subStr1.lastIndexOf("/");
13668         return subStr1.substring(sidx+1, eidx);
13669     }
13670
13671     /**
13672      * Logic to handle installation of ASEC applications, including copying and
13673      * renaming logic.
13674      */
13675     class AsecInstallArgs extends InstallArgs {
13676         static final String RES_FILE_NAME = "pkg.apk";
13677         static final String PUBLIC_RES_FILE_NAME = "res.zip";
13678
13679         String cid;
13680         String packagePath;
13681         String resourcePath;
13682
13683         /** New install */
13684         AsecInstallArgs(InstallParams params) {
13685             super(params.origin, params.move, params.observer, params.installFlags,
13686                     params.installerPackageName, params.volumeUuid,
13687                     params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13688                     params.grantedRuntimePermissions,
13689                     params.traceMethod, params.traceCookie, params.certificates);
13690         }
13691
13692         /** Existing install */
13693         AsecInstallArgs(String fullCodePath, String[] instructionSets,
13694                         boolean isExternal, boolean isForwardLocked) {
13695             super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13696               | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13697                     instructionSets, null, null, null, 0, null /*certificates*/);
13698             // Hackily pretend we're still looking at a full code path
13699             if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13700                 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13701             }
13702
13703             // Extract cid from fullCodePath
13704             int eidx = fullCodePath.lastIndexOf("/");
13705             String subStr1 = fullCodePath.substring(0, eidx);
13706             int sidx = subStr1.lastIndexOf("/");
13707             cid = subStr1.substring(sidx+1, eidx);
13708             setMountPath(subStr1);
13709         }
13710
13711         AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13712             super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13713               | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13714                     instructionSets, null, null, null, 0, null /*certificates*/);
13715             this.cid = cid;
13716             setMountPath(PackageHelper.getSdDir(cid));
13717         }
13718
13719         void createCopyFile() {
13720             cid = mInstallerService.allocateExternalStageCidLegacy();
13721         }
13722
13723         int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13724             if (origin.staged && origin.cid != null) {
13725                 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13726                 cid = origin.cid;
13727                 setMountPath(PackageHelper.getSdDir(cid));
13728                 return PackageManager.INSTALL_SUCCEEDED;
13729             }
13730
13731             if (temp) {
13732                 createCopyFile();
13733             } else {
13734                 /*
13735                  * Pre-emptively destroy the container since it's destroyed if
13736                  * copying fails due to it existing anyway.
13737                  */
13738                 PackageHelper.destroySdDir(cid);
13739             }
13740
13741             final String newMountPath = imcs.copyPackageToContainer(
13742                     origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13743                     isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13744
13745             if (newMountPath != null) {
13746                 setMountPath(newMountPath);
13747                 return PackageManager.INSTALL_SUCCEEDED;
13748             } else {
13749                 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13750             }
13751         }
13752
13753         @Override
13754         String getCodePath() {
13755             return packagePath;
13756         }
13757
13758         @Override
13759         String getResourcePath() {
13760             return resourcePath;
13761         }
13762
13763         int doPreInstall(int status) {
13764             if (status != PackageManager.INSTALL_SUCCEEDED) {
13765                 // Destroy container
13766                 PackageHelper.destroySdDir(cid);
13767             } else {
13768                 boolean mounted = PackageHelper.isContainerMounted(cid);
13769                 if (!mounted) {
13770                     String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13771                             Process.SYSTEM_UID);
13772                     if (newMountPath != null) {
13773                         setMountPath(newMountPath);
13774                     } else {
13775                         return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13776                     }
13777                 }
13778             }
13779             return status;
13780         }
13781
13782         boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13783             String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13784             String newMountPath = null;
13785             if (PackageHelper.isContainerMounted(cid)) {
13786                 // Unmount the container
13787                 if (!PackageHelper.unMountSdDir(cid)) {
13788                     Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13789                     return false;
13790                 }
13791             }
13792             if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13793                 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13794                         " which might be stale. Will try to clean up.");
13795                 // Clean up the stale container and proceed to recreate.
13796                 if (!PackageHelper.destroySdDir(newCacheId)) {
13797                     Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13798                     return false;
13799                 }
13800                 // Successfully cleaned up stale container. Try to rename again.
13801                 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13802                     Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13803                             + " inspite of cleaning it up.");
13804                     return false;
13805                 }
13806             }
13807             if (!PackageHelper.isContainerMounted(newCacheId)) {
13808                 Slog.w(TAG, "Mounting container " + newCacheId);
13809                 newMountPath = PackageHelper.mountSdDir(newCacheId,
13810                         getEncryptKey(), Process.SYSTEM_UID);
13811             } else {
13812                 newMountPath = PackageHelper.getSdDir(newCacheId);
13813             }
13814             if (newMountPath == null) {
13815                 Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13816                 return false;
13817             }
13818             Log.i(TAG, "Succesfully renamed " + cid +
13819                     " to " + newCacheId +
13820                     " at new path: " + newMountPath);
13821             cid = newCacheId;
13822
13823             final File beforeCodeFile = new File(packagePath);
13824             setMountPath(newMountPath);
13825             final File afterCodeFile = new File(packagePath);
13826
13827             // Reflect the rename in scanned details
13828             pkg.setCodePath(afterCodeFile.getAbsolutePath());
13829             pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13830                     afterCodeFile, pkg.baseCodePath));
13831             pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13832                     afterCodeFile, pkg.splitCodePaths));
13833
13834             // Reflect the rename in app info
13835             pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13836             pkg.setApplicationInfoCodePath(pkg.codePath);
13837             pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13838             pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13839             pkg.setApplicationInfoResourcePath(pkg.codePath);
13840             pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13841             pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13842
13843             return true;
13844         }
13845
13846         private void setMountPath(String mountPath) {
13847             final File mountFile = new File(mountPath);
13848
13849             final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13850             if (monolithicFile.exists()) {
13851                 packagePath = monolithicFile.getAbsolutePath();
13852                 if (isFwdLocked()) {
13853                     resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13854                 } else {
13855                     resourcePath = packagePath;
13856                 }
13857             } else {
13858                 packagePath = mountFile.getAbsolutePath();
13859                 resourcePath = packagePath;
13860             }
13861         }
13862
13863         int doPostInstall(int status, int uid) {
13864             if (status != PackageManager.INSTALL_SUCCEEDED) {
13865                 cleanUp();
13866             } else {
13867                 final int groupOwner;
13868                 final String protectedFile;
13869                 if (isFwdLocked()) {
13870                     groupOwner = UserHandle.getSharedAppGid(uid);
13871                     protectedFile = RES_FILE_NAME;
13872                 } else {
13873                     groupOwner = -1;
13874                     protectedFile = null;
13875                 }
13876
13877                 if (uid < Process.FIRST_APPLICATION_UID
13878                         || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13879                     Slog.e(TAG, "Failed to finalize " + cid);
13880                     PackageHelper.destroySdDir(cid);
13881                     return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13882                 }
13883
13884                 boolean mounted = PackageHelper.isContainerMounted(cid);
13885                 if (!mounted) {
13886                     PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13887                 }
13888             }
13889             return status;
13890         }
13891
13892         private void cleanUp() {
13893             if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13894
13895             // Destroy secure container
13896             PackageHelper.destroySdDir(cid);
13897         }
13898
13899         private List<String> getAllCodePaths() {
13900             final File codeFile = new File(getCodePath());
13901             if (codeFile != null && codeFile.exists()) {
13902                 try {
13903                     final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13904                     return pkg.getAllCodePaths();
13905                 } catch (PackageParserException e) {
13906                     // Ignored; we tried our best
13907                 }
13908             }
13909             return Collections.EMPTY_LIST;
13910         }
13911
13912         void cleanUpResourcesLI() {
13913             // Enumerate all code paths before deleting
13914             cleanUpResourcesLI(getAllCodePaths());
13915         }
13916
13917         private void cleanUpResourcesLI(List<String> allCodePaths) {
13918             cleanUp();
13919             removeDexFiles(allCodePaths, instructionSets);
13920         }
13921
13922         String getPackageName() {
13923             return getAsecPackageName(cid);
13924         }
13925
13926         boolean doPostDeleteLI(boolean delete) {
13927             if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13928             final List<String> allCodePaths = getAllCodePaths();
13929             boolean mounted = PackageHelper.isContainerMounted(cid);
13930             if (mounted) {
13931                 // Unmount first
13932                 if (PackageHelper.unMountSdDir(cid)) {
13933                     mounted = false;
13934                 }
13935             }
13936             if (!mounted && delete) {
13937                 cleanUpResourcesLI(allCodePaths);
13938             }
13939             return !mounted;
13940         }
13941
13942         @Override
13943         int doPreCopy() {
13944             if (isFwdLocked()) {
13945                 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13946                         MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13947                     return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13948                 }
13949             }
13950
13951             return PackageManager.INSTALL_SUCCEEDED;
13952         }
13953
13954         @Override
13955         int doPostCopy(int uid) {
13956             if (isFwdLocked()) {
13957                 if (uid < Process.FIRST_APPLICATION_UID
13958                         || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13959                                 RES_FILE_NAME)) {
13960                     Slog.e(TAG, "Failed to finalize " + cid);
13961                     PackageHelper.destroySdDir(cid);
13962                     return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13963                 }
13964             }
13965
13966             return PackageManager.INSTALL_SUCCEEDED;
13967         }
13968     }
13969
13970     /**
13971      * Logic to handle movement of existing installed applications.
13972      */
13973     class MoveInstallArgs extends InstallArgs {
13974         private File codeFile;
13975         private File resourceFile;
13976
13977         /** New install */
13978         MoveInstallArgs(InstallParams params) {
13979             super(params.origin, params.move, params.observer, params.installFlags,
13980                     params.installerPackageName, params.volumeUuid,
13981                     params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13982                     params.grantedRuntimePermissions,
13983                     params.traceMethod, params.traceCookie, params.certificates);
13984         }
13985
13986         int copyApk(IMediaContainerService imcs, boolean temp) {
13987             if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13988                     + move.fromUuid + " to " + move.toUuid);
13989             synchronized (mInstaller) {
13990                 try {
13991                     mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13992                             move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13993                 } catch (InstallerException e) {
13994                     Slog.w(TAG, "Failed to move app", e);
13995                     return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13996                 }
13997             }
13998
13999             codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
14000             resourceFile = codeFile;
14001             if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
14002
14003             return PackageManager.INSTALL_SUCCEEDED;
14004         }
14005
14006         int doPreInstall(int status) {
14007             if (status != PackageManager.INSTALL_SUCCEEDED) {
14008                 cleanUp(move.toUuid);
14009             }
14010             return status;
14011         }
14012
14013         boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14014             if (status != PackageManager.INSTALL_SUCCEEDED) {
14015                 cleanUp(move.toUuid);
14016                 return false;
14017             }
14018
14019             // Reflect the move in app info
14020             pkg.setApplicationVolumeUuid(pkg.volumeUuid);
14021             pkg.setApplicationInfoCodePath(pkg.codePath);
14022             pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
14023             pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
14024             pkg.setApplicationInfoResourcePath(pkg.codePath);
14025             pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
14026             pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
14027
14028             return true;
14029         }
14030
14031         int doPostInstall(int status, int uid) {
14032             if (status == PackageManager.INSTALL_SUCCEEDED) {
14033                 cleanUp(move.fromUuid);
14034             } else {
14035                 cleanUp(move.toUuid);
14036             }
14037             return status;
14038         }
14039
14040         @Override
14041         String getCodePath() {
14042             return (codeFile != null) ? codeFile.getAbsolutePath() : null;
14043         }
14044
14045         @Override
14046         String getResourcePath() {
14047             return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
14048         }
14049
14050         private boolean cleanUp(String volumeUuid) {
14051             final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
14052                     move.dataAppName);
14053             Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
14054             final int[] userIds = sUserManager.getUserIds();
14055             synchronized (mInstallLock) {
14056                 // Clean up both app data and code
14057                 // All package moves are frozen until finished
14058                 for (int userId : userIds) {
14059                     try {
14060                         mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
14061                                 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
14062                     } catch (InstallerException e) {
14063                         Slog.w(TAG, String.valueOf(e));
14064                     }
14065                 }
14066                 removeCodePathLI(codeFile);
14067             }
14068             return true;
14069         }
14070
14071         void cleanUpResourcesLI() {
14072             throw new UnsupportedOperationException();
14073         }
14074
14075         boolean doPostDeleteLI(boolean delete) {
14076             throw new UnsupportedOperationException();
14077         }
14078     }
14079
14080     static String getAsecPackageName(String packageCid) {
14081         int idx = packageCid.lastIndexOf("-");
14082         if (idx == -1) {
14083             return packageCid;
14084         }
14085         return packageCid.substring(0, idx);
14086     }
14087
14088     // Utility method used to create code paths based on package name and available index.
14089     private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
14090         String idxStr = "";
14091         int idx = 1;
14092         // Fall back to default value of idx=1 if prefix is not
14093         // part of oldCodePath
14094         if (oldCodePath != null) {
14095             String subStr = oldCodePath;
14096             // Drop the suffix right away
14097             if (suffix != null && subStr.endsWith(suffix)) {
14098                 subStr = subStr.substring(0, subStr.length() - suffix.length());
14099             }
14100             // If oldCodePath already contains prefix find out the
14101             // ending index to either increment or decrement.
14102             int sidx = subStr.lastIndexOf(prefix);
14103             if (sidx != -1) {
14104                 subStr = subStr.substring(sidx + prefix.length());
14105                 if (subStr != null) {
14106                     if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
14107                         subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
14108                     }
14109                     try {
14110                         idx = Integer.parseInt(subStr);
14111                         if (idx <= 1) {
14112                             idx++;
14113                         } else {
14114                             idx--;
14115                         }
14116                     } catch(NumberFormatException e) {
14117                     }
14118                 }
14119             }
14120         }
14121         idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
14122         return prefix + idxStr;
14123     }
14124
14125     private File getNextCodePath(File targetDir, String packageName) {
14126         int suffix = 1;
14127         File result;
14128         do {
14129             result = new File(targetDir, packageName + "-" + suffix);
14130             suffix++;
14131         } while (result.exists());
14132         return result;
14133     }
14134
14135     // Utility method that returns the relative package path with respect
14136     // to the installation directory. Like say for /data/data/com.test-1.apk
14137     // string com.test-1 is returned.
14138     static String deriveCodePathName(String codePath) {
14139         if (codePath == null) {
14140             return null;
14141         }
14142         final File codeFile = new File(codePath);
14143         final String name = codeFile.getName();
14144         if (codeFile.isDirectory()) {
14145             return name;
14146         } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14147             final int lastDot = name.lastIndexOf('.');
14148             return name.substring(0, lastDot);
14149         } else {
14150             Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14151             return null;
14152         }
14153     }
14154
14155     static class PackageInstalledInfo {
14156         String name;
14157         int uid;
14158         // The set of users that originally had this package installed.
14159         int[] origUsers;
14160         // The set of users that now have this package installed.
14161         int[] newUsers;
14162         PackageParser.Package pkg;
14163         int returnCode;
14164         String returnMsg;
14165         PackageRemovedInfo removedInfo;
14166         ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14167
14168         public void setError(int code, String msg) {
14169             setReturnCode(code);
14170             setReturnMessage(msg);
14171             Slog.w(TAG, msg);
14172         }
14173
14174         public void setError(String msg, PackageParserException e) {
14175             setReturnCode(e.error);
14176             setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14177             Slog.w(TAG, msg, e);
14178         }
14179
14180         public void setError(String msg, PackageManagerException e) {
14181             returnCode = e.error;
14182             setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14183             Slog.w(TAG, msg, e);
14184         }
14185
14186         public void setReturnCode(int returnCode) {
14187             this.returnCode = returnCode;
14188             final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14189             for (int i = 0; i < childCount; i++) {
14190                 addedChildPackages.valueAt(i).returnCode = returnCode;
14191             }
14192         }
14193
14194         private void setReturnMessage(String returnMsg) {
14195             this.returnMsg = returnMsg;
14196             final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14197             for (int i = 0; i < childCount; i++) {
14198                 addedChildPackages.valueAt(i).returnMsg = returnMsg;
14199             }
14200         }
14201
14202         // In some error cases we want to convey more info back to the observer
14203         String origPackage;
14204         String origPermission;
14205     }
14206
14207     /*
14208      * Install a non-existing package.
14209      */
14210     private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14211             int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14212             PackageInstalledInfo res) {
14213         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14214
14215         // Remember this for later, in case we need to rollback this install
14216         String pkgName = pkg.packageName;
14217
14218         if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14219
14220         synchronized(mPackages) {
14221             if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14222                 // A package with the same name is already installed, though
14223                 // it has been renamed to an older name.  The package we
14224                 // are trying to install should be installed as an update to
14225                 // the existing one, but that has not been requested, so bail.
14226                 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14227                         + " without first uninstalling package running as "
14228                         + mSettings.mRenamedPackages.get(pkgName));
14229                 return;
14230             }
14231             if (mPackages.containsKey(pkgName)) {
14232                 // Don't allow installation over an existing package with the same name.
14233                 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14234                         + " without first uninstalling.");
14235                 return;
14236             }
14237         }
14238
14239         try {
14240             PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14241                     System.currentTimeMillis(), user);
14242
14243             updateSettingsLI(newPackage, installerPackageName, null, res, user);
14244
14245             if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14246                 prepareAppDataAfterInstallLIF(newPackage);
14247
14248             } else {
14249                 // Remove package from internal structures, but keep around any
14250                 // data that might have already existed
14251                 deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14252                         PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14253             }
14254         } catch (PackageManagerException e) {
14255             res.setError("Package couldn't be installed in " + pkg.codePath, e);
14256         }
14257
14258         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14259     }
14260
14261     private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14262         // Can't rotate keys during boot or if sharedUser.
14263         if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14264                 || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14265             return false;
14266         }
14267         // app is using upgradeKeySets; make sure all are valid
14268         KeySetManagerService ksms = mSettings.mKeySetManagerService;
14269         long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14270         for (int i = 0; i < upgradeKeySets.length; i++) {
14271             if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14272                 Slog.wtf(TAG, "Package "
14273                          + (oldPs.name != null ? oldPs.name : "<null>")
14274                          + " contains upgrade-key-set reference to unknown key-set: "
14275                          + upgradeKeySets[i]
14276                          + " reverting to signatures check.");
14277                 return false;
14278             }
14279         }
14280         return true;
14281     }
14282
14283     private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14284         // Upgrade keysets are being used.  Determine if new package has a superset of the
14285         // required keys.
14286         long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14287         KeySetManagerService ksms = mSettings.mKeySetManagerService;
14288         for (int i = 0; i < upgradeKeySets.length; i++) {
14289             Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14290             if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14291                 return true;
14292             }
14293         }
14294         return false;
14295     }
14296
14297     private static void updateDigest(MessageDigest digest, File file) throws IOException {
14298         try (DigestInputStream digestStream =
14299                 new DigestInputStream(new FileInputStream(file), digest)) {
14300             while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14301         }
14302     }
14303
14304     private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14305             UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14306         final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14307
14308         final PackageParser.Package oldPackage;
14309         final String pkgName = pkg.packageName;
14310         final int[] allUsers;
14311         final int[] installedUsers;
14312
14313         synchronized(mPackages) {
14314             oldPackage = mPackages.get(pkgName);
14315             if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14316
14317             // don't allow upgrade to target a release SDK from a pre-release SDK
14318             final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14319                     == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14320             final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14321                     == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14322             if (oldTargetsPreRelease
14323                     && !newTargetsPreRelease
14324                     && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14325                 Slog.w(TAG, "Can't install package targeting released sdk");
14326                 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14327                 return;
14328             }
14329
14330             // don't allow an upgrade from full to ephemeral
14331             final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14332             if (isEphemeral && !oldIsEphemeral) {
14333                 // can't downgrade from full to ephemeral
14334                 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14335                 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14336                 return;
14337             }
14338
14339             // verify signatures are valid
14340             final PackageSetting ps = mSettings.mPackages.get(pkgName);
14341             if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14342                 if (!checkUpgradeKeySetLP(ps, pkg)) {
14343                     res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14344                             "New package not signed by keys specified by upgrade-keysets: "
14345                                     + pkgName);
14346                     return;
14347                 }
14348             } else {
14349                 // default to original signature matching
14350                 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14351                         != PackageManager.SIGNATURE_MATCH) {
14352                     res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14353                             "New package has a different signature: " + pkgName);
14354                     return;
14355                 }
14356             }
14357
14358             // don't allow a system upgrade unless the upgrade hash matches
14359             if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14360                 byte[] digestBytes = null;
14361                 try {
14362                     final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14363                     updateDigest(digest, new File(pkg.baseCodePath));
14364                     if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14365                         for (String path : pkg.splitCodePaths) {
14366                             updateDigest(digest, new File(path));
14367                         }
14368                     }
14369                     digestBytes = digest.digest();
14370                 } catch (NoSuchAlgorithmException | IOException e) {
14371                     res.setError(INSTALL_FAILED_INVALID_APK,
14372                             "Could not compute hash: " + pkgName);
14373                     return;
14374                 }
14375                 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14376                     res.setError(INSTALL_FAILED_INVALID_APK,
14377                             "New package fails restrict-update check: " + pkgName);
14378                     return;
14379                 }
14380                 // retain upgrade restriction
14381                 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14382             }
14383
14384             // Check for shared user id changes
14385             String invalidPackageName =
14386                     getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14387             if (invalidPackageName != null) {
14388                 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14389                         "Package " + invalidPackageName + " tried to change user "
14390                                 + oldPackage.mSharedUserId);
14391                 return;
14392             }
14393
14394             // In case of rollback, remember per-user/profile install state
14395             allUsers = sUserManager.getUserIds();
14396             installedUsers = ps.queryInstalledUsers(allUsers, true);
14397         }
14398
14399         // Update what is removed
14400         res.removedInfo = new PackageRemovedInfo();
14401         res.removedInfo.uid = oldPackage.applicationInfo.uid;
14402         res.removedInfo.removedPackage = oldPackage.packageName;
14403         res.removedInfo.isUpdate = true;
14404         res.removedInfo.origUsers = installedUsers;
14405         final int childCount = (oldPackage.childPackages != null)
14406                 ? oldPackage.childPackages.size() : 0;
14407         for (int i = 0; i < childCount; i++) {
14408             boolean childPackageUpdated = false;
14409             PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14410             if (res.addedChildPackages != null) {
14411                 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14412                 if (childRes != null) {
14413                     childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14414                     childRes.removedInfo.removedPackage = childPkg.packageName;
14415                     childRes.removedInfo.isUpdate = true;
14416                     childPackageUpdated = true;
14417                 }
14418             }
14419             if (!childPackageUpdated) {
14420                 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14421                 childRemovedRes.removedPackage = childPkg.packageName;
14422                 childRemovedRes.isUpdate = false;
14423                 childRemovedRes.dataRemoved = true;
14424                 synchronized (mPackages) {
14425                     PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14426                     if (childPs != null) {
14427                         childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14428                     }
14429                 }
14430                 if (res.removedInfo.removedChildPackages == null) {
14431                     res.removedInfo.removedChildPackages = new ArrayMap<>();
14432                 }
14433                 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14434             }
14435         }
14436
14437         boolean sysPkg = (isSystemApp(oldPackage));
14438         if (sysPkg) {
14439             // Set the system/privileged flags as needed
14440             final boolean privileged =
14441                     (oldPackage.applicationInfo.privateFlags
14442                             & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14443             final int systemPolicyFlags = policyFlags
14444                     | PackageParser.PARSE_IS_SYSTEM
14445                     | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14446
14447             replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14448                     user, allUsers, installerPackageName, res);
14449         } else {
14450             replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14451                     user, allUsers, installerPackageName, res);
14452         }
14453     }
14454
14455     public List<String> getPreviousCodePaths(String packageName) {
14456         final PackageSetting ps = mSettings.mPackages.get(packageName);
14457         final List<String> result = new ArrayList<String>();
14458         if (ps != null && ps.oldCodePaths != null) {
14459             result.addAll(ps.oldCodePaths);
14460         }
14461         return result;
14462     }
14463
14464     private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14465             PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14466             int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14467         if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14468                 + deletedPackage);
14469
14470         String pkgName = deletedPackage.packageName;
14471         boolean deletedPkg = true;
14472         boolean addedPkg = false;
14473         boolean updatedSettings = false;
14474         final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14475         final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14476                 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14477
14478         final long origUpdateTime = (pkg.mExtras != null)
14479                 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14480
14481         // First delete the existing package while retaining the data directory
14482         if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14483                 res.removedInfo, true, pkg)) {
14484             // If the existing package wasn't successfully deleted
14485             res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14486             deletedPkg = false;
14487         } else {
14488             // Successfully deleted the old package; proceed with replace.
14489
14490             // If deleted package lived in a container, give users a chance to
14491             // relinquish resources before killing.
14492             if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14493                 if (DEBUG_INSTALL) {
14494                     Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14495                 }
14496                 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14497                 final ArrayList<String> pkgList = new ArrayList<String>(1);
14498                 pkgList.add(deletedPackage.applicationInfo.packageName);
14499                 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14500             }
14501
14502             clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14503                     | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14504             clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14505
14506             try {
14507                 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14508                         scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14509                 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14510
14511                 // Update the in-memory copy of the previous code paths.
14512                 PackageSetting ps = mSettings.mPackages.get(pkgName);
14513                 if (!killApp) {
14514                     if (ps.oldCodePaths == null) {
14515                         ps.oldCodePaths = new ArraySet<>();
14516                     }
14517                     Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14518                     if (deletedPackage.splitCodePaths != null) {
14519                         Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14520                     }
14521                 } else {
14522                     ps.oldCodePaths = null;
14523                 }
14524                 if (ps.childPackageNames != null) {
14525                     for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14526                         final String childPkgName = ps.childPackageNames.get(i);
14527                         final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14528                         childPs.oldCodePaths = ps.oldCodePaths;
14529                     }
14530                 }
14531                 prepareAppDataAfterInstallLIF(newPackage);
14532                 addedPkg = true;
14533             } catch (PackageManagerException e) {
14534                 res.setError("Package couldn't be installed in " + pkg.codePath, e);
14535             }
14536         }
14537
14538         if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14539             if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14540
14541             // Revert all internal state mutations and added folders for the failed install
14542             if (addedPkg) {
14543                 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14544                         res.removedInfo, true, null);
14545             }
14546
14547             // Restore the old package
14548             if (deletedPkg) {
14549                 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14550                 File restoreFile = new File(deletedPackage.codePath);
14551                 // Parse old package
14552                 boolean oldExternal = isExternal(deletedPackage);
14553                 int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14554                         (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14555                         (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14556                 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14557                 try {
14558                     scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14559                             null);
14560                 } catch (PackageManagerException e) {
14561                     Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14562                             + e.getMessage());
14563                     return;
14564                 }
14565
14566                 synchronized (mPackages) {
14567                     // Ensure the installer package name up to date
14568                     setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14569
14570                     // Update permissions for restored package
14571                     updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14572
14573                     mSettings.writeLPr();
14574                 }
14575
14576                 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14577             }
14578         } else {
14579             synchronized (mPackages) {
14580                 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14581                 if (ps != null) {
14582                     res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14583                     if (res.removedInfo.removedChildPackages != null) {
14584                         final int childCount = res.removedInfo.removedChildPackages.size();
14585                         // Iterate in reverse as we may modify the collection
14586                         for (int i = childCount - 1; i >= 0; i--) {
14587                             String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14588                             if (res.addedChildPackages.containsKey(childPackageName)) {
14589                                 res.removedInfo.removedChildPackages.removeAt(i);
14590                             } else {
14591                                 PackageRemovedInfo childInfo = res.removedInfo
14592                                         .removedChildPackages.valueAt(i);
14593                                 childInfo.removedForAllUsers = mPackages.get(
14594                                         childInfo.removedPackage) == null;
14595                             }
14596                         }
14597                     }
14598                 }
14599             }
14600         }
14601     }
14602
14603     private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14604             PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14605             int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14606         if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14607                 + ", old=" + deletedPackage);
14608
14609         final boolean disabledSystem;
14610
14611         // Remove existing system package
14612         removePackageLI(deletedPackage, true);
14613
14614         synchronized (mPackages) {
14615             disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14616         }
14617         if (!disabledSystem) {
14618             // We didn't need to disable the .apk as a current system package,
14619             // which means we are replacing another update that is already
14620             // installed.  We need to make sure to delete the older one's .apk.
14621             res.removedInfo.args = createInstallArgsForExisting(0,
14622                     deletedPackage.applicationInfo.getCodePath(),
14623                     deletedPackage.applicationInfo.getResourcePath(),
14624                     getAppDexInstructionSets(deletedPackage.applicationInfo));
14625         } else {
14626             res.removedInfo.args = null;
14627         }
14628
14629         // Successfully disabled the old package. Now proceed with re-installation
14630         clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14631                 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14632         clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14633
14634         res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14635         pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14636                 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14637
14638         PackageParser.Package newPackage = null;
14639         try {
14640             // Add the package to the internal data structures
14641             newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14642
14643             // Set the update and install times
14644             PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14645             setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14646                     System.currentTimeMillis());
14647
14648             // Update the package dynamic state if succeeded
14649             if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14650                 // Now that the install succeeded make sure we remove data
14651                 // directories for any child package the update removed.
14652                 final int deletedChildCount = (deletedPackage.childPackages != null)
14653                         ? deletedPackage.childPackages.size() : 0;
14654                 final int newChildCount = (newPackage.childPackages != null)
14655                         ? newPackage.childPackages.size() : 0;
14656                 for (int i = 0; i < deletedChildCount; i++) {
14657                     PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14658                     boolean childPackageDeleted = true;
14659                     for (int j = 0; j < newChildCount; j++) {
14660                         PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14661                         if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14662                             childPackageDeleted = false;
14663                             break;
14664                         }
14665                     }
14666                     if (childPackageDeleted) {
14667                         PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14668                                 deletedChildPkg.packageName);
14669                         if (ps != null && res.removedInfo.removedChildPackages != null) {
14670                             PackageRemovedInfo removedChildRes = res.removedInfo
14671                                     .removedChildPackages.get(deletedChildPkg.packageName);
14672                             removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14673                             removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14674                         }
14675                     }
14676                 }
14677
14678                 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14679                 prepareAppDataAfterInstallLIF(newPackage);
14680             }
14681         } catch (PackageManagerException e) {
14682             res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14683             res.setError("Package couldn't be installed in " + pkg.codePath, e);
14684         }
14685
14686         if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14687             // Re installation failed. Restore old information
14688             // Remove new pkg information
14689             if (newPackage != null) {
14690                 removeInstalledPackageLI(newPackage, true);
14691             }
14692             // Add back the old system package
14693             try {
14694                 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14695             } catch (PackageManagerException e) {
14696                 Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14697             }
14698
14699             synchronized (mPackages) {
14700                 if (disabledSystem) {
14701                     enableSystemPackageLPw(deletedPackage);
14702                 }
14703
14704                 // Ensure the installer package name up to date
14705                 setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14706
14707                 // Update permissions for restored package
14708                 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14709
14710                 mSettings.writeLPr();
14711             }
14712
14713             Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14714                     + " after failed upgrade");
14715         }
14716     }
14717
14718     /**
14719      * Checks whether the parent or any of the child packages have a change shared
14720      * user. For a package to be a valid update the shred users of the parent and
14721      * the children should match. We may later support changing child shared users.
14722      * @param oldPkg The updated package.
14723      * @param newPkg The update package.
14724      * @return The shared user that change between the versions.
14725      */
14726     private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14727             PackageParser.Package newPkg) {
14728         // Check parent shared user
14729         if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14730             return newPkg.packageName;
14731         }
14732         // Check child shared users
14733         final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14734         final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14735         for (int i = 0; i < newChildCount; i++) {
14736             PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14737             // If this child was present, did it have the same shared user?
14738             for (int j = 0; j < oldChildCount; j++) {
14739                 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14740                 if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14741                         && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14742                     return newChildPkg.packageName;
14743                 }
14744             }
14745         }
14746         return null;
14747     }
14748
14749     private void removeNativeBinariesLI(PackageSetting ps) {
14750         // Remove the lib path for the parent package
14751         if (ps != null) {
14752             NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14753             // Remove the lib path for the child packages
14754             final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14755             for (int i = 0; i < childCount; i++) {
14756                 PackageSetting childPs = null;
14757                 synchronized (mPackages) {
14758                     childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14759                 }
14760                 if (childPs != null) {
14761                     NativeLibraryHelper.removeNativeBinariesLI(childPs
14762                             .legacyNativeLibraryPathString);
14763                 }
14764             }
14765         }
14766     }
14767
14768     private void enableSystemPackageLPw(PackageParser.Package pkg) {
14769         // Enable the parent package
14770         mSettings.enableSystemPackageLPw(pkg.packageName);
14771         // Enable the child packages
14772         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14773         for (int i = 0; i < childCount; i++) {
14774             PackageParser.Package childPkg = pkg.childPackages.get(i);
14775             mSettings.enableSystemPackageLPw(childPkg.packageName);
14776         }
14777     }
14778
14779     private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14780             PackageParser.Package newPkg) {
14781         // Disable the parent package (parent always replaced)
14782         boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14783         // Disable the child packages
14784         final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14785         for (int i = 0; i < childCount; i++) {
14786             PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14787             final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14788             disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14789         }
14790         return disabled;
14791     }
14792
14793     private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14794             String installerPackageName) {
14795         // Enable the parent package
14796         mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14797         // Enable the child packages
14798         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14799         for (int i = 0; i < childCount; i++) {
14800             PackageParser.Package childPkg = pkg.childPackages.get(i);
14801             mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14802         }
14803     }
14804
14805     private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14806         // Collect all used permissions in the UID
14807         ArraySet<String> usedPermissions = new ArraySet<>();
14808         final int packageCount = su.packages.size();
14809         for (int i = 0; i < packageCount; i++) {
14810             PackageSetting ps = su.packages.valueAt(i);
14811             if (ps.pkg == null) {
14812                 continue;
14813             }
14814             final int requestedPermCount = ps.pkg.requestedPermissions.size();
14815             for (int j = 0; j < requestedPermCount; j++) {
14816                 String permission = ps.pkg.requestedPermissions.get(j);
14817                 BasePermission bp = mSettings.mPermissions.get(permission);
14818                 if (bp != null) {
14819                     usedPermissions.add(permission);
14820                 }
14821             }
14822         }
14823
14824         PermissionsState permissionsState = su.getPermissionsState();
14825         // Prune install permissions
14826         List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14827         final int installPermCount = installPermStates.size();
14828         for (int i = installPermCount - 1; i >= 0;  i--) {
14829             PermissionState permissionState = installPermStates.get(i);
14830             if (!usedPermissions.contains(permissionState.getName())) {
14831                 BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14832                 if (bp != null) {
14833                     permissionsState.revokeInstallPermission(bp);
14834                     permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14835                             PackageManager.MASK_PERMISSION_FLAGS, 0);
14836                 }
14837             }
14838         }
14839
14840         int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14841
14842         // Prune runtime permissions
14843         for (int userId : allUserIds) {
14844             List<PermissionState> runtimePermStates = permissionsState
14845                     .getRuntimePermissionStates(userId);
14846             final int runtimePermCount = runtimePermStates.size();
14847             for (int i = runtimePermCount - 1; i >= 0; i--) {
14848                 PermissionState permissionState = runtimePermStates.get(i);
14849                 if (!usedPermissions.contains(permissionState.getName())) {
14850                     BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14851                     if (bp != null) {
14852                         permissionsState.revokeRuntimePermission(bp, userId);
14853                         permissionsState.updatePermissionFlags(bp, userId,
14854                                 PackageManager.MASK_PERMISSION_FLAGS, 0);
14855                         runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14856                                 runtimePermissionChangedUserIds, userId);
14857                     }
14858                 }
14859             }
14860         }
14861
14862         return runtimePermissionChangedUserIds;
14863     }
14864
14865     private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14866             int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14867         // Update the parent package setting
14868         updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14869                 res, user);
14870         // Update the child packages setting
14871         final int childCount = (newPackage.childPackages != null)
14872                 ? newPackage.childPackages.size() : 0;
14873         for (int i = 0; i < childCount; i++) {
14874             PackageParser.Package childPackage = newPackage.childPackages.get(i);
14875             PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14876             updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14877                     childRes.origUsers, childRes, user);
14878         }
14879     }
14880
14881     private void updateSettingsInternalLI(PackageParser.Package newPackage,
14882             String installerPackageName, int[] allUsers, int[] installedForUsers,
14883             PackageInstalledInfo res, UserHandle user) {
14884         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14885
14886         String pkgName = newPackage.packageName;
14887         synchronized (mPackages) {
14888             //write settings. the installStatus will be incomplete at this stage.
14889             //note that the new package setting would have already been
14890             //added to mPackages. It hasn't been persisted yet.
14891             mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14892             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14893             mSettings.writeLPr();
14894             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14895         }
14896
14897         if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14898         synchronized (mPackages) {
14899             updatePermissionsLPw(newPackage.packageName, newPackage,
14900                     UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14901                             ? UPDATE_PERMISSIONS_ALL : 0));
14902             // For system-bundled packages, we assume that installing an upgraded version
14903             // of the package implies that the user actually wants to run that new code,
14904             // so we enable the package.
14905             PackageSetting ps = mSettings.mPackages.get(pkgName);
14906             final int userId = user.getIdentifier();
14907             if (ps != null) {
14908                 if (isSystemApp(newPackage)) {
14909                     if (DEBUG_INSTALL) {
14910                         Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14911                     }
14912                     // Enable system package for requested users
14913                     if (res.origUsers != null) {
14914                         for (int origUserId : res.origUsers) {
14915                             if (userId == UserHandle.USER_ALL || userId == origUserId) {
14916                                 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14917                                         origUserId, installerPackageName);
14918                             }
14919                         }
14920                     }
14921                     // Also convey the prior install/uninstall state
14922                     if (allUsers != null && installedForUsers != null) {
14923                         for (int currentUserId : allUsers) {
14924                             final boolean installed = ArrayUtils.contains(
14925                                     installedForUsers, currentUserId);
14926                             if (DEBUG_INSTALL) {
14927                                 Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14928                             }
14929                             ps.setInstalled(installed, currentUserId);
14930                         }
14931                         // these install state changes will be persisted in the
14932                         // upcoming call to mSettings.writeLPr().
14933                     }
14934                 }
14935                 // It's implied that when a user requests installation, they want the app to be
14936                 // installed and enabled.
14937                 if (userId != UserHandle.USER_ALL) {
14938                     ps.setInstalled(true, userId);
14939                     ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14940                 }
14941             }
14942             res.name = pkgName;
14943             res.uid = newPackage.applicationInfo.uid;
14944             res.pkg = newPackage;
14945             mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14946             mSettings.setInstallerPackageName(pkgName, installerPackageName);
14947             res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14948             //to update install status
14949             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14950             mSettings.writeLPr();
14951             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14952         }
14953
14954         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14955     }
14956
14957     private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14958         try {
14959             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14960             installPackageLI(args, res);
14961         } finally {
14962             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14963         }
14964     }
14965
14966     private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14967         final int installFlags = args.installFlags;
14968         final String installerPackageName = args.installerPackageName;
14969         final String volumeUuid = args.volumeUuid;
14970         final File tmpPackageFile = new File(args.getCodePath());
14971         final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14972         final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14973                 || (args.volumeUuid != null));
14974         final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14975         final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14976         boolean replace = false;
14977         int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14978         if (args.move != null) {
14979             // moving a complete application; perform an initial scan on the new install location
14980             scanFlags |= SCAN_INITIAL;
14981         }
14982         if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14983             scanFlags |= SCAN_DONT_KILL_APP;
14984         }
14985
14986         // Result object to be returned
14987         res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14988
14989         if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14990
14991         // Sanity check
14992         if (ephemeral && (forwardLocked || onExternal)) {
14993             Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14994                     + " external=" + onExternal);
14995             res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14996             return;
14997         }
14998
14999         // Retrieve PackageSettings and parse package
15000         final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
15001                 | PackageParser.PARSE_ENFORCE_CODE
15002                 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
15003                 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
15004                 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
15005                 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
15006         PackageParser pp = new PackageParser();
15007         pp.setSeparateProcesses(mSeparateProcesses);
15008         pp.setDisplayMetrics(mMetrics);
15009
15010         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
15011         final PackageParser.Package pkg;
15012         try {
15013             pkg = pp.parsePackage(tmpPackageFile, parseFlags);
15014         } catch (PackageParserException e) {
15015             res.setError("Failed parse during installPackageLI", e);
15016             return;
15017         } finally {
15018             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15019         }
15020
15021         // If we are installing a clustered package add results for the children
15022         if (pkg.childPackages != null) {
15023             synchronized (mPackages) {
15024                 final int childCount = pkg.childPackages.size();
15025                 for (int i = 0; i < childCount; i++) {
15026                     PackageParser.Package childPkg = pkg.childPackages.get(i);
15027                     PackageInstalledInfo childRes = new PackageInstalledInfo();
15028                     childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
15029                     childRes.pkg = childPkg;
15030                     childRes.name = childPkg.packageName;
15031                     PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15032                     if (childPs != null) {
15033                         childRes.origUsers = childPs.queryInstalledUsers(
15034                                 sUserManager.getUserIds(), true);
15035                     }
15036                     if ((mPackages.containsKey(childPkg.packageName))) {
15037                         childRes.removedInfo = new PackageRemovedInfo();
15038                         childRes.removedInfo.removedPackage = childPkg.packageName;
15039                     }
15040                     if (res.addedChildPackages == null) {
15041                         res.addedChildPackages = new ArrayMap<>();
15042                     }
15043                     res.addedChildPackages.put(childPkg.packageName, childRes);
15044                 }
15045             }
15046         }
15047
15048         // If package doesn't declare API override, mark that we have an install
15049         // time CPU ABI override.
15050         if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
15051             pkg.cpuAbiOverride = args.abiOverride;
15052         }
15053
15054         String pkgName = res.name = pkg.packageName;
15055         if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
15056             if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
15057                 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
15058                 return;
15059             }
15060         }
15061
15062         try {
15063             // either use what we've been given or parse directly from the APK
15064             if (args.certificates != null) {
15065                 try {
15066                     PackageParser.populateCertificates(pkg, args.certificates);
15067                 } catch (PackageParserException e) {
15068                     // there was something wrong with the certificates we were given;
15069                     // try to pull them from the APK
15070                     PackageParser.collectCertificates(pkg, parseFlags);
15071                 }
15072             } else {
15073                 PackageParser.collectCertificates(pkg, parseFlags);
15074             }
15075         } catch (PackageParserException e) {
15076             res.setError("Failed collect during installPackageLI", e);
15077             return;
15078         }
15079
15080         // Get rid of all references to package scan path via parser.
15081         pp = null;
15082         String oldCodePath = null;
15083         boolean systemApp = false;
15084         synchronized (mPackages) {
15085             // Check if installing already existing package
15086             if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15087                 String oldName = mSettings.mRenamedPackages.get(pkgName);
15088                 if (pkg.mOriginalPackages != null
15089                         && pkg.mOriginalPackages.contains(oldName)
15090                         && mPackages.containsKey(oldName)) {
15091                     // This package is derived from an original package,
15092                     // and this device has been updating from that original
15093                     // name.  We must continue using the original name, so
15094                     // rename the new package here.
15095                     pkg.setPackageName(oldName);
15096                     pkgName = pkg.packageName;
15097                     replace = true;
15098                     if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
15099                             + oldName + " pkgName=" + pkgName);
15100                 } else if (mPackages.containsKey(pkgName)) {
15101                     // This package, under its official name, already exists
15102                     // on the device; we should replace it.
15103                     replace = true;
15104                     if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
15105                 }
15106
15107                 // Child packages are installed through the parent package
15108                 if (pkg.parentPackage != null) {
15109                     res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15110                             "Package " + pkg.packageName + " is child of package "
15111                                     + pkg.parentPackage.parentPackage + ". Child packages "
15112                                     + "can be updated only through the parent package.");
15113                     return;
15114                 }
15115
15116                 if (replace) {
15117                     // Prevent apps opting out from runtime permissions
15118                     PackageParser.Package oldPackage = mPackages.get(pkgName);
15119                     final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
15120                     final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
15121                     if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
15122                             && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
15123                         res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
15124                                 "Package " + pkg.packageName + " new target SDK " + newTargetSdk
15125                                         + " doesn't support runtime permissions but the old"
15126                                         + " target SDK " + oldTargetSdk + " does.");
15127                         return;
15128                     }
15129
15130                     // Prevent installing of child packages
15131                     if (oldPackage.parentPackage != null) {
15132                         res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15133                                 "Package " + pkg.packageName + " is child of package "
15134                                         + oldPackage.parentPackage + ". Child packages "
15135                                         + "can be updated only through the parent package.");
15136                         return;
15137                     }
15138                 }
15139             }
15140
15141             PackageSetting ps = mSettings.mPackages.get(pkgName);
15142             if (ps != null) {
15143                 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15144
15145                 // Quick sanity check that we're signed correctly if updating;
15146                 // we'll check this again later when scanning, but we want to
15147                 // bail early here before tripping over redefined permissions.
15148                 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15149                     if (!checkUpgradeKeySetLP(ps, pkg)) {
15150                         res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15151                                 + pkg.packageName + " upgrade keys do not match the "
15152                                 + "previously installed version");
15153                         return;
15154                     }
15155                 } else {
15156                     try {
15157                         verifySignaturesLP(ps, pkg);
15158                     } catch (PackageManagerException e) {
15159                         res.setError(e.error, e.getMessage());
15160                         return;
15161                     }
15162                 }
15163
15164                 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15165                 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15166                     systemApp = (ps.pkg.applicationInfo.flags &
15167                             ApplicationInfo.FLAG_SYSTEM) != 0;
15168                 }
15169                 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15170             }
15171
15172             // Check whether the newly-scanned package wants to define an already-defined perm
15173             int N = pkg.permissions.size();
15174             for (int i = N-1; i >= 0; i--) {
15175                 PackageParser.Permission perm = pkg.permissions.get(i);
15176                 BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15177                 if (bp != null) {
15178                     // If the defining package is signed with our cert, it's okay.  This
15179                     // also includes the "updating the same package" case, of course.
15180                     // "updating same package" could also involve key-rotation.
15181                     final boolean sigsOk;
15182                     if (bp.sourcePackage.equals(pkg.packageName)
15183                             && (bp.packageSetting instanceof PackageSetting)
15184                             && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15185                                     scanFlags))) {
15186                         sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15187                     } else {
15188                         sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15189                                 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15190                     }
15191                     if (!sigsOk) {
15192                         // If the owning package is the system itself, we log but allow
15193                         // install to proceed; we fail the install on all other permission
15194                         // redefinitions.
15195                         if (!bp.sourcePackage.equals("android")) {
15196                             res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15197                                     + pkg.packageName + " attempting to redeclare permission "
15198                                     + perm.info.name + " already owned by " + bp.sourcePackage);
15199                             res.origPermission = perm.info.name;
15200                             res.origPackage = bp.sourcePackage;
15201                             return;
15202                         } else {
15203                             Slog.w(TAG, "Package " + pkg.packageName
15204                                     + " attempting to redeclare system permission "
15205                                     + perm.info.name + "; ignoring new declaration");
15206                             pkg.permissions.remove(i);
15207                         }
15208                     }
15209                 }
15210             }
15211         }
15212
15213         if (systemApp) {
15214             if (onExternal) {
15215                 // Abort update; system app can't be replaced with app on sdcard
15216                 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15217                         "Cannot install updates to system apps on sdcard");
15218                 return;
15219             } else if (ephemeral) {
15220                 // Abort update; system app can't be replaced with an ephemeral app
15221                 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15222                         "Cannot update a system app with an ephemeral app");
15223                 return;
15224             }
15225         }
15226
15227         if (args.move != null) {
15228             // We did an in-place move, so dex is ready to roll
15229             scanFlags |= SCAN_NO_DEX;
15230             scanFlags |= SCAN_MOVE;
15231
15232             synchronized (mPackages) {
15233                 final PackageSetting ps = mSettings.mPackages.get(pkgName);
15234                 if (ps == null) {
15235                     res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15236                             "Missing settings for moved package " + pkgName);
15237                 }
15238
15239                 // We moved the entire application as-is, so bring over the
15240                 // previously derived ABI information.
15241                 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15242                 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15243             }
15244
15245         } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15246             // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15247             scanFlags |= SCAN_NO_DEX;
15248
15249             try {
15250                 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15251                     args.abiOverride : pkg.cpuAbiOverride);
15252                 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15253                         true /* extract libs */);
15254             } catch (PackageManagerException pme) {
15255                 Slog.e(TAG, "Error deriving application ABI", pme);
15256                 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15257                 return;
15258             }
15259
15260             // Shared libraries for the package need to be updated.
15261             synchronized (mPackages) {
15262                 try {
15263                     updateSharedLibrariesLPw(pkg, null);
15264                 } catch (PackageManagerException e) {
15265                     Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15266                 }
15267             }
15268             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15269             // Do not run PackageDexOptimizer through the local performDexOpt
15270             // method because `pkg` may not be in `mPackages` yet.
15271             //
15272             // Also, don't fail application installs if the dexopt step fails.
15273             mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15274                     null /* instructionSets */, false /* checkProfiles */,
15275                     getCompilerFilterForReason(REASON_INSTALL),
15276                     getOrCreateCompilerPackageStats(pkg));
15277             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15278
15279             // Notify BackgroundDexOptService that the package has been changed.
15280             // If this is an update of a package which used to fail to compile,
15281             // BDOS will remove it from its blacklist.
15282             BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15283         }
15284
15285         if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15286             res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15287             return;
15288         }
15289
15290         startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15291
15292         try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15293                 "installPackageLI")) {
15294             if (replace) {
15295                 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15296                         installerPackageName, res);
15297             } else {
15298                 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15299                         args.user, installerPackageName, volumeUuid, res);
15300             }
15301         }
15302         synchronized (mPackages) {
15303             final PackageSetting ps = mSettings.mPackages.get(pkgName);
15304             if (ps != null) {
15305                 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15306             }
15307
15308             final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15309             for (int i = 0; i < childCount; i++) {
15310                 PackageParser.Package childPkg = pkg.childPackages.get(i);
15311                 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15312                 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15313                 if (childPs != null) {
15314                     childRes.newUsers = childPs.queryInstalledUsers(
15315                             sUserManager.getUserIds(), true);
15316                 }
15317             }
15318         }
15319     }
15320
15321     private void startIntentFilterVerifications(int userId, boolean replacing,
15322             PackageParser.Package pkg) {
15323         if (mIntentFilterVerifierComponent == null) {
15324             Slog.w(TAG, "No IntentFilter verification will not be done as "
15325                     + "there is no IntentFilterVerifier available!");
15326             return;
15327         }
15328
15329         final int verifierUid = getPackageUid(
15330                 mIntentFilterVerifierComponent.getPackageName(),
15331                 MATCH_DEBUG_TRIAGED_MISSING,
15332                 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15333
15334         Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15335         msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15336         mHandler.sendMessage(msg);
15337
15338         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15339         for (int i = 0; i < childCount; i++) {
15340             PackageParser.Package childPkg = pkg.childPackages.get(i);
15341             msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15342             msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15343             mHandler.sendMessage(msg);
15344         }
15345     }
15346
15347     private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15348             PackageParser.Package pkg) {
15349         int size = pkg.activities.size();
15350         if (size == 0) {
15351             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15352                     "No activity, so no need to verify any IntentFilter!");
15353             return;
15354         }
15355
15356         final boolean hasDomainURLs = hasDomainURLs(pkg);
15357         if (!hasDomainURLs) {
15358             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15359                     "No domain URLs, so no need to verify any IntentFilter!");
15360             return;
15361         }
15362
15363         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15364                 + " if any IntentFilter from the " + size
15365                 + " Activities needs verification ...");
15366
15367         int count = 0;
15368         final String packageName = pkg.packageName;
15369
15370         synchronized (mPackages) {
15371             // If this is a new install and we see that we've already run verification for this
15372             // package, we have nothing to do: it means the state was restored from backup.
15373             if (!replacing) {
15374                 IntentFilterVerificationInfo ivi =
15375                         mSettings.getIntentFilterVerificationLPr(packageName);
15376                 if (ivi != null) {
15377                     if (DEBUG_DOMAIN_VERIFICATION) {
15378                         Slog.i(TAG, "Package " + packageName+ " already verified: status="
15379                                 + ivi.getStatusString());
15380                     }
15381                     return;
15382                 }
15383             }
15384
15385             // If any filters need to be verified, then all need to be.
15386             boolean needToVerify = false;
15387             for (PackageParser.Activity a : pkg.activities) {
15388                 for (ActivityIntentInfo filter : a.intents) {
15389                     if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15390                         if (DEBUG_DOMAIN_VERIFICATION) {
15391                             Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15392                         }
15393                         needToVerify = true;
15394                         break;
15395                     }
15396                 }
15397             }
15398
15399             if (needToVerify) {
15400                 final int verificationId = mIntentFilterVerificationToken++;
15401                 for (PackageParser.Activity a : pkg.activities) {
15402                     for (ActivityIntentInfo filter : a.intents) {
15403                         if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15404                             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15405                                     "Verification needed for IntentFilter:" + filter.toString());
15406                             mIntentFilterVerifier.addOneIntentFilterVerification(
15407                                     verifierUid, userId, verificationId, filter, packageName);
15408                             count++;
15409                         }
15410                     }
15411                 }
15412             }
15413         }
15414
15415         if (count > 0) {
15416             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15417                     + " IntentFilter verification" + (count > 1 ? "s" : "")
15418                     +  " for userId:" + userId);
15419             mIntentFilterVerifier.startVerifications(userId);
15420         } else {
15421             if (DEBUG_DOMAIN_VERIFICATION) {
15422                 Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15423             }
15424         }
15425     }
15426
15427     private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15428         final ComponentName cn  = filter.activity.getComponentName();
15429         final String packageName = cn.getPackageName();
15430
15431         IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15432                 packageName);
15433         if (ivi == null) {
15434             return true;
15435         }
15436         int status = ivi.getStatus();
15437         switch (status) {
15438             case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15439             case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15440                 return true;
15441
15442             default:
15443                 // Nothing to do
15444                 return false;
15445         }
15446     }
15447
15448     private static boolean isMultiArch(ApplicationInfo info) {
15449         return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15450     }
15451
15452     private static boolean isExternal(PackageParser.Package pkg) {
15453         return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15454     }
15455
15456     private static boolean isExternal(PackageSetting ps) {
15457         return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15458     }
15459
15460     private static boolean isEphemeral(PackageParser.Package pkg) {
15461         return pkg.applicationInfo.isEphemeralApp();
15462     }
15463
15464     private static boolean isEphemeral(PackageSetting ps) {
15465         return ps.pkg != null && isEphemeral(ps.pkg);
15466     }
15467
15468     private static boolean isSystemApp(PackageParser.Package pkg) {
15469         return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15470     }
15471
15472     private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15473         return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15474     }
15475
15476     private static boolean hasDomainURLs(PackageParser.Package pkg) {
15477         return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15478     }
15479
15480     private static boolean isSystemApp(PackageSetting ps) {
15481         return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15482     }
15483
15484     private static boolean isUpdatedSystemApp(PackageSetting ps) {
15485         return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15486     }
15487
15488     private int packageFlagsToInstallFlags(PackageSetting ps) {
15489         int installFlags = 0;
15490         if (isEphemeral(ps)) {
15491             installFlags |= PackageManager.INSTALL_EPHEMERAL;
15492         }
15493         if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15494             // This existing package was an external ASEC install when we have
15495             // the external flag without a UUID
15496             installFlags |= PackageManager.INSTALL_EXTERNAL;
15497         }
15498         if (ps.isForwardLocked()) {
15499             installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15500         }
15501         return installFlags;
15502     }
15503
15504     private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15505         if (isExternal(pkg)) {
15506             if (TextUtils.isEmpty(pkg.volumeUuid)) {
15507                 return StorageManager.UUID_PRIMARY_PHYSICAL;
15508             } else {
15509                 return pkg.volumeUuid;
15510             }
15511         } else {
15512             return StorageManager.UUID_PRIVATE_INTERNAL;
15513         }
15514     }
15515
15516     private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15517         if (isExternal(pkg)) {
15518             if (TextUtils.isEmpty(pkg.volumeUuid)) {
15519                 return mSettings.getExternalVersion();
15520             } else {
15521                 return mSettings.findOrCreateVersion(pkg.volumeUuid);
15522             }
15523         } else {
15524             return mSettings.getInternalVersion();
15525         }
15526     }
15527
15528     private void deleteTempPackageFiles() {
15529         final FilenameFilter filter = new FilenameFilter() {
15530             public boolean accept(File dir, String name) {
15531                 return name.startsWith("vmdl") && name.endsWith(".tmp");
15532             }
15533         };
15534         for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15535             file.delete();
15536         }
15537     }
15538
15539     @Override
15540     public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15541             int flags) {
15542         deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15543                 flags);
15544     }
15545
15546     @Override
15547     public void deletePackage(final String packageName,
15548             final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15549         mContext.enforceCallingOrSelfPermission(
15550                 android.Manifest.permission.DELETE_PACKAGES, null);
15551         Preconditions.checkNotNull(packageName);
15552         Preconditions.checkNotNull(observer);
15553         final int uid = Binder.getCallingUid();
15554         if (!isOrphaned(packageName)
15555                 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) {
15556             try {
15557                 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
15558                 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
15559                 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
15560                 observer.onUserActionRequired(intent);
15561             } catch (RemoteException re) {
15562             }
15563             return;
15564         }
15565         final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15566         final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15567         if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15568             mContext.enforceCallingOrSelfPermission(
15569                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15570                     "deletePackage for user " + userId);
15571         }
15572
15573         if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15574             try {
15575                 observer.onPackageDeleted(packageName,
15576                         PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15577             } catch (RemoteException re) {
15578             }
15579             return;
15580         }
15581
15582         if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15583             try {
15584                 observer.onPackageDeleted(packageName,
15585                         PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15586             } catch (RemoteException re) {
15587             }
15588             return;
15589         }
15590
15591         if (DEBUG_REMOVE) {
15592             Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15593                     + " deleteAllUsers: " + deleteAllUsers );
15594         }
15595         // Queue up an async operation since the package deletion may take a little while.
15596         mHandler.post(new Runnable() {
15597             public void run() {
15598                 mHandler.removeCallbacks(this);
15599                 int returnCode;
15600                 if (!deleteAllUsers) {
15601                     returnCode = deletePackageX(packageName, userId, deleteFlags);
15602                 } else {
15603                     int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15604                     // If nobody is blocking uninstall, proceed with delete for all users
15605                     if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15606                         returnCode = deletePackageX(packageName, userId, deleteFlags);
15607                     } else {
15608                         // Otherwise uninstall individually for users with blockUninstalls=false
15609                         final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15610                         for (int userId : users) {
15611                             if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15612                                 returnCode = deletePackageX(packageName, userId, userFlags);
15613                                 if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15614                                     Slog.w(TAG, "Package delete failed for user " + userId
15615                                             + ", returnCode " + returnCode);
15616                                 }
15617                             }
15618                         }
15619                         // The app has only been marked uninstalled for certain users.
15620                         // We still need to report that delete was blocked
15621                         returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15622                     }
15623                 }
15624                 try {
15625                     observer.onPackageDeleted(packageName, returnCode, null);
15626                 } catch (RemoteException e) {
15627                     Log.i(TAG, "Observer no longer exists.");
15628                 } //end catch
15629             } //end run
15630         });
15631     }
15632
15633     private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
15634         if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
15635               || callingUid == Process.SYSTEM_UID) {
15636             return true;
15637         }
15638         final int callingUserId = UserHandle.getUserId(callingUid);
15639         // If the caller installed the pkgName, then allow it to silently uninstall.
15640         if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
15641             return true;
15642         }
15643
15644         // Allow package verifier to silently uninstall.
15645         if (mRequiredVerifierPackage != null &&
15646                 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
15647             return true;
15648         }
15649
15650         // Allow package uninstaller to silently uninstall.
15651         if (mRequiredUninstallerPackage != null &&
15652                 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
15653             return true;
15654         }
15655
15656         // Allow storage manager to silently uninstall.
15657         if (mStorageManagerPackage != null &&
15658                 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
15659             return true;
15660         }
15661         return false;
15662     }
15663
15664     private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15665         int[] result = EMPTY_INT_ARRAY;
15666         for (int userId : userIds) {
15667             if (getBlockUninstallForUser(packageName, userId)) {
15668                 result = ArrayUtils.appendInt(result, userId);
15669             }
15670         }
15671         return result;
15672     }
15673
15674     @Override
15675     public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15676         return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15677     }
15678
15679     private boolean isPackageDeviceAdmin(String packageName, int userId) {
15680         IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15681                 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15682         try {
15683             if (dpm != null) {
15684                 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15685                         /* callingUserOnly =*/ false);
15686                 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15687                         : deviceOwnerComponentName.getPackageName();
15688                 // Does the package contains the device owner?
15689                 // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15690                 // this check is probably not needed, since DO should be registered as a device
15691                 // admin on some user too. (Original bug for this: b/17657954)
15692                 if (packageName.equals(deviceOwnerPackageName)) {
15693                     return true;
15694                 }
15695                 // Does it contain a device admin for any user?
15696                 int[] users;
15697                 if (userId == UserHandle.USER_ALL) {
15698                     users = sUserManager.getUserIds();
15699                 } else {
15700                     users = new int[]{userId};
15701                 }
15702                 for (int i = 0; i < users.length; ++i) {
15703                     if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15704                         return true;
15705                     }
15706                 }
15707             }
15708         } catch (RemoteException e) {
15709         }
15710         return false;
15711     }
15712
15713     private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15714         return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15715     }
15716
15717     /**
15718      *  This method is an internal method that could be get invoked either
15719      *  to delete an installed package or to clean up a failed installation.
15720      *  After deleting an installed package, a broadcast is sent to notify any
15721      *  listeners that the package has been removed. For cleaning up a failed
15722      *  installation, the broadcast is not necessary since the package's
15723      *  installation wouldn't have sent the initial broadcast either
15724      *  The key steps in deleting a package are
15725      *  deleting the package information in internal structures like mPackages,
15726      *  deleting the packages base directories through installd
15727      *  updating mSettings to reflect current status
15728      *  persisting settings for later use
15729      *  sending a broadcast if necessary
15730      */
15731     private int deletePackageX(String packageName, int userId, int deleteFlags) {
15732         final PackageRemovedInfo info = new PackageRemovedInfo();
15733         final boolean res;
15734
15735         final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15736                 ? UserHandle.USER_ALL : userId;
15737
15738         if (isPackageDeviceAdmin(packageName, removeUser)) {
15739             Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15740             return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15741         }
15742
15743         PackageSetting uninstalledPs = null;
15744
15745         // for the uninstall-updates case and restricted profiles, remember the per-
15746         // user handle installed state
15747         int[] allUsers;
15748         synchronized (mPackages) {
15749             uninstalledPs = mSettings.mPackages.get(packageName);
15750             if (uninstalledPs == null) {
15751                 Slog.w(TAG, "Not removing non-existent package " + packageName);
15752                 return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15753             }
15754             allUsers = sUserManager.getUserIds();
15755             info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15756         }
15757
15758         final int freezeUser;
15759         if (isUpdatedSystemApp(uninstalledPs)
15760                 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15761             // We're downgrading a system app, which will apply to all users, so
15762             // freeze them all during the downgrade
15763             freezeUser = UserHandle.USER_ALL;
15764         } else {
15765             freezeUser = removeUser;
15766         }
15767
15768         synchronized (mInstallLock) {
15769             if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15770             try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15771                     deleteFlags, "deletePackageX")) {
15772                 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15773                         deleteFlags | REMOVE_CHATTY, info, true, null);
15774             }
15775             synchronized (mPackages) {
15776                 if (res) {
15777                     mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15778                 }
15779             }
15780         }
15781
15782         if (res) {
15783             final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15784             info.sendPackageRemovedBroadcasts(killApp);
15785             info.sendSystemPackageUpdatedBroadcasts();
15786             info.sendSystemPackageAppearedBroadcasts();
15787         }
15788         // Force a gc here.
15789         Runtime.getRuntime().gc();
15790         // Delete the resources here after sending the broadcast to let
15791         // other processes clean up before deleting resources.
15792         if (info.args != null) {
15793             synchronized (mInstallLock) {
15794                 info.args.doPostDeleteLI(true);
15795             }
15796         }
15797
15798         return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15799     }
15800
15801     class PackageRemovedInfo {
15802         String removedPackage;
15803         int uid = -1;
15804         int removedAppId = -1;
15805         int[] origUsers;
15806         int[] removedUsers = null;
15807         boolean isRemovedPackageSystemUpdate = false;
15808         boolean isUpdate;
15809         boolean dataRemoved;
15810         boolean removedForAllUsers;
15811         // Clean up resources deleted packages.
15812         InstallArgs args = null;
15813         ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15814         ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15815
15816         void sendPackageRemovedBroadcasts(boolean killApp) {
15817             sendPackageRemovedBroadcastInternal(killApp);
15818             final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15819             for (int i = 0; i < childCount; i++) {
15820                 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15821                 childInfo.sendPackageRemovedBroadcastInternal(killApp);
15822             }
15823         }
15824
15825         void sendSystemPackageUpdatedBroadcasts() {
15826             if (isRemovedPackageSystemUpdate) {
15827                 sendSystemPackageUpdatedBroadcastsInternal();
15828                 final int childCount = (removedChildPackages != null)
15829                         ? removedChildPackages.size() : 0;
15830                 for (int i = 0; i < childCount; i++) {
15831                     PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15832                     if (childInfo.isRemovedPackageSystemUpdate) {
15833                         childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15834                     }
15835                 }
15836             }
15837         }
15838
15839         void sendSystemPackageAppearedBroadcasts() {
15840             final int packageCount = (appearedChildPackages != null)
15841                     ? appearedChildPackages.size() : 0;
15842             for (int i = 0; i < packageCount; i++) {
15843                 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15844                 for (int userId : installedInfo.newUsers) {
15845                     sendPackageAddedForUser(installedInfo.name, true,
15846                             UserHandle.getAppId(installedInfo.uid), userId);
15847                 }
15848             }
15849         }
15850
15851         private void sendSystemPackageUpdatedBroadcastsInternal() {
15852             Bundle extras = new Bundle(2);
15853             extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15854             extras.putBoolean(Intent.EXTRA_REPLACING, true);
15855             sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15856                     extras, 0, null, null, null);
15857             sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15858                     extras, 0, null, null, null);
15859             sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15860                     null, 0, removedPackage, null, null);
15861         }
15862
15863         private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15864             Bundle extras = new Bundle(2);
15865             extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15866             extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15867             extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15868             if (isUpdate || isRemovedPackageSystemUpdate) {
15869                 extras.putBoolean(Intent.EXTRA_REPLACING, true);
15870             }
15871             extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15872             if (removedPackage != null) {
15873                 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15874                         extras, 0, null, null, removedUsers);
15875                 if (dataRemoved && !isRemovedPackageSystemUpdate) {
15876                     sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15877                             removedPackage, extras, 0, null, null, removedUsers);
15878                 }
15879             }
15880             if (removedAppId >= 0) {
15881                 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15882                         removedUsers);
15883             }
15884         }
15885     }
15886
15887     /*
15888      * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15889      * flag is not set, the data directory is removed as well.
15890      * make sure this flag is set for partially installed apps. If not its meaningless to
15891      * delete a partially installed application.
15892      */
15893     private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15894             PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15895         String packageName = ps.name;
15896         if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15897         // Retrieve object to delete permissions for shared user later on
15898         final PackageParser.Package deletedPkg;
15899         final PackageSetting deletedPs;
15900         // reader
15901         synchronized (mPackages) {
15902             deletedPkg = mPackages.get(packageName);
15903             deletedPs = mSettings.mPackages.get(packageName);
15904             if (outInfo != null) {
15905                 outInfo.removedPackage = packageName;
15906                 outInfo.removedUsers = deletedPs != null
15907                         ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15908                         : null;
15909             }
15910         }
15911
15912         removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15913
15914         if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15915             final PackageParser.Package resolvedPkg;
15916             if (deletedPkg != null) {
15917                 resolvedPkg = deletedPkg;
15918             } else {
15919                 // We don't have a parsed package when it lives on an ejected
15920                 // adopted storage device, so fake something together
15921                 resolvedPkg = new PackageParser.Package(ps.name);
15922                 resolvedPkg.setVolumeUuid(ps.volumeUuid);
15923             }
15924             destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15925                     StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15926             destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15927             if (outInfo != null) {
15928                 outInfo.dataRemoved = true;
15929             }
15930             schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15931         }
15932
15933         // writer
15934         synchronized (mPackages) {
15935             if (deletedPs != null) {
15936                 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15937                     clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15938                     clearDefaultBrowserIfNeeded(packageName);
15939                     if (outInfo != null) {
15940                         mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15941                         outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15942                     }
15943                     updatePermissionsLPw(deletedPs.name, null, 0);
15944                     if (deletedPs.sharedUser != null) {
15945                         // Remove permissions associated with package. Since runtime
15946                         // permissions are per user we have to kill the removed package
15947                         // or packages running under the shared user of the removed
15948                         // package if revoking the permissions requested only by the removed
15949                         // package is successful and this causes a change in gids.
15950                         for (int userId : UserManagerService.getInstance().getUserIds()) {
15951                             final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15952                                     userId);
15953                             if (userIdToKill == UserHandle.USER_ALL
15954                                     || userIdToKill >= UserHandle.USER_SYSTEM) {
15955                                 // If gids changed for this user, kill all affected packages.
15956                                 mHandler.post(new Runnable() {
15957                                     @Override
15958                                     public void run() {
15959                                         // This has to happen with no lock held.
15960                                         killApplication(deletedPs.name, deletedPs.appId,
15961                                                 KILL_APP_REASON_GIDS_CHANGED);
15962                                     }
15963                                 });
15964                                 break;
15965                             }
15966                         }
15967                     }
15968                     clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15969                 }
15970                 // make sure to preserve per-user disabled state if this removal was just
15971                 // a downgrade of a system app to the factory package
15972                 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15973                     if (DEBUG_REMOVE) {
15974                         Slog.d(TAG, "Propagating install state across downgrade");
15975                     }
15976                     for (int userId : allUserHandles) {
15977                         final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15978                         if (DEBUG_REMOVE) {
15979                             Slog.d(TAG, "    user " + userId + " => " + installed);
15980                         }
15981                         ps.setInstalled(installed, userId);
15982                     }
15983                 }
15984             }
15985             // can downgrade to reader
15986             if (writeSettings) {
15987                 // Save settings now
15988                 mSettings.writeLPr();
15989             }
15990         }
15991         if (outInfo != null) {
15992             // A user ID was deleted here. Go through all users and remove it
15993             // from KeyStore.
15994             removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15995         }
15996     }
15997
15998     static boolean locationIsPrivileged(File path) {
15999         try {
16000             final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
16001                     .getCanonicalPath();
16002             return path.getCanonicalPath().startsWith(privilegedAppDir);
16003         } catch (IOException e) {
16004             Slog.e(TAG, "Unable to access code path " + path);
16005         }
16006         return false;
16007     }
16008
16009     /*
16010      * Tries to delete system package.
16011      */
16012     private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
16013             PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
16014             boolean writeSettings) {
16015         if (deletedPs.parentPackageName != null) {
16016             Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
16017             return false;
16018         }
16019
16020         final boolean applyUserRestrictions
16021                 = (allUserHandles != null) && (outInfo.origUsers != null);
16022         final PackageSetting disabledPs;
16023         // Confirm if the system package has been updated
16024         // An updated system app can be deleted. This will also have to restore
16025         // the system pkg from system partition
16026         // reader
16027         synchronized (mPackages) {
16028             disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
16029         }
16030
16031         if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
16032                 + " disabledPs=" + disabledPs);
16033
16034         if (disabledPs == null) {
16035             Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
16036             return false;
16037         } else if (DEBUG_REMOVE) {
16038             Slog.d(TAG, "Deleting system pkg from data partition");
16039         }
16040
16041         if (DEBUG_REMOVE) {
16042             if (applyUserRestrictions) {
16043                 Slog.d(TAG, "Remembering install states:");
16044                 for (int userId : allUserHandles) {
16045                     final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
16046                     Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
16047                 }
16048             }
16049         }
16050
16051         // Delete the updated package
16052         outInfo.isRemovedPackageSystemUpdate = true;
16053         if (outInfo.removedChildPackages != null) {
16054             final int childCount = (deletedPs.childPackageNames != null)
16055                     ? deletedPs.childPackageNames.size() : 0;
16056             for (int i = 0; i < childCount; i++) {
16057                 String childPackageName = deletedPs.childPackageNames.get(i);
16058                 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
16059                         .contains(childPackageName)) {
16060                     PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16061                             childPackageName);
16062                     if (childInfo != null) {
16063                         childInfo.isRemovedPackageSystemUpdate = true;
16064                     }
16065                 }
16066             }
16067         }
16068
16069         if (disabledPs.versionCode < deletedPs.versionCode) {
16070             // Delete data for downgrades
16071             flags &= ~PackageManager.DELETE_KEEP_DATA;
16072         } else {
16073             // Preserve data by setting flag
16074             flags |= PackageManager.DELETE_KEEP_DATA;
16075         }
16076
16077         boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
16078                 outInfo, writeSettings, disabledPs.pkg);
16079         if (!ret) {
16080             return false;
16081         }
16082
16083         // writer
16084         synchronized (mPackages) {
16085             // Reinstate the old system package
16086             enableSystemPackageLPw(disabledPs.pkg);
16087             // Remove any native libraries from the upgraded package.
16088             removeNativeBinariesLI(deletedPs);
16089         }
16090
16091         // Install the system package
16092         if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
16093         int parseFlags = mDefParseFlags
16094                 | PackageParser.PARSE_MUST_BE_APK
16095                 | PackageParser.PARSE_IS_SYSTEM
16096                 | PackageParser.PARSE_IS_SYSTEM_DIR;
16097         if (locationIsPrivileged(disabledPs.codePath)) {
16098             parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
16099         }
16100
16101         final PackageParser.Package newPkg;
16102         try {
16103             newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
16104         } catch (PackageManagerException e) {
16105             Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
16106                     + e.getMessage());
16107             return false;
16108         }
16109         try {
16110             // update shared libraries for the newly re-installed system package
16111             updateSharedLibrariesLPw(newPkg, null);
16112         } catch (PackageManagerException e) {
16113             Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16114         }
16115
16116         prepareAppDataAfterInstallLIF(newPkg);
16117
16118         // writer
16119         synchronized (mPackages) {
16120             PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
16121
16122             // Propagate the permissions state as we do not want to drop on the floor
16123             // runtime permissions. The update permissions method below will take
16124             // care of removing obsolete permissions and grant install permissions.
16125             ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
16126             updatePermissionsLPw(newPkg.packageName, newPkg,
16127                     UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
16128
16129             if (applyUserRestrictions) {
16130                 if (DEBUG_REMOVE) {
16131                     Slog.d(TAG, "Propagating install state across reinstall");
16132                 }
16133                 for (int userId : allUserHandles) {
16134                     final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
16135                     if (DEBUG_REMOVE) {
16136                         Slog.d(TAG, "    user " + userId + " => " + installed);
16137                     }
16138                     ps.setInstalled(installed, userId);
16139
16140                     mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16141                 }
16142                 // Regardless of writeSettings we need to ensure that this restriction
16143                 // state propagation is persisted
16144                 mSettings.writeAllUsersPackageRestrictionsLPr();
16145             }
16146             // can downgrade to reader here
16147             if (writeSettings) {
16148                 mSettings.writeLPr();
16149             }
16150         }
16151         return true;
16152     }
16153
16154     private boolean deleteInstalledPackageLIF(PackageSetting ps,
16155             boolean deleteCodeAndResources, int flags, int[] allUserHandles,
16156             PackageRemovedInfo outInfo, boolean writeSettings,
16157             PackageParser.Package replacingPackage) {
16158         synchronized (mPackages) {
16159             if (outInfo != null) {
16160                 outInfo.uid = ps.appId;
16161             }
16162
16163             if (outInfo != null && outInfo.removedChildPackages != null) {
16164                 final int childCount = (ps.childPackageNames != null)
16165                         ? ps.childPackageNames.size() : 0;
16166                 for (int i = 0; i < childCount; i++) {
16167                     String childPackageName = ps.childPackageNames.get(i);
16168                     PackageSetting childPs = mSettings.mPackages.get(childPackageName);
16169                     if (childPs == null) {
16170                         return false;
16171                     }
16172                     PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16173                             childPackageName);
16174                     if (childInfo != null) {
16175                         childInfo.uid = childPs.appId;
16176                     }
16177                 }
16178             }
16179         }
16180
16181         // Delete package data from internal structures and also remove data if flag is set
16182         removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16183
16184         // Delete the child packages data
16185         final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16186         for (int i = 0; i < childCount; i++) {
16187             PackageSetting childPs;
16188             synchronized (mPackages) {
16189                 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16190             }
16191             if (childPs != null) {
16192                 PackageRemovedInfo childOutInfo = (outInfo != null
16193                         && outInfo.removedChildPackages != null)
16194                         ? outInfo.removedChildPackages.get(childPs.name) : null;
16195                 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16196                         && (replacingPackage != null
16197                         && !replacingPackage.hasChildPackage(childPs.name))
16198                         ? flags & ~DELETE_KEEP_DATA : flags;
16199                 removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16200                         deleteFlags, writeSettings);
16201             }
16202         }
16203
16204         // Delete application code and resources only for parent packages
16205         if (ps.parentPackageName == null) {
16206             if (deleteCodeAndResources && (outInfo != null)) {
16207                 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16208                         ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16209                 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16210             }
16211         }
16212
16213         return true;
16214     }
16215
16216     @Override
16217     public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16218             int userId) {
16219         mContext.enforceCallingOrSelfPermission(
16220                 android.Manifest.permission.DELETE_PACKAGES, null);
16221         synchronized (mPackages) {
16222             PackageSetting ps = mSettings.mPackages.get(packageName);
16223             if (ps == null) {
16224                 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16225                 return false;
16226             }
16227             if (!ps.getInstalled(userId)) {
16228                 // Can't block uninstall for an app that is not installed or enabled.
16229                 Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16230                 return false;
16231             }
16232             ps.setBlockUninstall(blockUninstall, userId);
16233             mSettings.writePackageRestrictionsLPr(userId);
16234         }
16235         return true;
16236     }
16237
16238     @Override
16239     public boolean getBlockUninstallForUser(String packageName, int userId) {
16240         synchronized (mPackages) {
16241             PackageSetting ps = mSettings.mPackages.get(packageName);
16242             if (ps == null) {
16243                 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16244                 return false;
16245             }
16246             return ps.getBlockUninstall(userId);
16247         }
16248     }
16249
16250     @Override
16251     public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16252         int callingUid = Binder.getCallingUid();
16253         if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16254             throw new SecurityException(
16255                     "setRequiredForSystemUser can only be run by the system or root");
16256         }
16257         synchronized (mPackages) {
16258             PackageSetting ps = mSettings.mPackages.get(packageName);
16259             if (ps == null) {
16260                 Log.w(TAG, "Package doesn't exist: " + packageName);
16261                 return false;
16262             }
16263             if (systemUserApp) {
16264                 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16265             } else {
16266                 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16267             }
16268             mSettings.writeLPr();
16269         }
16270         return true;
16271     }
16272
16273     /*
16274      * This method handles package deletion in general
16275      */
16276     private boolean deletePackageLIF(String packageName, UserHandle user,
16277             boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16278             PackageRemovedInfo outInfo, boolean writeSettings,
16279             PackageParser.Package replacingPackage) {
16280         if (packageName == null) {
16281             Slog.w(TAG, "Attempt to delete null packageName.");
16282             return false;
16283         }
16284
16285         if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16286
16287         PackageSetting ps;
16288
16289         synchronized (mPackages) {
16290             ps = mSettings.mPackages.get(packageName);
16291             if (ps == null) {
16292                 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16293                 return false;
16294             }
16295
16296             if (ps.parentPackageName != null && (!isSystemApp(ps)
16297                     || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16298                 if (DEBUG_REMOVE) {
16299                     Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16300                             + ((user == null) ? UserHandle.USER_ALL : user));
16301                 }
16302                 final int removedUserId = (user != null) ? user.getIdentifier()
16303                         : UserHandle.USER_ALL;
16304                 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16305                     return false;
16306                 }
16307                 markPackageUninstalledForUserLPw(ps, user);
16308                 scheduleWritePackageRestrictionsLocked(user);
16309                 return true;
16310             }
16311         }
16312
16313         if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16314                 && user.getIdentifier() != UserHandle.USER_ALL)) {
16315             // The caller is asking that the package only be deleted for a single
16316             // user.  To do this, we just mark its uninstalled state and delete
16317             // its data. If this is a system app, we only allow this to happen if
16318             // they have set the special DELETE_SYSTEM_APP which requests different
16319             // semantics than normal for uninstalling system apps.
16320             markPackageUninstalledForUserLPw(ps, user);
16321
16322             if (!isSystemApp(ps)) {
16323                 // Do not uninstall the APK if an app should be cached
16324                 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16325                 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16326                     // Other user still have this package installed, so all
16327                     // we need to do is clear this user's data and save that
16328                     // it is uninstalled.
16329                     if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16330                     if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16331                         return false;
16332                     }
16333                     scheduleWritePackageRestrictionsLocked(user);
16334                     return true;
16335                 } else {
16336                     // We need to set it back to 'installed' so the uninstall
16337                     // broadcasts will be sent correctly.
16338                     if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16339                     ps.setInstalled(true, user.getIdentifier());
16340                 }
16341             } else {
16342                 // This is a system app, so we assume that the
16343                 // other users still have this package installed, so all
16344                 // we need to do is clear this user's data and save that
16345                 // it is uninstalled.
16346                 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16347                 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16348                     return false;
16349                 }
16350                 scheduleWritePackageRestrictionsLocked(user);
16351                 return true;
16352             }
16353         }
16354
16355         // If we are deleting a composite package for all users, keep track
16356         // of result for each child.
16357         if (ps.childPackageNames != null && outInfo != null) {
16358             synchronized (mPackages) {
16359                 final int childCount = ps.childPackageNames.size();
16360                 outInfo.removedChildPackages = new ArrayMap<>(childCount);
16361                 for (int i = 0; i < childCount; i++) {
16362                     String childPackageName = ps.childPackageNames.get(i);
16363                     PackageRemovedInfo childInfo = new PackageRemovedInfo();
16364                     childInfo.removedPackage = childPackageName;
16365                     outInfo.removedChildPackages.put(childPackageName, childInfo);
16366                     PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16367                     if (childPs != null) {
16368                         childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16369                     }
16370                 }
16371             }
16372         }
16373
16374         boolean ret = false;
16375         if (isSystemApp(ps)) {
16376             if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16377             // When an updated system application is deleted we delete the existing resources
16378             // as well and fall back to existing code in system partition
16379             ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16380         } else {
16381             if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16382             ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16383                     outInfo, writeSettings, replacingPackage);
16384         }
16385
16386         // Take a note whether we deleted the package for all users
16387         if (outInfo != null) {
16388             outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16389             if (outInfo.removedChildPackages != null) {
16390                 synchronized (mPackages) {
16391                     final int childCount = outInfo.removedChildPackages.size();
16392                     for (int i = 0; i < childCount; i++) {
16393                         PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16394                         if (childInfo != null) {
16395                             childInfo.removedForAllUsers = mPackages.get(
16396                                     childInfo.removedPackage) == null;
16397                         }
16398                     }
16399                 }
16400             }
16401             // If we uninstalled an update to a system app there may be some
16402             // child packages that appeared as they are declared in the system
16403             // app but were not declared in the update.
16404             if (isSystemApp(ps)) {
16405                 synchronized (mPackages) {
16406                     PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16407                     final int childCount = (updatedPs.childPackageNames != null)
16408                             ? updatedPs.childPackageNames.size() : 0;
16409                     for (int i = 0; i < childCount; i++) {
16410                         String childPackageName = updatedPs.childPackageNames.get(i);
16411                         if (outInfo.removedChildPackages == null
16412                                 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16413                             PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16414                             if (childPs == null) {
16415                                 continue;
16416                             }
16417                             PackageInstalledInfo installRes = new PackageInstalledInfo();
16418                             installRes.name = childPackageName;
16419                             installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16420                             installRes.pkg = mPackages.get(childPackageName);
16421                             installRes.uid = childPs.pkg.applicationInfo.uid;
16422                             if (outInfo.appearedChildPackages == null) {
16423                                 outInfo.appearedChildPackages = new ArrayMap<>();
16424                             }
16425                             outInfo.appearedChildPackages.put(childPackageName, installRes);
16426                         }
16427                     }
16428                 }
16429             }
16430         }
16431
16432         return ret;
16433     }
16434
16435     private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16436         final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16437                 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16438         for (int nextUserId : userIds) {
16439             if (DEBUG_REMOVE) {
16440                 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16441             }
16442             ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16443                     false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16444                     false /*hidden*/, false /*suspended*/, null, null, null,
16445                     false /*blockUninstall*/,
16446                     ps.readUserState(nextUserId).domainVerificationStatus, 0);
16447         }
16448     }
16449
16450     private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16451             PackageRemovedInfo outInfo) {
16452         final PackageParser.Package pkg;
16453         synchronized (mPackages) {
16454             pkg = mPackages.get(ps.name);
16455         }
16456
16457         final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16458                 : new int[] {userId};
16459         for (int nextUserId : userIds) {
16460             if (DEBUG_REMOVE) {
16461                 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16462                         + nextUserId);
16463             }
16464
16465             destroyAppDataLIF(pkg, userId,
16466                     StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16467             destroyAppProfilesLIF(pkg, userId);
16468             removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16469             schedulePackageCleaning(ps.name, nextUserId, false);
16470             synchronized (mPackages) {
16471                 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16472                     scheduleWritePackageRestrictionsLocked(nextUserId);
16473                 }
16474                 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16475             }
16476         }
16477
16478         if (outInfo != null) {
16479             outInfo.removedPackage = ps.name;
16480             outInfo.removedAppId = ps.appId;
16481             outInfo.removedUsers = userIds;
16482         }
16483
16484         return true;
16485     }
16486
16487     private final class ClearStorageConnection implements ServiceConnection {
16488         IMediaContainerService mContainerService;
16489
16490         @Override
16491         public void onServiceConnected(ComponentName name, IBinder service) {
16492             synchronized (this) {
16493                 mContainerService = IMediaContainerService.Stub.asInterface(service);
16494                 notifyAll();
16495             }
16496         }
16497
16498         @Override
16499         public void onServiceDisconnected(ComponentName name) {
16500         }
16501     }
16502
16503     private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16504         if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16505
16506         final boolean mounted;
16507         if (Environment.isExternalStorageEmulated()) {
16508             mounted = true;
16509         } else {
16510             final String status = Environment.getExternalStorageState();
16511
16512             mounted = status.equals(Environment.MEDIA_MOUNTED)
16513                     || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16514         }
16515
16516         if (!mounted) {
16517             return;
16518         }
16519
16520         final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16521         int[] users;
16522         if (userId == UserHandle.USER_ALL) {
16523             users = sUserManager.getUserIds();
16524         } else {
16525             users = new int[] { userId };
16526         }
16527         final ClearStorageConnection conn = new ClearStorageConnection();
16528         if (mContext.bindServiceAsUser(
16529                 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16530             try {
16531                 for (int curUser : users) {
16532                     long timeout = SystemClock.uptimeMillis() + 5000;
16533                     synchronized (conn) {
16534                         long now;
16535                         while (conn.mContainerService == null &&
16536                                 (now = SystemClock.uptimeMillis()) < timeout) {
16537                             try {
16538                                 conn.wait(timeout - now);
16539                             } catch (InterruptedException e) {
16540                             }
16541                         }
16542                     }
16543                     if (conn.mContainerService == null) {
16544                         return;
16545                     }
16546
16547                     final UserEnvironment userEnv = new UserEnvironment(curUser);
16548                     clearDirectory(conn.mContainerService,
16549                             userEnv.buildExternalStorageAppCacheDirs(packageName));
16550                     if (allData) {
16551                         clearDirectory(conn.mContainerService,
16552                                 userEnv.buildExternalStorageAppDataDirs(packageName));
16553                         clearDirectory(conn.mContainerService,
16554                                 userEnv.buildExternalStorageAppMediaDirs(packageName));
16555                     }
16556                 }
16557             } finally {
16558                 mContext.unbindService(conn);
16559             }
16560         }
16561     }
16562
16563     @Override
16564     public void clearApplicationProfileData(String packageName) {
16565         enforceSystemOrRoot("Only the system can clear all profile data");
16566
16567         final PackageParser.Package pkg;
16568         synchronized (mPackages) {
16569             pkg = mPackages.get(packageName);
16570         }
16571
16572         try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16573             synchronized (mInstallLock) {
16574                 clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16575                 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16576                         true /* removeBaseMarker */);
16577             }
16578         }
16579     }
16580
16581     @Override
16582     public void clearApplicationUserData(final String packageName,
16583             final IPackageDataObserver observer, final int userId) {
16584         mContext.enforceCallingOrSelfPermission(
16585                 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16586
16587         enforceCrossUserPermission(Binder.getCallingUid(), userId,
16588                 true /* requireFullPermission */, false /* checkShell */, "clear application data");
16589
16590         if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16591             throw new SecurityException("Cannot clear data for a protected package: "
16592                     + packageName);
16593         }
16594         // Queue up an async operation since the package deletion may take a little while.
16595         mHandler.post(new Runnable() {
16596             public void run() {
16597                 mHandler.removeCallbacks(this);
16598                 final boolean succeeded;
16599                 try (PackageFreezer freezer = freezePackage(packageName,
16600                         "clearApplicationUserData")) {
16601                     synchronized (mInstallLock) {
16602                         succeeded = clearApplicationUserDataLIF(packageName, userId);
16603                     }
16604                     clearExternalStorageDataSync(packageName, userId, true);
16605                 }
16606                 if (succeeded) {
16607                     // invoke DeviceStorageMonitor's update method to clear any notifications
16608                     DeviceStorageMonitorInternal dsm = LocalServices
16609                             .getService(DeviceStorageMonitorInternal.class);
16610                     if (dsm != null) {
16611                         dsm.checkMemory();
16612                     }
16613                 }
16614                 if(observer != null) {
16615                     try {
16616                         observer.onRemoveCompleted(packageName, succeeded);
16617                     } catch (RemoteException e) {
16618                         Log.i(TAG, "Observer no longer exists.");
16619                     }
16620                 } //end if observer
16621             } //end run
16622         });
16623     }
16624
16625     private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16626         if (packageName == null) {
16627             Slog.w(TAG, "Attempt to delete null packageName.");
16628             return false;
16629         }
16630
16631         // Try finding details about the requested package
16632         PackageParser.Package pkg;
16633         synchronized (mPackages) {
16634             pkg = mPackages.get(packageName);
16635             if (pkg == null) {
16636                 final PackageSetting ps = mSettings.mPackages.get(packageName);
16637                 if (ps != null) {
16638                     pkg = ps.pkg;
16639                 }
16640             }
16641
16642             if (pkg == null) {
16643                 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16644                 return false;
16645             }
16646
16647             PackageSetting ps = (PackageSetting) pkg.mExtras;
16648             resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16649         }
16650
16651         clearAppDataLIF(pkg, userId,
16652                 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16653
16654         final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16655         removeKeystoreDataIfNeeded(userId, appId);
16656
16657         UserManagerInternal umInternal = getUserManagerInternal();
16658         final int flags;
16659         if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16660             flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16661         } else if (umInternal.isUserRunning(userId)) {
16662             flags = StorageManager.FLAG_STORAGE_DE;
16663         } else {
16664             flags = 0;
16665         }
16666         prepareAppDataContentsLIF(pkg, userId, flags);
16667
16668         return true;
16669     }
16670
16671     /**
16672      * Reverts user permission state changes (permissions and flags) in
16673      * all packages for a given user.
16674      *
16675      * @param userId The device user for which to do a reset.
16676      */
16677     private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16678         final int packageCount = mPackages.size();
16679         for (int i = 0; i < packageCount; i++) {
16680             PackageParser.Package pkg = mPackages.valueAt(i);
16681             PackageSetting ps = (PackageSetting) pkg.mExtras;
16682             resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16683         }
16684     }
16685
16686     private void resetNetworkPolicies(int userId) {
16687         LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16688     }
16689
16690     /**
16691      * Reverts user permission state changes (permissions and flags).
16692      *
16693      * @param ps The package for which to reset.
16694      * @param userId The device user for which to do a reset.
16695      */
16696     private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16697             final PackageSetting ps, final int userId) {
16698         if (ps.pkg == null) {
16699             return;
16700         }
16701
16702         // These are flags that can change base on user actions.
16703         final int userSettableMask = FLAG_PERMISSION_USER_SET
16704                 | FLAG_PERMISSION_USER_FIXED
16705                 | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16706                 | FLAG_PERMISSION_REVIEW_REQUIRED;
16707
16708         final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16709                 | FLAG_PERMISSION_POLICY_FIXED;
16710
16711         boolean writeInstallPermissions = false;
16712         boolean writeRuntimePermissions = false;
16713
16714         final int permissionCount = ps.pkg.requestedPermissions.size();
16715         for (int i = 0; i < permissionCount; i++) {
16716             String permission = ps.pkg.requestedPermissions.get(i);
16717
16718             BasePermission bp = mSettings.mPermissions.get(permission);
16719             if (bp == null) {
16720                 continue;
16721             }
16722
16723             // If shared user we just reset the state to which only this app contributed.
16724             if (ps.sharedUser != null) {
16725                 boolean used = false;
16726                 final int packageCount = ps.sharedUser.packages.size();
16727                 for (int j = 0; j < packageCount; j++) {
16728                     PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16729                     if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16730                             && pkg.pkg.requestedPermissions.contains(permission)) {
16731                         used = true;
16732                         break;
16733                     }
16734                 }
16735                 if (used) {
16736                     continue;
16737                 }
16738             }
16739
16740             PermissionsState permissionsState = ps.getPermissionsState();
16741
16742             final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16743
16744             // Always clear the user settable flags.
16745             final boolean hasInstallState = permissionsState.getInstallPermissionState(
16746                     bp.name) != null;
16747             // If permission review is enabled and this is a legacy app, mark the
16748             // permission as requiring a review as this is the initial state.
16749             int flags = 0;
16750             if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED)
16751                     && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16752                 flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16753             }
16754             if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16755                 if (hasInstallState) {
16756                     writeInstallPermissions = true;
16757                 } else {
16758                     writeRuntimePermissions = true;
16759                 }
16760             }
16761
16762             // Below is only runtime permission handling.
16763             if (!bp.isRuntime()) {
16764                 continue;
16765             }
16766
16767             // Never clobber system or policy.
16768             if ((oldFlags & policyOrSystemFlags) != 0) {
16769                 continue;
16770             }
16771
16772             // If this permission was granted by default, make sure it is.
16773             if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16774                 if (permissionsState.grantRuntimePermission(bp, userId)
16775                         != PERMISSION_OPERATION_FAILURE) {
16776                     writeRuntimePermissions = true;
16777                 }
16778             // If permission review is enabled the permissions for a legacy apps
16779             // are represented as constantly granted runtime ones, so don't revoke.
16780             } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16781                 // Otherwise, reset the permission.
16782                 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16783                 switch (revokeResult) {
16784                     case PERMISSION_OPERATION_SUCCESS:
16785                     case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16786                         writeRuntimePermissions = true;
16787                         final int appId = ps.appId;
16788                         mHandler.post(new Runnable() {
16789                             @Override
16790                             public void run() {
16791                                 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16792                             }
16793                         });
16794                     } break;
16795                 }
16796             }
16797         }
16798
16799         // Synchronously write as we are taking permissions away.
16800         if (writeRuntimePermissions) {
16801             mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16802         }
16803
16804         // Synchronously write as we are taking permissions away.
16805         if (writeInstallPermissions) {
16806             mSettings.writeLPr();
16807         }
16808     }
16809
16810     /**
16811      * Remove entries from the keystore daemon. Will only remove it if the
16812      * {@code appId} is valid.
16813      */
16814     private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16815         if (appId < 0) {
16816             return;
16817         }
16818
16819         final KeyStore keyStore = KeyStore.getInstance();
16820         if (keyStore != null) {
16821             if (userId == UserHandle.USER_ALL) {
16822                 for (final int individual : sUserManager.getUserIds()) {
16823                     keyStore.clearUid(UserHandle.getUid(individual, appId));
16824                 }
16825             } else {
16826                 keyStore.clearUid(UserHandle.getUid(userId, appId));
16827             }
16828         } else {
16829             Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16830         }
16831     }
16832
16833     @Override
16834     public void deleteApplicationCacheFiles(final String packageName,
16835             final IPackageDataObserver observer) {
16836         final int userId = UserHandle.getCallingUserId();
16837         deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16838     }
16839
16840     @Override
16841     public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16842             final IPackageDataObserver observer) {
16843         mContext.enforceCallingOrSelfPermission(
16844                 android.Manifest.permission.DELETE_CACHE_FILES, null);
16845         enforceCrossUserPermission(Binder.getCallingUid(), userId,
16846                 /* requireFullPermission= */ true, /* checkShell= */ false,
16847                 "delete application cache files");
16848
16849         final PackageParser.Package pkg;
16850         synchronized (mPackages) {
16851             pkg = mPackages.get(packageName);
16852         }
16853
16854         // Queue up an async operation since the package deletion may take a little while.
16855         mHandler.post(new Runnable() {
16856             public void run() {
16857                 synchronized (mInstallLock) {
16858                     final int flags = StorageManager.FLAG_STORAGE_DE
16859                             | StorageManager.FLAG_STORAGE_CE;
16860                     // We're only clearing cache files, so we don't care if the
16861                     // app is unfrozen and still able to run
16862                     clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16863                     clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16864                 }
16865                 clearExternalStorageDataSync(packageName, userId, false);
16866                 if (observer != null) {
16867                     try {
16868                         observer.onRemoveCompleted(packageName, true);
16869                     } catch (RemoteException e) {
16870                         Log.i(TAG, "Observer no longer exists.");
16871                     }
16872                 }
16873             }
16874         });
16875     }
16876
16877     @Override
16878     public void getPackageSizeInfo(final String packageName, int userHandle,
16879             final IPackageStatsObserver observer) {
16880         mContext.enforceCallingOrSelfPermission(
16881                 android.Manifest.permission.GET_PACKAGE_SIZE, null);
16882         if (packageName == null) {
16883             throw new IllegalArgumentException("Attempt to get size of null packageName");
16884         }
16885
16886         PackageStats stats = new PackageStats(packageName, userHandle);
16887
16888         /*
16889          * Queue up an async operation since the package measurement may take a
16890          * little while.
16891          */
16892         Message msg = mHandler.obtainMessage(INIT_COPY);
16893         msg.obj = new MeasureParams(stats, observer);
16894         mHandler.sendMessage(msg);
16895     }
16896
16897     private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16898         final PackageSetting ps;
16899         synchronized (mPackages) {
16900             ps = mSettings.mPackages.get(packageName);
16901             if (ps == null) {
16902                 Slog.w(TAG, "Failed to find settings for " + packageName);
16903                 return false;
16904             }
16905         }
16906         try {
16907             mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16908                     StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16909                     ps.getCeDataInode(userId), ps.codePathString, stats);
16910         } catch (InstallerException e) {
16911             Slog.w(TAG, String.valueOf(e));
16912             return false;
16913         }
16914
16915         // For now, ignore code size of packages on system partition
16916         if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16917             stats.codeSize = 0;
16918         }
16919
16920         return true;
16921     }
16922
16923     private int getUidTargetSdkVersionLockedLPr(int uid) {
16924         Object obj = mSettings.getUserIdLPr(uid);
16925         if (obj instanceof SharedUserSetting) {
16926             final SharedUserSetting sus = (SharedUserSetting) obj;
16927             int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16928             final Iterator<PackageSetting> it = sus.packages.iterator();
16929             while (it.hasNext()) {
16930                 final PackageSetting ps = it.next();
16931                 if (ps.pkg != null) {
16932                     int v = ps.pkg.applicationInfo.targetSdkVersion;
16933                     if (v < vers) vers = v;
16934                 }
16935             }
16936             return vers;
16937         } else if (obj instanceof PackageSetting) {
16938             final PackageSetting ps = (PackageSetting) obj;
16939             if (ps.pkg != null) {
16940                 return ps.pkg.applicationInfo.targetSdkVersion;
16941             }
16942         }
16943         return Build.VERSION_CODES.CUR_DEVELOPMENT;
16944     }
16945
16946     @Override
16947     public void addPreferredActivity(IntentFilter filter, int match,
16948             ComponentName[] set, ComponentName activity, int userId) {
16949         addPreferredActivityInternal(filter, match, set, activity, true, userId,
16950                 "Adding preferred");
16951     }
16952
16953     private void addPreferredActivityInternal(IntentFilter filter, int match,
16954             ComponentName[] set, ComponentName activity, boolean always, int userId,
16955             String opname) {
16956         // writer
16957         int callingUid = Binder.getCallingUid();
16958         enforceCrossUserPermission(callingUid, userId,
16959                 true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16960         if (filter.countActions() == 0) {
16961             Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16962             return;
16963         }
16964         synchronized (mPackages) {
16965             if (mContext.checkCallingOrSelfPermission(
16966                     android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16967                     != PackageManager.PERMISSION_GRANTED) {
16968                 if (getUidTargetSdkVersionLockedLPr(callingUid)
16969                         < Build.VERSION_CODES.FROYO) {
16970                     Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16971                             + callingUid);
16972                     return;
16973                 }
16974                 mContext.enforceCallingOrSelfPermission(
16975                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16976             }
16977
16978             PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16979             Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16980                     + userId + ":");
16981             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16982             pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16983             scheduleWritePackageRestrictionsLocked(userId);
16984             postPreferredActivityChangedBroadcast(userId);
16985         }
16986     }
16987
16988     private void postPreferredActivityChangedBroadcast(int userId) {
16989         mHandler.post(() -> {
16990             final IActivityManager am = ActivityManagerNative.getDefault();
16991             if (am == null) {
16992                 return;
16993             }
16994
16995             final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
16996             intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
16997             try {
16998                 am.broadcastIntent(null, intent, null, null,
16999                         0, null, null, null, android.app.AppOpsManager.OP_NONE,
17000                         null, false, false, userId);
17001             } catch (RemoteException e) {
17002             }
17003         });
17004     }
17005
17006     @Override
17007     public void replacePreferredActivity(IntentFilter filter, int match,
17008             ComponentName[] set, ComponentName activity, int userId) {
17009         if (filter.countActions() != 1) {
17010             throw new IllegalArgumentException(
17011                     "replacePreferredActivity expects filter to have only 1 action.");
17012         }
17013         if (filter.countDataAuthorities() != 0
17014                 || filter.countDataPaths() != 0
17015                 || filter.countDataSchemes() > 1
17016                 || filter.countDataTypes() != 0) {
17017             throw new IllegalArgumentException(
17018                     "replacePreferredActivity expects filter to have no data authorities, " +
17019                     "paths, or types; and at most one scheme.");
17020         }
17021
17022         final int callingUid = Binder.getCallingUid();
17023         enforceCrossUserPermission(callingUid, userId,
17024                 true /* requireFullPermission */, false /* checkShell */,
17025                 "replace preferred activity");
17026         synchronized (mPackages) {
17027             if (mContext.checkCallingOrSelfPermission(
17028                     android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17029                     != PackageManager.PERMISSION_GRANTED) {
17030                 if (getUidTargetSdkVersionLockedLPr(callingUid)
17031                         < Build.VERSION_CODES.FROYO) {
17032                     Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
17033                             + Binder.getCallingUid());
17034                     return;
17035                 }
17036                 mContext.enforceCallingOrSelfPermission(
17037                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17038             }
17039
17040             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17041             if (pir != null) {
17042                 // Get all of the existing entries that exactly match this filter.
17043                 ArrayList<PreferredActivity> existing = pir.findFilters(filter);
17044                 if (existing != null && existing.size() == 1) {
17045                     PreferredActivity cur = existing.get(0);
17046                     if (DEBUG_PREFERRED) {
17047                         Slog.i(TAG, "Checking replace of preferred:");
17048                         filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17049                         if (!cur.mPref.mAlways) {
17050                             Slog.i(TAG, "  -- CUR; not mAlways!");
17051                         } else {
17052                             Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
17053                             Slog.i(TAG, "  -- CUR: mSet="
17054                                     + Arrays.toString(cur.mPref.mSetComponents));
17055                             Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
17056                             Slog.i(TAG, "  -- NEW: mMatch="
17057                                     + (match&IntentFilter.MATCH_CATEGORY_MASK));
17058                             Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
17059                             Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
17060                         }
17061                     }
17062                     if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
17063                             && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
17064                             && cur.mPref.sameSet(set)) {
17065                         // Setting the preferred activity to what it happens to be already
17066                         if (DEBUG_PREFERRED) {
17067                             Slog.i(TAG, "Replacing with same preferred activity "
17068                                     + cur.mPref.mShortComponent + " for user "
17069                                     + userId + ":");
17070                             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17071                         }
17072                         return;
17073                     }
17074                 }
17075
17076                 if (existing != null) {
17077                     if (DEBUG_PREFERRED) {
17078                         Slog.i(TAG, existing.size() + " existing preferred matches for:");
17079                         filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17080                     }
17081                     for (int i = 0; i < existing.size(); i++) {
17082                         PreferredActivity pa = existing.get(i);
17083                         if (DEBUG_PREFERRED) {
17084                             Slog.i(TAG, "Removing existing preferred activity "
17085                                     + pa.mPref.mComponent + ":");
17086                             pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
17087                         }
17088                         pir.removeFilter(pa);
17089                     }
17090                 }
17091             }
17092             addPreferredActivityInternal(filter, match, set, activity, true, userId,
17093                     "Replacing preferred");
17094         }
17095     }
17096
17097     @Override
17098     public void clearPackagePreferredActivities(String packageName) {
17099         final int uid = Binder.getCallingUid();
17100         // writer
17101         synchronized (mPackages) {
17102             PackageParser.Package pkg = mPackages.get(packageName);
17103             if (pkg == null || pkg.applicationInfo.uid != uid) {
17104                 if (mContext.checkCallingOrSelfPermission(
17105                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
17106                         != PackageManager.PERMISSION_GRANTED) {
17107                     if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
17108                             < Build.VERSION_CODES.FROYO) {
17109                         Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
17110                                 + Binder.getCallingUid());
17111                         return;
17112                     }
17113                     mContext.enforceCallingOrSelfPermission(
17114                             android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17115                 }
17116             }
17117
17118             int user = UserHandle.getCallingUserId();
17119             if (clearPackagePreferredActivitiesLPw(packageName, user)) {
17120                 scheduleWritePackageRestrictionsLocked(user);
17121             }
17122         }
17123     }
17124
17125     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17126     boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
17127         ArrayList<PreferredActivity> removed = null;
17128         boolean changed = false;
17129         for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17130             final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
17131             PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17132             if (userId != UserHandle.USER_ALL && userId != thisUserId) {
17133                 continue;
17134             }
17135             Iterator<PreferredActivity> it = pir.filterIterator();
17136             while (it.hasNext()) {
17137                 PreferredActivity pa = it.next();
17138                 // Mark entry for removal only if it matches the package name
17139                 // and the entry is of type "always".
17140                 if (packageName == null ||
17141                         (pa.mPref.mComponent.getPackageName().equals(packageName)
17142                                 && pa.mPref.mAlways)) {
17143                     if (removed == null) {
17144                         removed = new ArrayList<PreferredActivity>();
17145                     }
17146                     removed.add(pa);
17147                 }
17148             }
17149             if (removed != null) {
17150                 for (int j=0; j<removed.size(); j++) {
17151                     PreferredActivity pa = removed.get(j);
17152                     pir.removeFilter(pa);
17153                 }
17154                 changed = true;
17155             }
17156         }
17157         if (changed) {
17158             postPreferredActivityChangedBroadcast(userId);
17159         }
17160         return changed;
17161     }
17162
17163     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17164     private void clearIntentFilterVerificationsLPw(int userId) {
17165         final int packageCount = mPackages.size();
17166         for (int i = 0; i < packageCount; i++) {
17167             PackageParser.Package pkg = mPackages.valueAt(i);
17168             clearIntentFilterVerificationsLPw(pkg.packageName, userId);
17169         }
17170     }
17171
17172     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
17173     void clearIntentFilterVerificationsLPw(String packageName, int userId) {
17174         if (userId == UserHandle.USER_ALL) {
17175             if (mSettings.removeIntentFilterVerificationLPw(packageName,
17176                     sUserManager.getUserIds())) {
17177                 for (int oneUserId : sUserManager.getUserIds()) {
17178                     scheduleWritePackageRestrictionsLocked(oneUserId);
17179                 }
17180             }
17181         } else {
17182             if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
17183                 scheduleWritePackageRestrictionsLocked(userId);
17184             }
17185         }
17186     }
17187
17188     void clearDefaultBrowserIfNeeded(String packageName) {
17189         for (int oneUserId : sUserManager.getUserIds()) {
17190             String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
17191             if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
17192             if (packageName.equals(defaultBrowserPackageName)) {
17193                 setDefaultBrowserPackageName(null, oneUserId);
17194             }
17195         }
17196     }
17197
17198     @Override
17199     public void resetApplicationPreferences(int userId) {
17200         mContext.enforceCallingOrSelfPermission(
17201                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17202         final long identity = Binder.clearCallingIdentity();
17203         // writer
17204         try {
17205             synchronized (mPackages) {
17206                 clearPackagePreferredActivitiesLPw(null, userId);
17207                 mSettings.applyDefaultPreferredAppsLPw(this, userId);
17208                 // TODO: We have to reset the default SMS and Phone. This requires
17209                 // significant refactoring to keep all default apps in the package
17210                 // manager (cleaner but more work) or have the services provide
17211                 // callbacks to the package manager to request a default app reset.
17212                 applyFactoryDefaultBrowserLPw(userId);
17213                 clearIntentFilterVerificationsLPw(userId);
17214                 primeDomainVerificationsLPw(userId);
17215                 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17216                 scheduleWritePackageRestrictionsLocked(userId);
17217             }
17218             resetNetworkPolicies(userId);
17219         } finally {
17220             Binder.restoreCallingIdentity(identity);
17221         }
17222     }
17223
17224     @Override
17225     public int getPreferredActivities(List<IntentFilter> outFilters,
17226             List<ComponentName> outActivities, String packageName) {
17227
17228         int num = 0;
17229         final int userId = UserHandle.getCallingUserId();
17230         // reader
17231         synchronized (mPackages) {
17232             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17233             if (pir != null) {
17234                 final Iterator<PreferredActivity> it = pir.filterIterator();
17235                 while (it.hasNext()) {
17236                     final PreferredActivity pa = it.next();
17237                     if (packageName == null
17238                             || (pa.mPref.mComponent.getPackageName().equals(packageName)
17239                                     && pa.mPref.mAlways)) {
17240                         if (outFilters != null) {
17241                             outFilters.add(new IntentFilter(pa));
17242                         }
17243                         if (outActivities != null) {
17244                             outActivities.add(pa.mPref.mComponent);
17245                         }
17246                     }
17247                 }
17248             }
17249         }
17250
17251         return num;
17252     }
17253
17254     @Override
17255     public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17256             int userId) {
17257         int callingUid = Binder.getCallingUid();
17258         if (callingUid != Process.SYSTEM_UID) {
17259             throw new SecurityException(
17260                     "addPersistentPreferredActivity can only be run by the system");
17261         }
17262         if (filter.countActions() == 0) {
17263             Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17264             return;
17265         }
17266         synchronized (mPackages) {
17267             Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17268                     ":");
17269             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17270             mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17271                     new PersistentPreferredActivity(filter, activity));
17272             scheduleWritePackageRestrictionsLocked(userId);
17273             postPreferredActivityChangedBroadcast(userId);
17274         }
17275     }
17276
17277     @Override
17278     public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17279         int callingUid = Binder.getCallingUid();
17280         if (callingUid != Process.SYSTEM_UID) {
17281             throw new SecurityException(
17282                     "clearPackagePersistentPreferredActivities can only be run by the system");
17283         }
17284         ArrayList<PersistentPreferredActivity> removed = null;
17285         boolean changed = false;
17286         synchronized (mPackages) {
17287             for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17288                 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17289                 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17290                         .valueAt(i);
17291                 if (userId != thisUserId) {
17292                     continue;
17293                 }
17294                 Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17295                 while (it.hasNext()) {
17296                     PersistentPreferredActivity ppa = it.next();
17297                     // Mark entry for removal only if it matches the package name.
17298                     if (ppa.mComponent.getPackageName().equals(packageName)) {
17299                         if (removed == null) {
17300                             removed = new ArrayList<PersistentPreferredActivity>();
17301                         }
17302                         removed.add(ppa);
17303                     }
17304                 }
17305                 if (removed != null) {
17306                     for (int j=0; j<removed.size(); j++) {
17307                         PersistentPreferredActivity ppa = removed.get(j);
17308                         ppir.removeFilter(ppa);
17309                     }
17310                     changed = true;
17311                 }
17312             }
17313
17314             if (changed) {
17315                 scheduleWritePackageRestrictionsLocked(userId);
17316                 postPreferredActivityChangedBroadcast(userId);
17317             }
17318         }
17319     }
17320
17321     /**
17322      * Common machinery for picking apart a restored XML blob and passing
17323      * it to a caller-supplied functor to be applied to the running system.
17324      */
17325     private void restoreFromXml(XmlPullParser parser, int userId,
17326             String expectedStartTag, BlobXmlRestorer functor)
17327             throws IOException, XmlPullParserException {
17328         int type;
17329         while ((type = parser.next()) != XmlPullParser.START_TAG
17330                 && type != XmlPullParser.END_DOCUMENT) {
17331         }
17332         if (type != XmlPullParser.START_TAG) {
17333             // oops didn't find a start tag?!
17334             if (DEBUG_BACKUP) {
17335                 Slog.e(TAG, "Didn't find start tag during restore");
17336             }
17337             return;
17338         }
17339 Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17340         // this is supposed to be TAG_PREFERRED_BACKUP
17341         if (!expectedStartTag.equals(parser.getName())) {
17342             if (DEBUG_BACKUP) {
17343                 Slog.e(TAG, "Found unexpected tag " + parser.getName());
17344             }
17345             return;
17346         }
17347
17348         // skip interfering stuff, then we're aligned with the backing implementation
17349         while ((type = parser.next()) == XmlPullParser.TEXT) { }
17350 Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17351         functor.apply(parser, userId);
17352     }
17353
17354     private interface BlobXmlRestorer {
17355         public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17356     }
17357
17358     /**
17359      * Non-Binder method, support for the backup/restore mechanism: write the
17360      * full set of preferred activities in its canonical XML format.  Returns the
17361      * XML output as a byte array, or null if there is none.
17362      */
17363     @Override
17364     public byte[] getPreferredActivityBackup(int userId) {
17365         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17366             throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17367         }
17368
17369         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17370         try {
17371             final XmlSerializer serializer = new FastXmlSerializer();
17372             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17373             serializer.startDocument(null, true);
17374             serializer.startTag(null, TAG_PREFERRED_BACKUP);
17375
17376             synchronized (mPackages) {
17377                 mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17378             }
17379
17380             serializer.endTag(null, TAG_PREFERRED_BACKUP);
17381             serializer.endDocument();
17382             serializer.flush();
17383         } catch (Exception e) {
17384             if (DEBUG_BACKUP) {
17385                 Slog.e(TAG, "Unable to write preferred activities for backup", e);
17386             }
17387             return null;
17388         }
17389
17390         return dataStream.toByteArray();
17391     }
17392
17393     @Override
17394     public void restorePreferredActivities(byte[] backup, int userId) {
17395         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17396             throw new SecurityException("Only the system may call restorePreferredActivities()");
17397         }
17398
17399         try {
17400             final XmlPullParser parser = Xml.newPullParser();
17401             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17402             restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17403                     new BlobXmlRestorer() {
17404                         @Override
17405                         public void apply(XmlPullParser parser, int userId)
17406                                 throws XmlPullParserException, IOException {
17407                             synchronized (mPackages) {
17408                                 mSettings.readPreferredActivitiesLPw(parser, userId);
17409                             }
17410                         }
17411                     } );
17412         } catch (Exception e) {
17413             if (DEBUG_BACKUP) {
17414                 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17415             }
17416         }
17417     }
17418
17419     /**
17420      * Non-Binder method, support for the backup/restore mechanism: write the
17421      * default browser (etc) settings in its canonical XML format.  Returns the default
17422      * browser XML representation as a byte array, or null if there is none.
17423      */
17424     @Override
17425     public byte[] getDefaultAppsBackup(int userId) {
17426         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17427             throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17428         }
17429
17430         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17431         try {
17432             final XmlSerializer serializer = new FastXmlSerializer();
17433             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17434             serializer.startDocument(null, true);
17435             serializer.startTag(null, TAG_DEFAULT_APPS);
17436
17437             synchronized (mPackages) {
17438                 mSettings.writeDefaultAppsLPr(serializer, userId);
17439             }
17440
17441             serializer.endTag(null, TAG_DEFAULT_APPS);
17442             serializer.endDocument();
17443             serializer.flush();
17444         } catch (Exception e) {
17445             if (DEBUG_BACKUP) {
17446                 Slog.e(TAG, "Unable to write default apps for backup", e);
17447             }
17448             return null;
17449         }
17450
17451         return dataStream.toByteArray();
17452     }
17453
17454     @Override
17455     public void restoreDefaultApps(byte[] backup, int userId) {
17456         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17457             throw new SecurityException("Only the system may call restoreDefaultApps()");
17458         }
17459
17460         try {
17461             final XmlPullParser parser = Xml.newPullParser();
17462             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17463             restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17464                     new BlobXmlRestorer() {
17465                         @Override
17466                         public void apply(XmlPullParser parser, int userId)
17467                                 throws XmlPullParserException, IOException {
17468                             synchronized (mPackages) {
17469                                 mSettings.readDefaultAppsLPw(parser, userId);
17470                             }
17471                         }
17472                     } );
17473         } catch (Exception e) {
17474             if (DEBUG_BACKUP) {
17475                 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17476             }
17477         }
17478     }
17479
17480     @Override
17481     public byte[] getIntentFilterVerificationBackup(int userId) {
17482         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17483             throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17484         }
17485
17486         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17487         try {
17488             final XmlSerializer serializer = new FastXmlSerializer();
17489             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17490             serializer.startDocument(null, true);
17491             serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17492
17493             synchronized (mPackages) {
17494                 mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17495             }
17496
17497             serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17498             serializer.endDocument();
17499             serializer.flush();
17500         } catch (Exception e) {
17501             if (DEBUG_BACKUP) {
17502                 Slog.e(TAG, "Unable to write default apps for backup", e);
17503             }
17504             return null;
17505         }
17506
17507         return dataStream.toByteArray();
17508     }
17509
17510     @Override
17511     public void restoreIntentFilterVerification(byte[] backup, int userId) {
17512         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17513             throw new SecurityException("Only the system may call restorePreferredActivities()");
17514         }
17515
17516         try {
17517             final XmlPullParser parser = Xml.newPullParser();
17518             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17519             restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17520                     new BlobXmlRestorer() {
17521                         @Override
17522                         public void apply(XmlPullParser parser, int userId)
17523                                 throws XmlPullParserException, IOException {
17524                             synchronized (mPackages) {
17525                                 mSettings.readAllDomainVerificationsLPr(parser, userId);
17526                                 mSettings.writeLPr();
17527                             }
17528                         }
17529                     } );
17530         } catch (Exception e) {
17531             if (DEBUG_BACKUP) {
17532                 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17533             }
17534         }
17535     }
17536
17537     @Override
17538     public byte[] getPermissionGrantBackup(int userId) {
17539         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17540             throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17541         }
17542
17543         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17544         try {
17545             final XmlSerializer serializer = new FastXmlSerializer();
17546             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17547             serializer.startDocument(null, true);
17548             serializer.startTag(null, TAG_PERMISSION_BACKUP);
17549
17550             synchronized (mPackages) {
17551                 serializeRuntimePermissionGrantsLPr(serializer, userId);
17552             }
17553
17554             serializer.endTag(null, TAG_PERMISSION_BACKUP);
17555             serializer.endDocument();
17556             serializer.flush();
17557         } catch (Exception e) {
17558             if (DEBUG_BACKUP) {
17559                 Slog.e(TAG, "Unable to write default apps for backup", e);
17560             }
17561             return null;
17562         }
17563
17564         return dataStream.toByteArray();
17565     }
17566
17567     @Override
17568     public void restorePermissionGrants(byte[] backup, int userId) {
17569         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17570             throw new SecurityException("Only the system may call restorePermissionGrants()");
17571         }
17572
17573         try {
17574             final XmlPullParser parser = Xml.newPullParser();
17575             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17576             restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17577                     new BlobXmlRestorer() {
17578                         @Override
17579                         public void apply(XmlPullParser parser, int userId)
17580                                 throws XmlPullParserException, IOException {
17581                             synchronized (mPackages) {
17582                                 processRestoredPermissionGrantsLPr(parser, userId);
17583                             }
17584                         }
17585                     } );
17586         } catch (Exception e) {
17587             if (DEBUG_BACKUP) {
17588                 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17589             }
17590         }
17591     }
17592
17593     private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17594             throws IOException {
17595         serializer.startTag(null, TAG_ALL_GRANTS);
17596
17597         final int N = mSettings.mPackages.size();
17598         for (int i = 0; i < N; i++) {
17599             final PackageSetting ps = mSettings.mPackages.valueAt(i);
17600             boolean pkgGrantsKnown = false;
17601
17602             PermissionsState packagePerms = ps.getPermissionsState();
17603
17604             for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17605                 final int grantFlags = state.getFlags();
17606                 // only look at grants that are not system/policy fixed
17607                 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17608                     final boolean isGranted = state.isGranted();
17609                     // And only back up the user-twiddled state bits
17610                     if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17611                         final String packageName = mSettings.mPackages.keyAt(i);
17612                         if (!pkgGrantsKnown) {
17613                             serializer.startTag(null, TAG_GRANT);
17614                             serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17615                             pkgGrantsKnown = true;
17616                         }
17617
17618                         final boolean userSet =
17619                                 (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17620                         final boolean userFixed =
17621                                 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17622                         final boolean revoke =
17623                                 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17624
17625                         serializer.startTag(null, TAG_PERMISSION);
17626                         serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17627                         if (isGranted) {
17628                             serializer.attribute(null, ATTR_IS_GRANTED, "true");
17629                         }
17630                         if (userSet) {
17631                             serializer.attribute(null, ATTR_USER_SET, "true");
17632                         }
17633                         if (userFixed) {
17634                             serializer.attribute(null, ATTR_USER_FIXED, "true");
17635                         }
17636                         if (revoke) {
17637                             serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17638                         }
17639                         serializer.endTag(null, TAG_PERMISSION);
17640                     }
17641                 }
17642             }
17643
17644             if (pkgGrantsKnown) {
17645                 serializer.endTag(null, TAG_GRANT);
17646             }
17647         }
17648
17649         serializer.endTag(null, TAG_ALL_GRANTS);
17650     }
17651
17652     private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17653             throws XmlPullParserException, IOException {
17654         String pkgName = null;
17655         int outerDepth = parser.getDepth();
17656         int type;
17657         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17658                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17659             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17660                 continue;
17661             }
17662
17663             final String tagName = parser.getName();
17664             if (tagName.equals(TAG_GRANT)) {
17665                 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17666                 if (DEBUG_BACKUP) {
17667                     Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17668                 }
17669             } else if (tagName.equals(TAG_PERMISSION)) {
17670
17671                 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17672                 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17673
17674                 int newFlagSet = 0;
17675                 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17676                     newFlagSet |= FLAG_PERMISSION_USER_SET;
17677                 }
17678                 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17679                     newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17680                 }
17681                 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17682                     newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17683                 }
17684                 if (DEBUG_BACKUP) {
17685                     Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17686                             + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17687                 }
17688                 final PackageSetting ps = mSettings.mPackages.get(pkgName);
17689                 if (ps != null) {
17690                     // Already installed so we apply the grant immediately
17691                     if (DEBUG_BACKUP) {
17692                         Slog.v(TAG, "        + already installed; applying");
17693                     }
17694                     PermissionsState perms = ps.getPermissionsState();
17695                     BasePermission bp = mSettings.mPermissions.get(permName);
17696                     if (bp != null) {
17697                         if (isGranted) {
17698                             perms.grantRuntimePermission(bp, userId);
17699                         }
17700                         if (newFlagSet != 0) {
17701                             perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17702                         }
17703                     }
17704                 } else {
17705                     // Need to wait for post-restore install to apply the grant
17706                     if (DEBUG_BACKUP) {
17707                         Slog.v(TAG, "        - not yet installed; saving for later");
17708                     }
17709                     mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17710                             isGranted, newFlagSet, userId);
17711                 }
17712             } else {
17713                 PackageManagerService.reportSettingsProblem(Log.WARN,
17714                         "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17715                 XmlUtils.skipCurrentTag(parser);
17716             }
17717         }
17718
17719         scheduleWriteSettingsLocked();
17720         mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17721     }
17722
17723     @Override
17724     public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17725             int sourceUserId, int targetUserId, int flags) {
17726         mContext.enforceCallingOrSelfPermission(
17727                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17728         int callingUid = Binder.getCallingUid();
17729         enforceOwnerRights(ownerPackage, callingUid);
17730         enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17731         if (intentFilter.countActions() == 0) {
17732             Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17733             return;
17734         }
17735         synchronized (mPackages) {
17736             CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17737                     ownerPackage, targetUserId, flags);
17738             CrossProfileIntentResolver resolver =
17739                     mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17740             ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17741             // We have all those whose filter is equal. Now checking if the rest is equal as well.
17742             if (existing != null) {
17743                 int size = existing.size();
17744                 for (int i = 0; i < size; i++) {
17745                     if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17746                         return;
17747                     }
17748                 }
17749             }
17750             resolver.addFilter(newFilter);
17751             scheduleWritePackageRestrictionsLocked(sourceUserId);
17752         }
17753     }
17754
17755     @Override
17756     public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17757         mContext.enforceCallingOrSelfPermission(
17758                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17759         int callingUid = Binder.getCallingUid();
17760         enforceOwnerRights(ownerPackage, callingUid);
17761         enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17762         synchronized (mPackages) {
17763             CrossProfileIntentResolver resolver =
17764                     mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17765             ArraySet<CrossProfileIntentFilter> set =
17766                     new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17767             for (CrossProfileIntentFilter filter : set) {
17768                 if (filter.getOwnerPackage().equals(ownerPackage)) {
17769                     resolver.removeFilter(filter);
17770                 }
17771             }
17772             scheduleWritePackageRestrictionsLocked(sourceUserId);
17773         }
17774     }
17775
17776     // Enforcing that callingUid is owning pkg on userId
17777     private void enforceOwnerRights(String pkg, int callingUid) {
17778         // The system owns everything.
17779         if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17780             return;
17781         }
17782         int callingUserId = UserHandle.getUserId(callingUid);
17783         PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17784         if (pi == null) {
17785             throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17786                     + callingUserId);
17787         }
17788         if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17789             throw new SecurityException("Calling uid " + callingUid
17790                     + " does not own package " + pkg);
17791         }
17792     }
17793
17794     @Override
17795     public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17796         return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17797     }
17798
17799     private Intent getHomeIntent() {
17800         Intent intent = new Intent(Intent.ACTION_MAIN);
17801         intent.addCategory(Intent.CATEGORY_HOME);
17802         intent.addCategory(Intent.CATEGORY_DEFAULT);
17803         return intent;
17804     }
17805
17806     private IntentFilter getHomeFilter() {
17807         IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17808         filter.addCategory(Intent.CATEGORY_HOME);
17809         filter.addCategory(Intent.CATEGORY_DEFAULT);
17810         return filter;
17811     }
17812
17813     ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17814             int userId) {
17815         Intent intent  = getHomeIntent();
17816         List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17817                 PackageManager.GET_META_DATA, userId);
17818         ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17819                 true, false, false, userId);
17820
17821         allHomeCandidates.clear();
17822         if (list != null) {
17823             for (ResolveInfo ri : list) {
17824                 allHomeCandidates.add(ri);
17825             }
17826         }
17827         return (preferred == null || preferred.activityInfo == null)
17828                 ? null
17829                 : new ComponentName(preferred.activityInfo.packageName,
17830                         preferred.activityInfo.name);
17831     }
17832
17833     @Override
17834     public void setHomeActivity(ComponentName comp, int userId) {
17835         ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17836         getHomeActivitiesAsUser(homeActivities, userId);
17837
17838         boolean found = false;
17839
17840         final int size = homeActivities.size();
17841         final ComponentName[] set = new ComponentName[size];
17842         for (int i = 0; i < size; i++) {
17843             final ResolveInfo candidate = homeActivities.get(i);
17844             final ActivityInfo info = candidate.activityInfo;
17845             final ComponentName activityName = new ComponentName(info.packageName, info.name);
17846             set[i] = activityName;
17847             if (!found && activityName.equals(comp)) {
17848                 found = true;
17849             }
17850         }
17851         if (!found) {
17852             throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17853                     + userId);
17854         }
17855         replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17856                 set, comp, userId);
17857     }
17858
17859     private @Nullable String getSetupWizardPackageName() {
17860         final Intent intent = new Intent(Intent.ACTION_MAIN);
17861         intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17862
17863         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17864                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17865                         | MATCH_DISABLED_COMPONENTS,
17866                 UserHandle.myUserId());
17867         if (matches.size() == 1) {
17868             return matches.get(0).getComponentInfo().packageName;
17869         } else {
17870             Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17871                     + ": matches=" + matches);
17872             return null;
17873         }
17874     }
17875
17876     private @Nullable String getStorageManagerPackageName() {
17877         final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
17878
17879         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17880                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17881                         | MATCH_DISABLED_COMPONENTS,
17882                 UserHandle.myUserId());
17883         if (matches.size() == 1) {
17884             return matches.get(0).getComponentInfo().packageName;
17885         } else {
17886             Slog.e(TAG, "There should probably be exactly one storage manager; found "
17887                     + matches.size() + ": matches=" + matches);
17888             return null;
17889         }
17890     }
17891
17892     @Override
17893     public void setApplicationEnabledSetting(String appPackageName,
17894             int newState, int flags, int userId, String callingPackage) {
17895         if (!sUserManager.exists(userId)) return;
17896         if (callingPackage == null) {
17897             callingPackage = Integer.toString(Binder.getCallingUid());
17898         }
17899         setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17900     }
17901
17902     @Override
17903     public void setComponentEnabledSetting(ComponentName componentName,
17904             int newState, int flags, int userId) {
17905         if (!sUserManager.exists(userId)) return;
17906         setEnabledSetting(componentName.getPackageName(),
17907                 componentName.getClassName(), newState, flags, userId, null);
17908     }
17909
17910     private void setEnabledSetting(final String packageName, String className, int newState,
17911             final int flags, int userId, String callingPackage) {
17912         if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17913               || newState == COMPONENT_ENABLED_STATE_ENABLED
17914               || newState == COMPONENT_ENABLED_STATE_DISABLED
17915               || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17916               || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17917             throw new IllegalArgumentException("Invalid new component state: "
17918                     + newState);
17919         }
17920         PackageSetting pkgSetting;
17921         final int uid = Binder.getCallingUid();
17922         final int permission;
17923         if (uid == Process.SYSTEM_UID) {
17924             permission = PackageManager.PERMISSION_GRANTED;
17925         } else {
17926             permission = mContext.checkCallingOrSelfPermission(
17927                     android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17928         }
17929         enforceCrossUserPermission(uid, userId,
17930                 false /* requireFullPermission */, true /* checkShell */, "set enabled");
17931         final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17932         boolean sendNow = false;
17933         boolean isApp = (className == null);
17934         String componentName = isApp ? packageName : className;
17935         int packageUid = -1;
17936         ArrayList<String> components;
17937
17938         // writer
17939         synchronized (mPackages) {
17940             pkgSetting = mSettings.mPackages.get(packageName);
17941             if (pkgSetting == null) {
17942                 if (className == null) {
17943                     throw new IllegalArgumentException("Unknown package: " + packageName);
17944                 }
17945                 throw new IllegalArgumentException(
17946                         "Unknown component: " + packageName + "/" + className);
17947             }
17948         }
17949
17950         // Limit who can change which apps
17951         if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17952             // Don't allow apps that don't have permission to modify other apps
17953             if (!allowedByPermission) {
17954                 throw new SecurityException(
17955                         "Permission Denial: attempt to change component state from pid="
17956                         + Binder.getCallingPid()
17957                         + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17958             }
17959             // Don't allow changing protected packages.
17960             if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
17961                 throw new SecurityException("Cannot disable a protected package: " + packageName);
17962             }
17963         }
17964
17965         synchronized (mPackages) {
17966             if (uid == Process.SHELL_UID) {
17967                 // Shell can only change whole packages between ENABLED and DISABLED_USER states
17968                 int oldState = pkgSetting.getEnabled(userId);
17969                 if (className == null
17970                     &&
17971                     (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17972                      || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17973                      || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17974                     &&
17975                     (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17976                      || newState == COMPONENT_ENABLED_STATE_DEFAULT
17977                      || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17978                     // ok
17979                 } else {
17980                     throw new SecurityException(
17981                             "Shell cannot change component state for " + packageName + "/"
17982                             + className + " to " + newState);
17983                 }
17984             }
17985             if (className == null) {
17986                 // We're dealing with an application/package level state change
17987                 if (pkgSetting.getEnabled(userId) == newState) {
17988                     // Nothing to do
17989                     return;
17990                 }
17991                 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17992                     || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17993                     // Don't care about who enables an app.
17994                     callingPackage = null;
17995                 }
17996                 pkgSetting.setEnabled(newState, userId, callingPackage);
17997                 // pkgSetting.pkg.mSetEnabled = newState;
17998             } else {
17999                 // We're dealing with a component level state change
18000                 // First, verify that this is a valid class name.
18001                 PackageParser.Package pkg = pkgSetting.pkg;
18002                 if (pkg == null || !pkg.hasComponentClassName(className)) {
18003                     if (pkg != null &&
18004                             pkg.applicationInfo.targetSdkVersion >=
18005                                     Build.VERSION_CODES.JELLY_BEAN) {
18006                         throw new IllegalArgumentException("Component class " + className
18007                                 + " does not exist in " + packageName);
18008                     } else {
18009                         Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
18010                                 + className + " does not exist in " + packageName);
18011                     }
18012                 }
18013                 switch (newState) {
18014                 case COMPONENT_ENABLED_STATE_ENABLED:
18015                     if (!pkgSetting.enableComponentLPw(className, userId)) {
18016                         return;
18017                     }
18018                     break;
18019                 case COMPONENT_ENABLED_STATE_DISABLED:
18020                     if (!pkgSetting.disableComponentLPw(className, userId)) {
18021                         return;
18022                     }
18023                     break;
18024                 case COMPONENT_ENABLED_STATE_DEFAULT:
18025                     if (!pkgSetting.restoreComponentLPw(className, userId)) {
18026                         return;
18027                     }
18028                     break;
18029                 default:
18030                     Slog.e(TAG, "Invalid new component state: " + newState);
18031                     return;
18032                 }
18033             }
18034             scheduleWritePackageRestrictionsLocked(userId);
18035             components = mPendingBroadcasts.get(userId, packageName);
18036             final boolean newPackage = components == null;
18037             if (newPackage) {
18038                 components = new ArrayList<String>();
18039             }
18040             if (!components.contains(componentName)) {
18041                 components.add(componentName);
18042             }
18043             if ((flags&PackageManager.DONT_KILL_APP) == 0) {
18044                 sendNow = true;
18045                 // Purge entry from pending broadcast list if another one exists already
18046                 // since we are sending one right away.
18047                 mPendingBroadcasts.remove(userId, packageName);
18048             } else {
18049                 if (newPackage) {
18050                     mPendingBroadcasts.put(userId, packageName, components);
18051                 }
18052                 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
18053                     // Schedule a message
18054                     mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
18055                 }
18056             }
18057         }
18058
18059         long callingId = Binder.clearCallingIdentity();
18060         try {
18061             if (sendNow) {
18062                 packageUid = UserHandle.getUid(userId, pkgSetting.appId);
18063                 sendPackageChangedBroadcast(packageName,
18064                         (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
18065             }
18066         } finally {
18067             Binder.restoreCallingIdentity(callingId);
18068         }
18069     }
18070
18071     @Override
18072     public void flushPackageRestrictionsAsUser(int userId) {
18073         if (!sUserManager.exists(userId)) {
18074             return;
18075         }
18076         enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
18077                 false /* checkShell */, "flushPackageRestrictions");
18078         synchronized (mPackages) {
18079             mSettings.writePackageRestrictionsLPr(userId);
18080             mDirtyUsers.remove(userId);
18081             if (mDirtyUsers.isEmpty()) {
18082                 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
18083             }
18084         }
18085     }
18086
18087     private void sendPackageChangedBroadcast(String packageName,
18088             boolean killFlag, ArrayList<String> componentNames, int packageUid) {
18089         if (DEBUG_INSTALL)
18090             Log.v(TAG, "Sending package changed: package=" + packageName + " components="
18091                     + componentNames);
18092         Bundle extras = new Bundle(4);
18093         extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
18094         String nameList[] = new String[componentNames.size()];
18095         componentNames.toArray(nameList);
18096         extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
18097         extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
18098         extras.putInt(Intent.EXTRA_UID, packageUid);
18099         // If this is not reporting a change of the overall package, then only send it
18100         // to registered receivers.  We don't want to launch a swath of apps for every
18101         // little component state change.
18102         final int flags = !componentNames.contains(packageName)
18103                 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
18104         sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
18105                 new int[] {UserHandle.getUserId(packageUid)});
18106     }
18107
18108     @Override
18109     public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
18110         if (!sUserManager.exists(userId)) return;
18111         final int uid = Binder.getCallingUid();
18112         final int permission = mContext.checkCallingOrSelfPermission(
18113                 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
18114         final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
18115         enforceCrossUserPermission(uid, userId,
18116                 true /* requireFullPermission */, true /* checkShell */, "stop package");
18117         // writer
18118         synchronized (mPackages) {
18119             if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
18120                     allowedByPermission, uid, userId)) {
18121                 scheduleWritePackageRestrictionsLocked(userId);
18122             }
18123         }
18124     }
18125
18126     @Override
18127     public String getInstallerPackageName(String packageName) {
18128         // reader
18129         synchronized (mPackages) {
18130             return mSettings.getInstallerPackageNameLPr(packageName);
18131         }
18132     }
18133
18134     public boolean isOrphaned(String packageName) {
18135         // reader
18136         synchronized (mPackages) {
18137             return mSettings.isOrphaned(packageName);
18138         }
18139     }
18140
18141     @Override
18142     public int getApplicationEnabledSetting(String packageName, int userId) {
18143         if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18144         int uid = Binder.getCallingUid();
18145         enforceCrossUserPermission(uid, userId,
18146                 false /* requireFullPermission */, false /* checkShell */, "get enabled");
18147         // reader
18148         synchronized (mPackages) {
18149             return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
18150         }
18151     }
18152
18153     @Override
18154     public int getComponentEnabledSetting(ComponentName componentName, int userId) {
18155         if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
18156         int uid = Binder.getCallingUid();
18157         enforceCrossUserPermission(uid, userId,
18158                 false /* requireFullPermission */, false /* checkShell */, "get component enabled");
18159         // reader
18160         synchronized (mPackages) {
18161             return mSettings.getComponentEnabledSettingLPr(componentName, userId);
18162         }
18163     }
18164
18165     @Override
18166     public void enterSafeMode() {
18167         enforceSystemOrRoot("Only the system can request entering safe mode");
18168
18169         if (!mSystemReady) {
18170             mSafeMode = true;
18171         }
18172     }
18173
18174     @Override
18175     public void systemReady() {
18176         mSystemReady = true;
18177
18178         // Disable any carrier apps. We do this very early in boot to prevent the apps from being
18179         // disabled after already being started.
18180         CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
18181                 mContext.getContentResolver(), UserHandle.USER_SYSTEM);
18182
18183         // Read the compatibilty setting when the system is ready.
18184         boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
18185                 mContext.getContentResolver(),
18186                 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
18187         PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
18188         if (DEBUG_SETTINGS) {
18189             Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
18190         }
18191
18192         int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
18193
18194         synchronized (mPackages) {
18195             // Verify that all of the preferred activity components actually
18196             // exist.  It is possible for applications to be updated and at
18197             // that point remove a previously declared activity component that
18198             // had been set as a preferred activity.  We try to clean this up
18199             // the next time we encounter that preferred activity, but it is
18200             // possible for the user flow to never be able to return to that
18201             // situation so here we do a sanity check to make sure we haven't
18202             // left any junk around.
18203             ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
18204             for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18205                 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18206                 removed.clear();
18207                 for (PreferredActivity pa : pir.filterSet()) {
18208                     if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
18209                         removed.add(pa);
18210                     }
18211                 }
18212                 if (removed.size() > 0) {
18213                     for (int r=0; r<removed.size(); r++) {
18214                         PreferredActivity pa = removed.get(r);
18215                         Slog.w(TAG, "Removing dangling preferred activity: "
18216                                 + pa.mPref.mComponent);
18217                         pir.removeFilter(pa);
18218                     }
18219                     mSettings.writePackageRestrictionsLPr(
18220                             mSettings.mPreferredActivities.keyAt(i));
18221                 }
18222             }
18223
18224             for (int userId : UserManagerService.getInstance().getUserIds()) {
18225                 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18226                     grantPermissionsUserIds = ArrayUtils.appendInt(
18227                             grantPermissionsUserIds, userId);
18228                 }
18229             }
18230         }
18231         sUserManager.systemReady();
18232
18233         // If we upgraded grant all default permissions before kicking off.
18234         for (int userId : grantPermissionsUserIds) {
18235             mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18236         }
18237
18238         // If we did not grant default permissions, we preload from this the
18239         // default permission exceptions lazily to ensure we don't hit the
18240         // disk on a new user creation.
18241         if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
18242             mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
18243         }
18244
18245         // Kick off any messages waiting for system ready
18246         if (mPostSystemReadyMessages != null) {
18247             for (Message msg : mPostSystemReadyMessages) {
18248                 msg.sendToTarget();
18249             }
18250             mPostSystemReadyMessages = null;
18251         }
18252
18253         // Watch for external volumes that come and go over time
18254         final StorageManager storage = mContext.getSystemService(StorageManager.class);
18255         storage.registerListener(mStorageListener);
18256
18257         mInstallerService.systemReady();
18258         mPackageDexOptimizer.systemReady();
18259
18260         MountServiceInternal mountServiceInternal = LocalServices.getService(
18261                 MountServiceInternal.class);
18262         mountServiceInternal.addExternalStoragePolicy(
18263                 new MountServiceInternal.ExternalStorageMountPolicy() {
18264             @Override
18265             public int getMountMode(int uid, String packageName) {
18266                 if (Process.isIsolated(uid)) {
18267                     return Zygote.MOUNT_EXTERNAL_NONE;
18268                 }
18269                 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18270                     return Zygote.MOUNT_EXTERNAL_DEFAULT;
18271                 }
18272                 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18273                     return Zygote.MOUNT_EXTERNAL_DEFAULT;
18274                 }
18275                 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18276                     return Zygote.MOUNT_EXTERNAL_READ;
18277                 }
18278                 return Zygote.MOUNT_EXTERNAL_WRITE;
18279             }
18280
18281             @Override
18282             public boolean hasExternalStorage(int uid, String packageName) {
18283                 return true;
18284             }
18285         });
18286
18287         // Now that we're mostly running, clean up stale users and apps
18288         reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18289         reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18290     }
18291
18292     @Override
18293     public boolean isSafeMode() {
18294         return mSafeMode;
18295     }
18296
18297     @Override
18298     public boolean hasSystemUidErrors() {
18299         return mHasSystemUidErrors;
18300     }
18301
18302     static String arrayToString(int[] array) {
18303         StringBuffer buf = new StringBuffer(128);
18304         buf.append('[');
18305         if (array != null) {
18306             for (int i=0; i<array.length; i++) {
18307                 if (i > 0) buf.append(", ");
18308                 buf.append(array[i]);
18309             }
18310         }
18311         buf.append(']');
18312         return buf.toString();
18313     }
18314
18315     static class DumpState {
18316         public static final int DUMP_LIBS = 1 << 0;
18317         public static final int DUMP_FEATURES = 1 << 1;
18318         public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18319         public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18320         public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18321         public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18322         public static final int DUMP_PERMISSIONS = 1 << 6;
18323         public static final int DUMP_PACKAGES = 1 << 7;
18324         public static final int DUMP_SHARED_USERS = 1 << 8;
18325         public static final int DUMP_MESSAGES = 1 << 9;
18326         public static final int DUMP_PROVIDERS = 1 << 10;
18327         public static final int DUMP_VERIFIERS = 1 << 11;
18328         public static final int DUMP_PREFERRED = 1 << 12;
18329         public static final int DUMP_PREFERRED_XML = 1 << 13;
18330         public static final int DUMP_KEYSETS = 1 << 14;
18331         public static final int DUMP_VERSION = 1 << 15;
18332         public static final int DUMP_INSTALLS = 1 << 16;
18333         public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18334         public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18335         public static final int DUMP_FROZEN = 1 << 19;
18336         public static final int DUMP_DEXOPT = 1 << 20;
18337         public static final int DUMP_COMPILER_STATS = 1 << 21;
18338
18339         public static final int OPTION_SHOW_FILTERS = 1 << 0;
18340
18341         private int mTypes;
18342
18343         private int mOptions;
18344
18345         private boolean mTitlePrinted;
18346
18347         private SharedUserSetting mSharedUser;
18348
18349         public boolean isDumping(int type) {
18350             if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18351                 return true;
18352             }
18353
18354             return (mTypes & type) != 0;
18355         }
18356
18357         public void setDump(int type) {
18358             mTypes |= type;
18359         }
18360
18361         public boolean isOptionEnabled(int option) {
18362             return (mOptions & option) != 0;
18363         }
18364
18365         public void setOptionEnabled(int option) {
18366             mOptions |= option;
18367         }
18368
18369         public boolean onTitlePrinted() {
18370             final boolean printed = mTitlePrinted;
18371             mTitlePrinted = true;
18372             return printed;
18373         }
18374
18375         public boolean getTitlePrinted() {
18376             return mTitlePrinted;
18377         }
18378
18379         public void setTitlePrinted(boolean enabled) {
18380             mTitlePrinted = enabled;
18381         }
18382
18383         public SharedUserSetting getSharedUser() {
18384             return mSharedUser;
18385         }
18386
18387         public void setSharedUser(SharedUserSetting user) {
18388             mSharedUser = user;
18389         }
18390     }
18391
18392     @Override
18393     public void onShellCommand(FileDescriptor in, FileDescriptor out,
18394             FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18395         (new PackageManagerShellCommand(this)).exec(
18396                 this, in, out, err, args, resultReceiver);
18397     }
18398
18399     @Override
18400     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18401         if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18402                 != PackageManager.PERMISSION_GRANTED) {
18403             pw.println("Permission Denial: can't dump ActivityManager from from pid="
18404                     + Binder.getCallingPid()
18405                     + ", uid=" + Binder.getCallingUid()
18406                     + " without permission "
18407                     + android.Manifest.permission.DUMP);
18408             return;
18409         }
18410
18411         DumpState dumpState = new DumpState();
18412         boolean fullPreferred = false;
18413         boolean checkin = false;
18414
18415         String packageName = null;
18416         ArraySet<String> permissionNames = null;
18417
18418         int opti = 0;
18419         while (opti < args.length) {
18420             String opt = args[opti];
18421             if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18422                 break;
18423             }
18424             opti++;
18425
18426             if ("-a".equals(opt)) {
18427                 // Right now we only know how to print all.
18428             } else if ("-h".equals(opt)) {
18429                 pw.println("Package manager dump options:");
18430                 pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18431                 pw.println("    --checkin: dump for a checkin");
18432                 pw.println("    -f: print details of intent filters");
18433                 pw.println("    -h: print this help");
18434                 pw.println("  cmd may be one of:");
18435                 pw.println("    l[ibraries]: list known shared libraries");
18436                 pw.println("    f[eatures]: list device features");
18437                 pw.println("    k[eysets]: print known keysets");
18438                 pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18439                 pw.println("    perm[issions]: dump permissions");
18440                 pw.println("    permission [name ...]: dump declaration and use of given permission");
18441                 pw.println("    pref[erred]: print preferred package settings");
18442                 pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18443                 pw.println("    prov[iders]: dump content providers");
18444                 pw.println("    p[ackages]: dump installed packages");
18445                 pw.println("    s[hared-users]: dump shared user IDs");
18446                 pw.println("    m[essages]: print collected runtime messages");
18447                 pw.println("    v[erifiers]: print package verifier info");
18448                 pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18449                 pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18450                 pw.println("    version: print database version info");
18451                 pw.println("    write: write current settings now");
18452                 pw.println("    installs: details about install sessions");
18453                 pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18454                 pw.println("    dexopt: dump dexopt state");
18455                 pw.println("    compiler-stats: dump compiler statistics");
18456                 pw.println("    <package.name>: info about given package");
18457                 return;
18458             } else if ("--checkin".equals(opt)) {
18459                 checkin = true;
18460             } else if ("-f".equals(opt)) {
18461                 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18462             } else {
18463                 pw.println("Unknown argument: " + opt + "; use -h for help");
18464             }
18465         }
18466
18467         // Is the caller requesting to dump a particular piece of data?
18468         if (opti < args.length) {
18469             String cmd = args[opti];
18470             opti++;
18471             // Is this a package name?
18472             if ("android".equals(cmd) || cmd.contains(".")) {
18473                 packageName = cmd;
18474                 // When dumping a single package, we always dump all of its
18475                 // filter information since the amount of data will be reasonable.
18476                 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18477             } else if ("check-permission".equals(cmd)) {
18478                 if (opti >= args.length) {
18479                     pw.println("Error: check-permission missing permission argument");
18480                     return;
18481                 }
18482                 String perm = args[opti];
18483                 opti++;
18484                 if (opti >= args.length) {
18485                     pw.println("Error: check-permission missing package argument");
18486                     return;
18487                 }
18488                 String pkg = args[opti];
18489                 opti++;
18490                 int user = UserHandle.getUserId(Binder.getCallingUid());
18491                 if (opti < args.length) {
18492                     try {
18493                         user = Integer.parseInt(args[opti]);
18494                     } catch (NumberFormatException e) {
18495                         pw.println("Error: check-permission user argument is not a number: "
18496                                 + args[opti]);
18497                         return;
18498                     }
18499                 }
18500                 pw.println(checkPermission(perm, pkg, user));
18501                 return;
18502             } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18503                 dumpState.setDump(DumpState.DUMP_LIBS);
18504             } else if ("f".equals(cmd) || "features".equals(cmd)) {
18505                 dumpState.setDump(DumpState.DUMP_FEATURES);
18506             } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18507                 if (opti >= args.length) {
18508                     dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18509                             | DumpState.DUMP_SERVICE_RESOLVERS
18510                             | DumpState.DUMP_RECEIVER_RESOLVERS
18511                             | DumpState.DUMP_CONTENT_RESOLVERS);
18512                 } else {
18513                     while (opti < args.length) {
18514                         String name = args[opti];
18515                         if ("a".equals(name) || "activity".equals(name)) {
18516                             dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18517                         } else if ("s".equals(name) || "service".equals(name)) {
18518                             dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18519                         } else if ("r".equals(name) || "receiver".equals(name)) {
18520                             dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18521                         } else if ("c".equals(name) || "content".equals(name)) {
18522                             dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18523                         } else {
18524                             pw.println("Error: unknown resolver table type: " + name);
18525                             return;
18526                         }
18527                         opti++;
18528                     }
18529                 }
18530             } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18531                 dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18532             } else if ("permission".equals(cmd)) {
18533                 if (opti >= args.length) {
18534                     pw.println("Error: permission requires permission name");
18535                     return;
18536                 }
18537                 permissionNames = new ArraySet<>();
18538                 while (opti < args.length) {
18539                     permissionNames.add(args[opti]);
18540                     opti++;
18541                 }
18542                 dumpState.setDump(DumpState.DUMP_PERMISSIONS
18543                         | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18544             } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18545                 dumpState.setDump(DumpState.DUMP_PREFERRED);
18546             } else if ("preferred-xml".equals(cmd)) {
18547                 dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18548                 if (opti < args.length && "--full".equals(args[opti])) {
18549                     fullPreferred = true;
18550                     opti++;
18551                 }
18552             } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18553                 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18554             } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18555                 dumpState.setDump(DumpState.DUMP_PACKAGES);
18556             } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18557                 dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18558             } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18559                 dumpState.setDump(DumpState.DUMP_PROVIDERS);
18560             } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18561                 dumpState.setDump(DumpState.DUMP_MESSAGES);
18562             } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18563                 dumpState.setDump(DumpState.DUMP_VERIFIERS);
18564             } else if ("i".equals(cmd) || "ifv".equals(cmd)
18565                     || "intent-filter-verifiers".equals(cmd)) {
18566                 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18567             } else if ("version".equals(cmd)) {
18568                 dumpState.setDump(DumpState.DUMP_VERSION);
18569             } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18570                 dumpState.setDump(DumpState.DUMP_KEYSETS);
18571             } else if ("installs".equals(cmd)) {
18572                 dumpState.setDump(DumpState.DUMP_INSTALLS);
18573             } else if ("frozen".equals(cmd)) {
18574                 dumpState.setDump(DumpState.DUMP_FROZEN);
18575             } else if ("dexopt".equals(cmd)) {
18576                 dumpState.setDump(DumpState.DUMP_DEXOPT);
18577             } else if ("compiler-stats".equals(cmd)) {
18578                 dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18579             } else if ("write".equals(cmd)) {
18580                 synchronized (mPackages) {
18581                     mSettings.writeLPr();
18582                     pw.println("Settings written.");
18583                     return;
18584                 }
18585             }
18586         }
18587
18588         if (checkin) {
18589             pw.println("vers,1");
18590         }
18591
18592         // reader
18593         synchronized (mPackages) {
18594             if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18595                 if (!checkin) {
18596                     if (dumpState.onTitlePrinted())
18597                         pw.println();
18598                     pw.println("Database versions:");
18599                     mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18600                 }
18601             }
18602
18603             if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18604                 if (!checkin) {
18605                     if (dumpState.onTitlePrinted())
18606                         pw.println();
18607                     pw.println("Verifiers:");
18608                     pw.print("  Required: ");
18609                     pw.print(mRequiredVerifierPackage);
18610                     pw.print(" (uid=");
18611                     pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18612                             UserHandle.USER_SYSTEM));
18613                     pw.println(")");
18614                 } else if (mRequiredVerifierPackage != null) {
18615                     pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18616                     pw.print(",");
18617                     pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18618                             UserHandle.USER_SYSTEM));
18619                 }
18620             }
18621
18622             if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18623                     packageName == null) {
18624                 if (mIntentFilterVerifierComponent != null) {
18625                     String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18626                     if (!checkin) {
18627                         if (dumpState.onTitlePrinted())
18628                             pw.println();
18629                         pw.println("Intent Filter Verifier:");
18630                         pw.print("  Using: ");
18631                         pw.print(verifierPackageName);
18632                         pw.print(" (uid=");
18633                         pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18634                                 UserHandle.USER_SYSTEM));
18635                         pw.println(")");
18636                     } else if (verifierPackageName != null) {
18637                         pw.print("ifv,"); pw.print(verifierPackageName);
18638                         pw.print(",");
18639                         pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18640                                 UserHandle.USER_SYSTEM));
18641                     }
18642                 } else {
18643                     pw.println();
18644                     pw.println("No Intent Filter Verifier available!");
18645                 }
18646             }
18647
18648             if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18649                 boolean printedHeader = false;
18650                 final Iterator<String> it = mSharedLibraries.keySet().iterator();
18651                 while (it.hasNext()) {
18652                     String name = it.next();
18653                     SharedLibraryEntry ent = mSharedLibraries.get(name);
18654                     if (!checkin) {
18655                         if (!printedHeader) {
18656                             if (dumpState.onTitlePrinted())
18657                                 pw.println();
18658                             pw.println("Libraries:");
18659                             printedHeader = true;
18660                         }
18661                         pw.print("  ");
18662                     } else {
18663                         pw.print("lib,");
18664                     }
18665                     pw.print(name);
18666                     if (!checkin) {
18667                         pw.print(" -> ");
18668                     }
18669                     if (ent.path != null) {
18670                         if (!checkin) {
18671                             pw.print("(jar) ");
18672                             pw.print(ent.path);
18673                         } else {
18674                             pw.print(",jar,");
18675                             pw.print(ent.path);
18676                         }
18677                     } else {
18678                         if (!checkin) {
18679                             pw.print("(apk) ");
18680                             pw.print(ent.apk);
18681                         } else {
18682                             pw.print(",apk,");
18683                             pw.print(ent.apk);
18684                         }
18685                     }
18686                     pw.println();
18687                 }
18688             }
18689
18690             if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18691                 if (dumpState.onTitlePrinted())
18692                     pw.println();
18693                 if (!checkin) {
18694                     pw.println("Features:");
18695                 }
18696
18697                 for (FeatureInfo feat : mAvailableFeatures.values()) {
18698                     if (checkin) {
18699                         pw.print("feat,");
18700                         pw.print(feat.name);
18701                         pw.print(",");
18702                         pw.println(feat.version);
18703                     } else {
18704                         pw.print("  ");
18705                         pw.print(feat.name);
18706                         if (feat.version > 0) {
18707                             pw.print(" version=");
18708                             pw.print(feat.version);
18709                         }
18710                         pw.println();
18711                     }
18712                 }
18713             }
18714
18715             if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18716                 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18717                         : "Activity Resolver Table:", "  ", packageName,
18718                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18719                     dumpState.setTitlePrinted(true);
18720                 }
18721             }
18722             if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18723                 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18724                         : "Receiver Resolver Table:", "  ", packageName,
18725                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18726                     dumpState.setTitlePrinted(true);
18727                 }
18728             }
18729             if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18730                 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18731                         : "Service Resolver Table:", "  ", packageName,
18732                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18733                     dumpState.setTitlePrinted(true);
18734                 }
18735             }
18736             if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18737                 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18738                         : "Provider Resolver Table:", "  ", packageName,
18739                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18740                     dumpState.setTitlePrinted(true);
18741                 }
18742             }
18743
18744             if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18745                 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18746                     PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18747                     int user = mSettings.mPreferredActivities.keyAt(i);
18748                     if (pir.dump(pw,
18749                             dumpState.getTitlePrinted()
18750                                 ? "\nPreferred Activities User " + user + ":"
18751                                 : "Preferred Activities User " + user + ":", "  ",
18752                             packageName, true, false)) {
18753                         dumpState.setTitlePrinted(true);
18754                     }
18755                 }
18756             }
18757
18758             if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18759                 pw.flush();
18760                 FileOutputStream fout = new FileOutputStream(fd);
18761                 BufferedOutputStream str = new BufferedOutputStream(fout);
18762                 XmlSerializer serializer = new FastXmlSerializer();
18763                 try {
18764                     serializer.setOutput(str, StandardCharsets.UTF_8.name());
18765                     serializer.startDocument(null, true);
18766                     serializer.setFeature(
18767                             "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18768                     mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18769                     serializer.endDocument();
18770                     serializer.flush();
18771                 } catch (IllegalArgumentException e) {
18772                     pw.println("Failed writing: " + e);
18773                 } catch (IllegalStateException e) {
18774                     pw.println("Failed writing: " + e);
18775                 } catch (IOException e) {
18776                     pw.println("Failed writing: " + e);
18777                 }
18778             }
18779
18780             if (!checkin
18781                     && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18782                     && packageName == null) {
18783                 pw.println();
18784                 int count = mSettings.mPackages.size();
18785                 if (count == 0) {
18786                     pw.println("No applications!");
18787                     pw.println();
18788                 } else {
18789                     final String prefix = "  ";
18790                     Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18791                     if (allPackageSettings.size() == 0) {
18792                         pw.println("No domain preferred apps!");
18793                         pw.println();
18794                     } else {
18795                         pw.println("App verification status:");
18796                         pw.println();
18797                         count = 0;
18798                         for (PackageSetting ps : allPackageSettings) {
18799                             IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18800                             if (ivi == null || ivi.getPackageName() == null) continue;
18801                             pw.println(prefix + "Package: " + ivi.getPackageName());
18802                             pw.println(prefix + "Domains: " + ivi.getDomainsString());
18803                             pw.println(prefix + "Status:  " + ivi.getStatusString());
18804                             pw.println();
18805                             count++;
18806                         }
18807                         if (count == 0) {
18808                             pw.println(prefix + "No app verification established.");
18809                             pw.println();
18810                         }
18811                         for (int userId : sUserManager.getUserIds()) {
18812                             pw.println("App linkages for user " + userId + ":");
18813                             pw.println();
18814                             count = 0;
18815                             for (PackageSetting ps : allPackageSettings) {
18816                                 final long status = ps.getDomainVerificationStatusForUser(userId);
18817                                 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18818                                     continue;
18819                                 }
18820                                 pw.println(prefix + "Package: " + ps.name);
18821                                 pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18822                                 String statusStr = IntentFilterVerificationInfo.
18823                                         getStatusStringFromValue(status);
18824                                 pw.println(prefix + "Status:  " + statusStr);
18825                                 pw.println();
18826                                 count++;
18827                             }
18828                             if (count == 0) {
18829                                 pw.println(prefix + "No configured app linkages.");
18830                                 pw.println();
18831                             }
18832                         }
18833                     }
18834                 }
18835             }
18836
18837             if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18838                 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18839                 if (packageName == null && permissionNames == null) {
18840                     for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18841                         if (iperm == 0) {
18842                             if (dumpState.onTitlePrinted())
18843                                 pw.println();
18844                             pw.println("AppOp Permissions:");
18845                         }
18846                         pw.print("  AppOp Permission ");
18847                         pw.print(mAppOpPermissionPackages.keyAt(iperm));
18848                         pw.println(":");
18849                         ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18850                         for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18851                             pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18852                         }
18853                     }
18854                 }
18855             }
18856
18857             if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18858                 boolean printedSomething = false;
18859                 for (PackageParser.Provider p : mProviders.mProviders.values()) {
18860                     if (packageName != null && !packageName.equals(p.info.packageName)) {
18861                         continue;
18862                     }
18863                     if (!printedSomething) {
18864                         if (dumpState.onTitlePrinted())
18865                             pw.println();
18866                         pw.println("Registered ContentProviders:");
18867                         printedSomething = true;
18868                     }
18869                     pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18870                     pw.print("    "); pw.println(p.toString());
18871                 }
18872                 printedSomething = false;
18873                 for (Map.Entry<String, PackageParser.Provider> entry :
18874                         mProvidersByAuthority.entrySet()) {
18875                     PackageParser.Provider p = entry.getValue();
18876                     if (packageName != null && !packageName.equals(p.info.packageName)) {
18877                         continue;
18878                     }
18879                     if (!printedSomething) {
18880                         if (dumpState.onTitlePrinted())
18881                             pw.println();
18882                         pw.println("ContentProvider Authorities:");
18883                         printedSomething = true;
18884                     }
18885                     pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18886                     pw.print("    "); pw.println(p.toString());
18887                     if (p.info != null && p.info.applicationInfo != null) {
18888                         final String appInfo = p.info.applicationInfo.toString();
18889                         pw.print("      applicationInfo="); pw.println(appInfo);
18890                     }
18891                 }
18892             }
18893
18894             if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18895                 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18896             }
18897
18898             if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18899                 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18900             }
18901
18902             if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18903                 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18904             }
18905
18906             if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18907                 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18908             }
18909
18910             if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18911                 // XXX should handle packageName != null by dumping only install data that
18912                 // the given package is involved with.
18913                 if (dumpState.onTitlePrinted()) pw.println();
18914                 mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18915             }
18916
18917             if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18918                 // XXX should handle packageName != null by dumping only install data that
18919                 // the given package is involved with.
18920                 if (dumpState.onTitlePrinted()) pw.println();
18921
18922                 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18923                 ipw.println();
18924                 ipw.println("Frozen packages:");
18925                 ipw.increaseIndent();
18926                 if (mFrozenPackages.size() == 0) {
18927                     ipw.println("(none)");
18928                 } else {
18929                     for (int i = 0; i < mFrozenPackages.size(); i++) {
18930                         ipw.println(mFrozenPackages.valueAt(i));
18931                     }
18932                 }
18933                 ipw.decreaseIndent();
18934             }
18935
18936             if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18937                 if (dumpState.onTitlePrinted()) pw.println();
18938                 dumpDexoptStateLPr(pw, packageName);
18939             }
18940
18941             if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
18942                 if (dumpState.onTitlePrinted()) pw.println();
18943                 dumpCompilerStatsLPr(pw, packageName);
18944             }
18945
18946             if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18947                 if (dumpState.onTitlePrinted()) pw.println();
18948                 mSettings.dumpReadMessagesLPr(pw, dumpState);
18949
18950                 pw.println();
18951                 pw.println("Package warning messages:");
18952                 BufferedReader in = null;
18953                 String line = null;
18954                 try {
18955                     in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18956                     while ((line = in.readLine()) != null) {
18957                         if (line.contains("ignored: updated version")) continue;
18958                         pw.println(line);
18959                     }
18960                 } catch (IOException ignored) {
18961                 } finally {
18962                     IoUtils.closeQuietly(in);
18963                 }
18964             }
18965
18966             if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18967                 BufferedReader in = null;
18968                 String line = null;
18969                 try {
18970                     in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18971                     while ((line = in.readLine()) != null) {
18972                         if (line.contains("ignored: updated version")) continue;
18973                         pw.print("msg,");
18974                         pw.println(line);
18975                     }
18976                 } catch (IOException ignored) {
18977                 } finally {
18978                     IoUtils.closeQuietly(in);
18979                 }
18980             }
18981         }
18982     }
18983
18984     private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18985         final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18986         ipw.println();
18987         ipw.println("Dexopt state:");
18988         ipw.increaseIndent();
18989         Collection<PackageParser.Package> packages = null;
18990         if (packageName != null) {
18991             PackageParser.Package targetPackage = mPackages.get(packageName);
18992             if (targetPackage != null) {
18993                 packages = Collections.singletonList(targetPackage);
18994             } else {
18995                 ipw.println("Unable to find package: " + packageName);
18996                 return;
18997             }
18998         } else {
18999             packages = mPackages.values();
19000         }
19001
19002         for (PackageParser.Package pkg : packages) {
19003             ipw.println("[" + pkg.packageName + "]");
19004             ipw.increaseIndent();
19005             mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
19006             ipw.decreaseIndent();
19007         }
19008     }
19009
19010     private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
19011         final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
19012         ipw.println();
19013         ipw.println("Compiler stats:");
19014         ipw.increaseIndent();
19015         Collection<PackageParser.Package> packages = null;
19016         if (packageName != null) {
19017             PackageParser.Package targetPackage = mPackages.get(packageName);
19018             if (targetPackage != null) {
19019                 packages = Collections.singletonList(targetPackage);
19020             } else {
19021                 ipw.println("Unable to find package: " + packageName);
19022                 return;
19023             }
19024         } else {
19025             packages = mPackages.values();
19026         }
19027
19028         for (PackageParser.Package pkg : packages) {
19029             ipw.println("[" + pkg.packageName + "]");
19030             ipw.increaseIndent();
19031
19032             CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
19033             if (stats == null) {
19034                 ipw.println("(No recorded stats)");
19035             } else {
19036                 stats.dump(ipw);
19037             }
19038             ipw.decreaseIndent();
19039         }
19040     }
19041
19042     private String dumpDomainString(String packageName) {
19043         List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
19044                 .getList();
19045         List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
19046
19047         ArraySet<String> result = new ArraySet<>();
19048         if (iviList.size() > 0) {
19049             for (IntentFilterVerificationInfo ivi : iviList) {
19050                 for (String host : ivi.getDomains()) {
19051                     result.add(host);
19052                 }
19053             }
19054         }
19055         if (filters != null && filters.size() > 0) {
19056             for (IntentFilter filter : filters) {
19057                 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
19058                         && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
19059                                 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
19060                     result.addAll(filter.getHostsList());
19061                 }
19062             }
19063         }
19064
19065         StringBuilder sb = new StringBuilder(result.size() * 16);
19066         for (String domain : result) {
19067             if (sb.length() > 0) sb.append(" ");
19068             sb.append(domain);
19069         }
19070         return sb.toString();
19071     }
19072
19073     // ------- apps on sdcard specific code -------
19074     static final boolean DEBUG_SD_INSTALL = false;
19075
19076     private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
19077
19078     private static final String SD_ENCRYPTION_ALGORITHM = "AES";
19079
19080     private boolean mMediaMounted = false;
19081
19082     static String getEncryptKey() {
19083         try {
19084             String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
19085                     SD_ENCRYPTION_KEYSTORE_NAME);
19086             if (sdEncKey == null) {
19087                 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
19088                         SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
19089                 if (sdEncKey == null) {
19090                     Slog.e(TAG, "Failed to create encryption keys");
19091                     return null;
19092                 }
19093             }
19094             return sdEncKey;
19095         } catch (NoSuchAlgorithmException nsae) {
19096             Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
19097             return null;
19098         } catch (IOException ioe) {
19099             Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
19100             return null;
19101         }
19102     }
19103
19104     /*
19105      * Update media status on PackageManager.
19106      */
19107     @Override
19108     public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
19109         int callingUid = Binder.getCallingUid();
19110         if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
19111             throw new SecurityException("Media status can only be updated by the system");
19112         }
19113         // reader; this apparently protects mMediaMounted, but should probably
19114         // be a different lock in that case.
19115         synchronized (mPackages) {
19116             Log.i(TAG, "Updating external media status from "
19117                     + (mMediaMounted ? "mounted" : "unmounted") + " to "
19118                     + (mediaStatus ? "mounted" : "unmounted"));
19119             if (DEBUG_SD_INSTALL)
19120                 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
19121                         + ", mMediaMounted=" + mMediaMounted);
19122             if (mediaStatus == mMediaMounted) {
19123                 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
19124                         : 0, -1);
19125                 mHandler.sendMessage(msg);
19126                 return;
19127             }
19128             mMediaMounted = mediaStatus;
19129         }
19130         // Queue up an async operation since the package installation may take a
19131         // little while.
19132         mHandler.post(new Runnable() {
19133             public void run() {
19134                 updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
19135             }
19136         });
19137     }
19138
19139     /**
19140      * Called by MountService when the initial ASECs to scan are available.
19141      * Should block until all the ASEC containers are finished being scanned.
19142      */
19143     public void scanAvailableAsecs() {
19144         updateExternalMediaStatusInner(true, false, false);
19145     }
19146
19147     /*
19148      * Collect information of applications on external media, map them against
19149      * existing containers and update information based on current mount status.
19150      * Please note that we always have to report status if reportStatus has been
19151      * set to true especially when unloading packages.
19152      */
19153     private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
19154             boolean externalStorage) {
19155         ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
19156         int[] uidArr = EmptyArray.INT;
19157
19158         final String[] list = PackageHelper.getSecureContainerList();
19159         if (ArrayUtils.isEmpty(list)) {
19160             Log.i(TAG, "No secure containers found");
19161         } else {
19162             // Process list of secure containers and categorize them
19163             // as active or stale based on their package internal state.
19164
19165             // reader
19166             synchronized (mPackages) {
19167                 for (String cid : list) {
19168                     // Leave stages untouched for now; installer service owns them
19169                     if (PackageInstallerService.isStageName(cid)) continue;
19170
19171                     if (DEBUG_SD_INSTALL)
19172                         Log.i(TAG, "Processing container " + cid);
19173                     String pkgName = getAsecPackageName(cid);
19174                     if (pkgName == null) {
19175                         Slog.i(TAG, "Found stale container " + cid + " with no package name");
19176                         continue;
19177                     }
19178                     if (DEBUG_SD_INSTALL)
19179                         Log.i(TAG, "Looking for pkg : " + pkgName);
19180
19181                     final PackageSetting ps = mSettings.mPackages.get(pkgName);
19182                     if (ps == null) {
19183                         Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
19184                         continue;
19185                     }
19186
19187                     /*
19188                      * Skip packages that are not external if we're unmounting
19189                      * external storage.
19190                      */
19191                     if (externalStorage && !isMounted && !isExternal(ps)) {
19192                         continue;
19193                     }
19194
19195                     final AsecInstallArgs args = new AsecInstallArgs(cid,
19196                             getAppDexInstructionSets(ps), ps.isForwardLocked());
19197                     // The package status is changed only if the code path
19198                     // matches between settings and the container id.
19199                     if (ps.codePathString != null
19200                             && ps.codePathString.startsWith(args.getCodePath())) {
19201                         if (DEBUG_SD_INSTALL) {
19202                             Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
19203                                     + " at code path: " + ps.codePathString);
19204                         }
19205
19206                         // We do have a valid package installed on sdcard
19207                         processCids.put(args, ps.codePathString);
19208                         final int uid = ps.appId;
19209                         if (uid != -1) {
19210                             uidArr = ArrayUtils.appendInt(uidArr, uid);
19211                         }
19212                     } else {
19213                         Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
19214                                 + ps.codePathString);
19215                     }
19216                 }
19217             }
19218
19219             Arrays.sort(uidArr);
19220         }
19221
19222         // Process packages with valid entries.
19223         if (isMounted) {
19224             if (DEBUG_SD_INSTALL)
19225                 Log.i(TAG, "Loading packages");
19226             loadMediaPackages(processCids, uidArr, externalStorage);
19227             startCleaningPackages();
19228             mInstallerService.onSecureContainersAvailable();
19229         } else {
19230             if (DEBUG_SD_INSTALL)
19231                 Log.i(TAG, "Unloading packages");
19232             unloadMediaPackages(processCids, uidArr, reportStatus);
19233         }
19234     }
19235
19236     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19237             ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
19238         final int size = infos.size();
19239         final String[] packageNames = new String[size];
19240         final int[] packageUids = new int[size];
19241         for (int i = 0; i < size; i++) {
19242             final ApplicationInfo info = infos.get(i);
19243             packageNames[i] = info.packageName;
19244             packageUids[i] = info.uid;
19245         }
19246         sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
19247                 finishedReceiver);
19248     }
19249
19250     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19251             ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19252         sendResourcesChangedBroadcast(mediaStatus, replacing,
19253                 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
19254     }
19255
19256     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
19257             String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
19258         int size = pkgList.length;
19259         if (size > 0) {
19260             // Send broadcasts here
19261             Bundle extras = new Bundle();
19262             extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
19263             if (uidArr != null) {
19264                 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
19265             }
19266             if (replacing) {
19267                 extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19268             }
19269             String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19270                     : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19271             sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19272         }
19273     }
19274
19275    /*
19276      * Look at potentially valid container ids from processCids If package
19277      * information doesn't match the one on record or package scanning fails,
19278      * the cid is added to list of removeCids. We currently don't delete stale
19279      * containers.
19280      */
19281     private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19282             boolean externalStorage) {
19283         ArrayList<String> pkgList = new ArrayList<String>();
19284         Set<AsecInstallArgs> keys = processCids.keySet();
19285
19286         for (AsecInstallArgs args : keys) {
19287             String codePath = processCids.get(args);
19288             if (DEBUG_SD_INSTALL)
19289                 Log.i(TAG, "Loading container : " + args.cid);
19290             int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19291             try {
19292                 // Make sure there are no container errors first.
19293                 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19294                     Slog.e(TAG, "Failed to mount cid : " + args.cid
19295                             + " when installing from sdcard");
19296                     continue;
19297                 }
19298                 // Check code path here.
19299                 if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19300                     Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19301                             + " does not match one in settings " + codePath);
19302                     continue;
19303                 }
19304                 // Parse package
19305                 int parseFlags = mDefParseFlags;
19306                 if (args.isExternalAsec()) {
19307                     parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19308                 }
19309                 if (args.isFwdLocked()) {
19310                     parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19311                 }
19312
19313                 synchronized (mInstallLock) {
19314                     PackageParser.Package pkg = null;
19315                     try {
19316                         // Sadly we don't know the package name yet to freeze it
19317                         pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19318                                 SCAN_IGNORE_FROZEN, 0, null);
19319                     } catch (PackageManagerException e) {
19320                         Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19321                     }
19322                     // Scan the package
19323                     if (pkg != null) {
19324                         /*
19325                          * TODO why is the lock being held? doPostInstall is
19326                          * called in other places without the lock. This needs
19327                          * to be straightened out.
19328                          */
19329                         // writer
19330                         synchronized (mPackages) {
19331                             retCode = PackageManager.INSTALL_SUCCEEDED;
19332                             pkgList.add(pkg.packageName);
19333                             // Post process args
19334                             args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19335                                     pkg.applicationInfo.uid);
19336                         }
19337                     } else {
19338                         Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19339                     }
19340                 }
19341
19342             } finally {
19343                 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19344                     Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19345                 }
19346             }
19347         }
19348         // writer
19349         synchronized (mPackages) {
19350             // If the platform SDK has changed since the last time we booted,
19351             // we need to re-grant app permission to catch any new ones that
19352             // appear. This is really a hack, and means that apps can in some
19353             // cases get permissions that the user didn't initially explicitly
19354             // allow... it would be nice to have some better way to handle
19355             // this situation.
19356             final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19357                     : mSettings.getInternalVersion();
19358             final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19359                     : StorageManager.UUID_PRIVATE_INTERNAL;
19360
19361             int updateFlags = UPDATE_PERMISSIONS_ALL;
19362             if (ver.sdkVersion != mSdkVersion) {
19363                 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19364                         + mSdkVersion + "; regranting permissions for external");
19365                 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19366             }
19367             updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19368
19369             // Yay, everything is now upgraded
19370             ver.forceCurrent();
19371
19372             // can downgrade to reader
19373             // Persist settings
19374             mSettings.writeLPr();
19375         }
19376         // Send a broadcast to let everyone know we are done processing
19377         if (pkgList.size() > 0) {
19378             sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19379         }
19380     }
19381
19382    /*
19383      * Utility method to unload a list of specified containers
19384      */
19385     private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19386         // Just unmount all valid containers.
19387         for (AsecInstallArgs arg : cidArgs) {
19388             synchronized (mInstallLock) {
19389                 arg.doPostDeleteLI(false);
19390            }
19391        }
19392    }
19393
19394     /*
19395      * Unload packages mounted on external media. This involves deleting package
19396      * data from internal structures, sending broadcasts about disabled packages,
19397      * gc'ing to free up references, unmounting all secure containers
19398      * corresponding to packages on external media, and posting a
19399      * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19400      * that we always have to post this message if status has been requested no
19401      * matter what.
19402      */
19403     private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19404             final boolean reportStatus) {
19405         if (DEBUG_SD_INSTALL)
19406             Log.i(TAG, "unloading media packages");
19407         ArrayList<String> pkgList = new ArrayList<String>();
19408         ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19409         final Set<AsecInstallArgs> keys = processCids.keySet();
19410         for (AsecInstallArgs args : keys) {
19411             String pkgName = args.getPackageName();
19412             if (DEBUG_SD_INSTALL)
19413                 Log.i(TAG, "Trying to unload pkg : " + pkgName);
19414             // Delete package internally
19415             PackageRemovedInfo outInfo = new PackageRemovedInfo();
19416             synchronized (mInstallLock) {
19417                 final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19418                 final boolean res;
19419                 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19420                         "unloadMediaPackages")) {
19421                     res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19422                             null);
19423                 }
19424                 if (res) {
19425                     pkgList.add(pkgName);
19426                 } else {
19427                     Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19428                     failedList.add(args);
19429                 }
19430             }
19431         }
19432
19433         // reader
19434         synchronized (mPackages) {
19435             // We didn't update the settings after removing each package;
19436             // write them now for all packages.
19437             mSettings.writeLPr();
19438         }
19439
19440         // We have to absolutely send UPDATED_MEDIA_STATUS only
19441         // after confirming that all the receivers processed the ordered
19442         // broadcast when packages get disabled, force a gc to clean things up.
19443         // and unload all the containers.
19444         if (pkgList.size() > 0) {
19445             sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19446                     new IIntentReceiver.Stub() {
19447                 public void performReceive(Intent intent, int resultCode, String data,
19448                         Bundle extras, boolean ordered, boolean sticky,
19449                         int sendingUser) throws RemoteException {
19450                     Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19451                             reportStatus ? 1 : 0, 1, keys);
19452                     mHandler.sendMessage(msg);
19453                 }
19454             });
19455         } else {
19456             Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19457                     keys);
19458             mHandler.sendMessage(msg);
19459         }
19460     }
19461
19462     private void loadPrivatePackages(final VolumeInfo vol) {
19463         mHandler.post(new Runnable() {
19464             @Override
19465             public void run() {
19466                 loadPrivatePackagesInner(vol);
19467             }
19468         });
19469     }
19470
19471     private void loadPrivatePackagesInner(VolumeInfo vol) {
19472         final String volumeUuid = vol.fsUuid;
19473         if (TextUtils.isEmpty(volumeUuid)) {
19474             Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19475             return;
19476         }
19477
19478         final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19479         final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19480         final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19481
19482         final VersionInfo ver;
19483         final List<PackageSetting> packages;
19484         synchronized (mPackages) {
19485             ver = mSettings.findOrCreateVersion(volumeUuid);
19486             packages = mSettings.getVolumePackagesLPr(volumeUuid);
19487         }
19488
19489         for (PackageSetting ps : packages) {
19490             freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19491             synchronized (mInstallLock) {
19492                 final PackageParser.Package pkg;
19493                 try {
19494                     pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19495                     loaded.add(pkg.applicationInfo);
19496
19497                 } catch (PackageManagerException e) {
19498                     Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19499                 }
19500
19501                 if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19502                     clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19503                             StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19504                                     | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19505                 }
19506             }
19507         }
19508
19509         // Reconcile app data for all started/unlocked users
19510         final StorageManager sm = mContext.getSystemService(StorageManager.class);
19511         final UserManager um = mContext.getSystemService(UserManager.class);
19512         UserManagerInternal umInternal = getUserManagerInternal();
19513         for (UserInfo user : um.getUsers()) {
19514             final int flags;
19515             if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19516                 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19517             } else if (umInternal.isUserRunning(user.id)) {
19518                 flags = StorageManager.FLAG_STORAGE_DE;
19519             } else {
19520                 continue;
19521             }
19522
19523             try {
19524                 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19525                 synchronized (mInstallLock) {
19526                     reconcileAppsDataLI(volumeUuid, user.id, flags);
19527                 }
19528             } catch (IllegalStateException e) {
19529                 // Device was probably ejected, and we'll process that event momentarily
19530                 Slog.w(TAG, "Failed to prepare storage: " + e);
19531             }
19532         }
19533
19534         synchronized (mPackages) {
19535             int updateFlags = UPDATE_PERMISSIONS_ALL;
19536             if (ver.sdkVersion != mSdkVersion) {
19537                 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19538                         + mSdkVersion + "; regranting permissions for " + volumeUuid);
19539                 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19540             }
19541             updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19542
19543             // Yay, everything is now upgraded
19544             ver.forceCurrent();
19545
19546             mSettings.writeLPr();
19547         }
19548
19549         for (PackageFreezer freezer : freezers) {
19550             freezer.close();
19551         }
19552
19553         if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19554         sendResourcesChangedBroadcast(true, false, loaded, null);
19555     }
19556
19557     private void unloadPrivatePackages(final VolumeInfo vol) {
19558         mHandler.post(new Runnable() {
19559             @Override
19560             public void run() {
19561                 unloadPrivatePackagesInner(vol);
19562             }
19563         });
19564     }
19565
19566     private void unloadPrivatePackagesInner(VolumeInfo vol) {
19567         final String volumeUuid = vol.fsUuid;
19568         if (TextUtils.isEmpty(volumeUuid)) {
19569             Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19570             return;
19571         }
19572
19573         final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19574         synchronized (mInstallLock) {
19575         synchronized (mPackages) {
19576             final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19577             for (PackageSetting ps : packages) {
19578                 if (ps.pkg == null) continue;
19579
19580                 final ApplicationInfo info = ps.pkg.applicationInfo;
19581                 final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19582                 final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19583
19584                 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19585                         "unloadPrivatePackagesInner")) {
19586                     if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19587                             false, null)) {
19588                         unloaded.add(info);
19589                     } else {
19590                         Slog.w(TAG, "Failed to unload " + ps.codePath);
19591                     }
19592                 }
19593
19594                 // Try very hard to release any references to this package
19595                 // so we don't risk the system server being killed due to
19596                 // open FDs
19597                 AttributeCache.instance().removePackage(ps.name);
19598             }
19599
19600             mSettings.writeLPr();
19601         }
19602         }
19603
19604         if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19605         sendResourcesChangedBroadcast(false, false, unloaded, null);
19606
19607         // Try very hard to release any references to this path so we don't risk
19608         // the system server being killed due to open FDs
19609         ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19610
19611         for (int i = 0; i < 3; i++) {
19612             System.gc();
19613             System.runFinalization();
19614         }
19615     }
19616
19617     /**
19618      * Prepare storage areas for given user on all mounted devices.
19619      */
19620     void prepareUserData(int userId, int userSerial, int flags) {
19621         synchronized (mInstallLock) {
19622             final StorageManager storage = mContext.getSystemService(StorageManager.class);
19623             for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19624                 final String volumeUuid = vol.getFsUuid();
19625                 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19626             }
19627         }
19628     }
19629
19630     private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19631             boolean allowRecover) {
19632         // Prepare storage and verify that serial numbers are consistent; if
19633         // there's a mismatch we need to destroy to avoid leaking data
19634         final StorageManager storage = mContext.getSystemService(StorageManager.class);
19635         try {
19636             storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19637
19638             if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19639                 UserManagerService.enforceSerialNumber(
19640                         Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19641                 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19642                     UserManagerService.enforceSerialNumber(
19643                             Environment.getDataSystemDeDirectory(userId), userSerial);
19644                 }
19645             }
19646             if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19647                 UserManagerService.enforceSerialNumber(
19648                         Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19649                 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19650                     UserManagerService.enforceSerialNumber(
19651                             Environment.getDataSystemCeDirectory(userId), userSerial);
19652                 }
19653             }
19654
19655             synchronized (mInstallLock) {
19656                 mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19657             }
19658         } catch (Exception e) {
19659             logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19660                     + " because we failed to prepare: " + e);
19661             destroyUserDataLI(volumeUuid, userId,
19662                     StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19663
19664             if (allowRecover) {
19665                 // Try one last time; if we fail again we're really in trouble
19666                 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19667             }
19668         }
19669     }
19670
19671     /**
19672      * Destroy storage areas for given user on all mounted devices.
19673      */
19674     void destroyUserData(int userId, int flags) {
19675         synchronized (mInstallLock) {
19676             final StorageManager storage = mContext.getSystemService(StorageManager.class);
19677             for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19678                 final String volumeUuid = vol.getFsUuid();
19679                 destroyUserDataLI(volumeUuid, userId, flags);
19680             }
19681         }
19682     }
19683
19684     private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19685         final StorageManager storage = mContext.getSystemService(StorageManager.class);
19686         try {
19687             // Clean up app data, profile data, and media data
19688             mInstaller.destroyUserData(volumeUuid, userId, flags);
19689
19690             // Clean up system data
19691             if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19692                 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19693                     FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19694                     FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19695                 }
19696                 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19697                     FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19698                 }
19699             }
19700
19701             // Data with special labels is now gone, so finish the job
19702             storage.destroyUserStorage(volumeUuid, userId, flags);
19703
19704         } catch (Exception e) {
19705             logCriticalInfo(Log.WARN,
19706                     "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19707         }
19708     }
19709
19710     /**
19711      * Examine all users present on given mounted volume, and destroy data
19712      * belonging to users that are no longer valid, or whose user ID has been
19713      * recycled.
19714      */
19715     private void reconcileUsers(String volumeUuid) {
19716         final List<File> files = new ArrayList<>();
19717         Collections.addAll(files, FileUtils
19718                 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19719         Collections.addAll(files, FileUtils
19720                 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19721         Collections.addAll(files, FileUtils
19722                 .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19723         Collections.addAll(files, FileUtils
19724                 .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19725         for (File file : files) {
19726             if (!file.isDirectory()) continue;
19727
19728             final int userId;
19729             final UserInfo info;
19730             try {
19731                 userId = Integer.parseInt(file.getName());
19732                 info = sUserManager.getUserInfo(userId);
19733             } catch (NumberFormatException e) {
19734                 Slog.w(TAG, "Invalid user directory " + file);
19735                 continue;
19736             }
19737
19738             boolean destroyUser = false;
19739             if (info == null) {
19740                 logCriticalInfo(Log.WARN, "Destroying user directory " + file
19741                         + " because no matching user was found");
19742                 destroyUser = true;
19743             } else if (!mOnlyCore) {
19744                 try {
19745                     UserManagerService.enforceSerialNumber(file, info.serialNumber);
19746                 } catch (IOException e) {
19747                     logCriticalInfo(Log.WARN, "Destroying user directory " + file
19748                             + " because we failed to enforce serial number: " + e);
19749                     destroyUser = true;
19750                 }
19751             }
19752
19753             if (destroyUser) {
19754                 synchronized (mInstallLock) {
19755                     destroyUserDataLI(volumeUuid, userId,
19756                             StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19757                 }
19758             }
19759         }
19760     }
19761
19762     private void assertPackageKnown(String volumeUuid, String packageName)
19763             throws PackageManagerException {
19764         synchronized (mPackages) {
19765             // Normalize package name to handle renamed packages
19766             packageName = normalizePackageNameLPr(packageName);
19767
19768             final PackageSetting ps = mSettings.mPackages.get(packageName);
19769             if (ps == null) {
19770                 throw new PackageManagerException("Package " + packageName + " is unknown");
19771             } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19772                 throw new PackageManagerException(
19773                         "Package " + packageName + " found on unknown volume " + volumeUuid
19774                                 + "; expected volume " + ps.volumeUuid);
19775             }
19776         }
19777     }
19778
19779     private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19780             throws PackageManagerException {
19781         synchronized (mPackages) {
19782             // Normalize package name to handle renamed packages
19783             packageName = normalizePackageNameLPr(packageName);
19784
19785             final PackageSetting ps = mSettings.mPackages.get(packageName);
19786             if (ps == null) {
19787                 throw new PackageManagerException("Package " + packageName + " is unknown");
19788             } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19789                 throw new PackageManagerException(
19790                         "Package " + packageName + " found on unknown volume " + volumeUuid
19791                                 + "; expected volume " + ps.volumeUuid);
19792             } else if (!ps.getInstalled(userId)) {
19793                 throw new PackageManagerException(
19794                         "Package " + packageName + " not installed for user " + userId);
19795             }
19796         }
19797     }
19798
19799     /**
19800      * Examine all apps present on given mounted volume, and destroy apps that
19801      * aren't expected, either due to uninstallation or reinstallation on
19802      * another volume.
19803      */
19804     private void reconcileApps(String volumeUuid) {
19805         final File[] files = FileUtils
19806                 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19807         for (File file : files) {
19808             final boolean isPackage = (isApkFile(file) || file.isDirectory())
19809                     && !PackageInstallerService.isStageName(file.getName());
19810             if (!isPackage) {
19811                 // Ignore entries which are not packages
19812                 continue;
19813             }
19814
19815             try {
19816                 final PackageLite pkg = PackageParser.parsePackageLite(file,
19817                         PackageParser.PARSE_MUST_BE_APK);
19818                 assertPackageKnown(volumeUuid, pkg.packageName);
19819
19820             } catch (PackageParserException | PackageManagerException e) {
19821                 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19822                 synchronized (mInstallLock) {
19823                     removeCodePathLI(file);
19824                 }
19825             }
19826         }
19827     }
19828
19829     /**
19830      * Reconcile all app data for the given user.
19831      * <p>
19832      * Verifies that directories exist and that ownership and labeling is
19833      * correct for all installed apps on all mounted volumes.
19834      */
19835     void reconcileAppsData(int userId, int flags) {
19836         final StorageManager storage = mContext.getSystemService(StorageManager.class);
19837         for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19838             final String volumeUuid = vol.getFsUuid();
19839             synchronized (mInstallLock) {
19840                 reconcileAppsDataLI(volumeUuid, userId, flags);
19841             }
19842         }
19843     }
19844
19845     /**
19846      * Reconcile all app data on given mounted volume.
19847      * <p>
19848      * Destroys app data that isn't expected, either due to uninstallation or
19849      * reinstallation on another volume.
19850      * <p>
19851      * Verifies that directories exist and that ownership and labeling is
19852      * correct for all installed apps.
19853      */
19854     private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19855         Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19856                 + Integer.toHexString(flags));
19857
19858         final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19859         final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19860
19861         // First look for stale data that doesn't belong, and check if things
19862         // have changed since we did our last restorecon
19863         if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19864             if (StorageManager.isFileEncryptedNativeOrEmulated()
19865                     && !StorageManager.isUserKeyUnlocked(userId)) {
19866                 throw new RuntimeException(
19867                         "Yikes, someone asked us to reconcile CE storage while " + userId
19868                                 + " was still locked; this would have caused massive data loss!");
19869             }
19870
19871             final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19872             for (File file : files) {
19873                 final String packageName = file.getName();
19874                 try {
19875                     assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19876                 } catch (PackageManagerException e) {
19877                     logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19878                     try {
19879                         mInstaller.destroyAppData(volumeUuid, packageName, userId,
19880                                 StorageManager.FLAG_STORAGE_CE, 0);
19881                     } catch (InstallerException e2) {
19882                         logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19883                     }
19884                 }
19885             }
19886         }
19887         if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19888             final File[] files = FileUtils.listFilesOrEmpty(deDir);
19889             for (File file : files) {
19890                 final String packageName = file.getName();
19891                 try {
19892                     assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19893                 } catch (PackageManagerException e) {
19894                     logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19895                     try {
19896                         mInstaller.destroyAppData(volumeUuid, packageName, userId,
19897                                 StorageManager.FLAG_STORAGE_DE, 0);
19898                     } catch (InstallerException e2) {
19899                         logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19900                     }
19901                 }
19902             }
19903         }
19904
19905         // Ensure that data directories are ready to roll for all packages
19906         // installed for this volume and user
19907         final List<PackageSetting> packages;
19908         synchronized (mPackages) {
19909             packages = mSettings.getVolumePackagesLPr(volumeUuid);
19910         }
19911         int preparedCount = 0;
19912         for (PackageSetting ps : packages) {
19913             final String packageName = ps.name;
19914             if (ps.pkg == null) {
19915                 Slog.w(TAG, "Odd, missing scanned package " + packageName);
19916                 // TODO: might be due to legacy ASEC apps; we should circle back
19917                 // and reconcile again once they're scanned
19918                 continue;
19919             }
19920
19921             if (ps.getInstalled(userId)) {
19922                 prepareAppDataLIF(ps.pkg, userId, flags);
19923
19924                 if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19925                     // We may have just shuffled around app data directories, so
19926                     // prepare them one more time
19927                     prepareAppDataLIF(ps.pkg, userId, flags);
19928                 }
19929
19930                 preparedCount++;
19931             }
19932         }
19933
19934         Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
19935     }
19936
19937     /**
19938      * Prepare app data for the given app just after it was installed or
19939      * upgraded. This method carefully only touches users that it's installed
19940      * for, and it forces a restorecon to handle any seinfo changes.
19941      * <p>
19942      * Verifies that directories exist and that ownership and labeling is
19943      * correct for all installed apps. If there is an ownership mismatch, it
19944      * will try recovering system apps by wiping data; third-party app data is
19945      * left intact.
19946      * <p>
19947      * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19948      */
19949     private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19950         final PackageSetting ps;
19951         synchronized (mPackages) {
19952             ps = mSettings.mPackages.get(pkg.packageName);
19953             mSettings.writeKernelMappingLPr(ps);
19954         }
19955
19956         final UserManager um = mContext.getSystemService(UserManager.class);
19957         UserManagerInternal umInternal = getUserManagerInternal();
19958         for (UserInfo user : um.getUsers()) {
19959             final int flags;
19960             if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19961                 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19962             } else if (umInternal.isUserRunning(user.id)) {
19963                 flags = StorageManager.FLAG_STORAGE_DE;
19964             } else {
19965                 continue;
19966             }
19967
19968             if (ps.getInstalled(user.id)) {
19969                 // TODO: when user data is locked, mark that we're still dirty
19970                 prepareAppDataLIF(pkg, user.id, flags);
19971             }
19972         }
19973     }
19974
19975     /**
19976      * Prepare app data for the given app.
19977      * <p>
19978      * Verifies that directories exist and that ownership and labeling is
19979      * correct for all installed apps. If there is an ownership mismatch, this
19980      * will try recovering system apps by wiping data; third-party app data is
19981      * left intact.
19982      */
19983     private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
19984         if (pkg == null) {
19985             Slog.wtf(TAG, "Package was null!", new Throwable());
19986             return;
19987         }
19988         prepareAppDataLeafLIF(pkg, userId, flags);
19989         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19990         for (int i = 0; i < childCount; i++) {
19991             prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
19992         }
19993     }
19994
19995     private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19996         if (DEBUG_APP_DATA) {
19997             Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19998                     + Integer.toHexString(flags));
19999         }
20000
20001         final String volumeUuid = pkg.volumeUuid;
20002         final String packageName = pkg.packageName;
20003         final ApplicationInfo app = pkg.applicationInfo;
20004         final int appId = UserHandle.getAppId(app.uid);
20005
20006         Preconditions.checkNotNull(app.seinfo);
20007
20008         try {
20009             mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20010                     appId, app.seinfo, app.targetSdkVersion);
20011         } catch (InstallerException e) {
20012             if (app.isSystemApp()) {
20013                 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
20014                         + ", but trying to recover: " + e);
20015                 destroyAppDataLeafLIF(pkg, userId, flags);
20016                 try {
20017                     mInstaller.createAppData(volumeUuid, packageName, userId, flags,
20018                             appId, app.seinfo, app.targetSdkVersion);
20019                     logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
20020                 } catch (InstallerException e2) {
20021                     logCriticalInfo(Log.DEBUG, "Recovery failed!");
20022                 }
20023             } else {
20024                 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
20025             }
20026         }
20027
20028         if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20029             try {
20030                 // CE storage is unlocked right now, so read out the inode and
20031                 // remember for use later when it's locked
20032                 // TODO: mark this structure as dirty so we persist it!
20033                 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
20034                         StorageManager.FLAG_STORAGE_CE);
20035                 synchronized (mPackages) {
20036                     final PackageSetting ps = mSettings.mPackages.get(packageName);
20037                     if (ps != null) {
20038                         ps.setCeDataInode(ceDataInode, userId);
20039                     }
20040                 }
20041             } catch (InstallerException e) {
20042                 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
20043             }
20044         }
20045
20046         prepareAppDataContentsLeafLIF(pkg, userId, flags);
20047     }
20048
20049     private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
20050         if (pkg == null) {
20051             Slog.wtf(TAG, "Package was null!", new Throwable());
20052             return;
20053         }
20054         prepareAppDataContentsLeafLIF(pkg, userId, flags);
20055         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
20056         for (int i = 0; i < childCount; i++) {
20057             prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
20058         }
20059     }
20060
20061     private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
20062         final String volumeUuid = pkg.volumeUuid;
20063         final String packageName = pkg.packageName;
20064         final ApplicationInfo app = pkg.applicationInfo;
20065
20066         if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
20067             // Create a native library symlink only if we have native libraries
20068             // and if the native libraries are 32 bit libraries. We do not provide
20069             // this symlink for 64 bit libraries.
20070             if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
20071                 final String nativeLibPath = app.nativeLibraryDir;
20072                 try {
20073                     mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
20074                             nativeLibPath, userId);
20075                 } catch (InstallerException e) {
20076                     Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
20077                 }
20078             }
20079         }
20080     }
20081
20082     /**
20083      * For system apps on non-FBE devices, this method migrates any existing
20084      * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
20085      * requested by the app.
20086      */
20087     private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
20088         if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
20089                 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
20090             final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
20091                     ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
20092             try {
20093                 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
20094                         storageTarget);
20095             } catch (InstallerException e) {
20096                 logCriticalInfo(Log.WARN,
20097                         "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
20098             }
20099             return true;
20100         } else {
20101             return false;
20102         }
20103     }
20104
20105     public PackageFreezer freezePackage(String packageName, String killReason) {
20106         return freezePackage(packageName, UserHandle.USER_ALL, killReason);
20107     }
20108
20109     public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
20110         return new PackageFreezer(packageName, userId, killReason);
20111     }
20112
20113     public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
20114             String killReason) {
20115         return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
20116     }
20117
20118     public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
20119             String killReason) {
20120         if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
20121             return new PackageFreezer();
20122         } else {
20123             return freezePackage(packageName, userId, killReason);
20124         }
20125     }
20126
20127     public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
20128             String killReason) {
20129         return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
20130     }
20131
20132     public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
20133             String killReason) {
20134         if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
20135             return new PackageFreezer();
20136         } else {
20137             return freezePackage(packageName, userId, killReason);
20138         }
20139     }
20140
20141     /**
20142      * Class that freezes and kills the given package upon creation, and
20143      * unfreezes it upon closing. This is typically used when doing surgery on
20144      * app code/data to prevent the app from running while you're working.
20145      */
20146     private class PackageFreezer implements AutoCloseable {
20147         private final String mPackageName;
20148         private final PackageFreezer[] mChildren;
20149
20150         private final boolean mWeFroze;
20151
20152         private final AtomicBoolean mClosed = new AtomicBoolean();
20153         private final CloseGuard mCloseGuard = CloseGuard.get();
20154
20155         /**
20156          * Create and return a stub freezer that doesn't actually do anything,
20157          * typically used when someone requested
20158          * {@link PackageManager#INSTALL_DONT_KILL_APP} or
20159          * {@link PackageManager#DELETE_DONT_KILL_APP}.
20160          */
20161         public PackageFreezer() {
20162             mPackageName = null;
20163             mChildren = null;
20164             mWeFroze = false;
20165             mCloseGuard.open("close");
20166         }
20167
20168         public PackageFreezer(String packageName, int userId, String killReason) {
20169             synchronized (mPackages) {
20170                 mPackageName = packageName;
20171                 mWeFroze = mFrozenPackages.add(mPackageName);
20172
20173                 final PackageSetting ps = mSettings.mPackages.get(mPackageName);
20174                 if (ps != null) {
20175                     killApplication(ps.name, ps.appId, userId, killReason);
20176                 }
20177
20178                 final PackageParser.Package p = mPackages.get(packageName);
20179                 if (p != null && p.childPackages != null) {
20180                     final int N = p.childPackages.size();
20181                     mChildren = new PackageFreezer[N];
20182                     for (int i = 0; i < N; i++) {
20183                         mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
20184                                 userId, killReason);
20185                     }
20186                 } else {
20187                     mChildren = null;
20188                 }
20189             }
20190             mCloseGuard.open("close");
20191         }
20192
20193         @Override
20194         protected void finalize() throws Throwable {
20195             try {
20196                 mCloseGuard.warnIfOpen();
20197                 close();
20198             } finally {
20199                 super.finalize();
20200             }
20201         }
20202
20203         @Override
20204         public void close() {
20205             mCloseGuard.close();
20206             if (mClosed.compareAndSet(false, true)) {
20207                 synchronized (mPackages) {
20208                     if (mWeFroze) {
20209                         mFrozenPackages.remove(mPackageName);
20210                     }
20211
20212                     if (mChildren != null) {
20213                         for (PackageFreezer freezer : mChildren) {
20214                             freezer.close();
20215                         }
20216                     }
20217                 }
20218             }
20219         }
20220     }
20221
20222     /**
20223      * Verify that given package is currently frozen.
20224      */
20225     private void checkPackageFrozen(String packageName) {
20226         synchronized (mPackages) {
20227             if (!mFrozenPackages.contains(packageName)) {
20228                 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
20229             }
20230         }
20231     }
20232
20233     @Override
20234     public int movePackage(final String packageName, final String volumeUuid) {
20235         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20236
20237         final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
20238         final int moveId = mNextMoveId.getAndIncrement();
20239         mHandler.post(new Runnable() {
20240             @Override
20241             public void run() {
20242                 try {
20243                     movePackageInternal(packageName, volumeUuid, moveId, user);
20244                 } catch (PackageManagerException e) {
20245                     Slog.w(TAG, "Failed to move " + packageName, e);
20246                     mMoveCallbacks.notifyStatusChanged(moveId,
20247                             PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20248                 }
20249             }
20250         });
20251         return moveId;
20252     }
20253
20254     private void movePackageInternal(final String packageName, final String volumeUuid,
20255             final int moveId, UserHandle user) throws PackageManagerException {
20256         final StorageManager storage = mContext.getSystemService(StorageManager.class);
20257         final PackageManager pm = mContext.getPackageManager();
20258
20259         final boolean currentAsec;
20260         final String currentVolumeUuid;
20261         final File codeFile;
20262         final String installerPackageName;
20263         final String packageAbiOverride;
20264         final int appId;
20265         final String seinfo;
20266         final String label;
20267         final int targetSdkVersion;
20268         final PackageFreezer freezer;
20269         final int[] installedUserIds;
20270
20271         // reader
20272         synchronized (mPackages) {
20273             final PackageParser.Package pkg = mPackages.get(packageName);
20274             final PackageSetting ps = mSettings.mPackages.get(packageName);
20275             if (pkg == null || ps == null) {
20276                 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20277             }
20278
20279             if (pkg.applicationInfo.isSystemApp()) {
20280                 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20281                         "Cannot move system application");
20282             }
20283
20284             if (pkg.applicationInfo.isExternalAsec()) {
20285                 currentAsec = true;
20286                 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20287             } else if (pkg.applicationInfo.isForwardLocked()) {
20288                 currentAsec = true;
20289                 currentVolumeUuid = "forward_locked";
20290             } else {
20291                 currentAsec = false;
20292                 currentVolumeUuid = ps.volumeUuid;
20293
20294                 final File probe = new File(pkg.codePath);
20295                 final File probeOat = new File(probe, "oat");
20296                 if (!probe.isDirectory() || !probeOat.isDirectory()) {
20297                     throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20298                             "Move only supported for modern cluster style installs");
20299                 }
20300             }
20301
20302             if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20303                 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20304                         "Package already moved to " + volumeUuid);
20305             }
20306             if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20307                 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20308                         "Device admin cannot be moved");
20309             }
20310
20311             if (mFrozenPackages.contains(packageName)) {
20312                 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20313                         "Failed to move already frozen package");
20314             }
20315
20316             codeFile = new File(pkg.codePath);
20317             installerPackageName = ps.installerPackageName;
20318             packageAbiOverride = ps.cpuAbiOverrideString;
20319             appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20320             seinfo = pkg.applicationInfo.seinfo;
20321             label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20322             targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20323             freezer = freezePackage(packageName, "movePackageInternal");
20324             installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20325         }
20326
20327         final Bundle extras = new Bundle();
20328         extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20329         extras.putString(Intent.EXTRA_TITLE, label);
20330         mMoveCallbacks.notifyCreated(moveId, extras);
20331
20332         int installFlags;
20333         final boolean moveCompleteApp;
20334         final File measurePath;
20335
20336         if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20337             installFlags = INSTALL_INTERNAL;
20338             moveCompleteApp = !currentAsec;
20339             measurePath = Environment.getDataAppDirectory(volumeUuid);
20340         } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20341             installFlags = INSTALL_EXTERNAL;
20342             moveCompleteApp = false;
20343             measurePath = storage.getPrimaryPhysicalVolume().getPath();
20344         } else {
20345             final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20346             if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20347                     || !volume.isMountedWritable()) {
20348                 freezer.close();
20349                 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20350                         "Move location not mounted private volume");
20351             }
20352
20353             Preconditions.checkState(!currentAsec);
20354
20355             installFlags = INSTALL_INTERNAL;
20356             moveCompleteApp = true;
20357             measurePath = Environment.getDataAppDirectory(volumeUuid);
20358         }
20359
20360         final PackageStats stats = new PackageStats(null, -1);
20361         synchronized (mInstaller) {
20362             for (int userId : installedUserIds) {
20363                 if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20364                     freezer.close();
20365                     throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20366                             "Failed to measure package size");
20367                 }
20368             }
20369         }
20370
20371         if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20372                 + stats.dataSize);
20373
20374         final long startFreeBytes = measurePath.getFreeSpace();
20375         final long sizeBytes;
20376         if (moveCompleteApp) {
20377             sizeBytes = stats.codeSize + stats.dataSize;
20378         } else {
20379             sizeBytes = stats.codeSize;
20380         }
20381
20382         if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20383             freezer.close();
20384             throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20385                     "Not enough free space to move");
20386         }
20387
20388         mMoveCallbacks.notifyStatusChanged(moveId, 10);
20389
20390         final CountDownLatch installedLatch = new CountDownLatch(1);
20391         final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20392             @Override
20393             public void onUserActionRequired(Intent intent) throws RemoteException {
20394                 throw new IllegalStateException();
20395             }
20396
20397             @Override
20398             public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20399                     Bundle extras) throws RemoteException {
20400                 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20401                         + PackageManager.installStatusToString(returnCode, msg));
20402
20403                 installedLatch.countDown();
20404                 freezer.close();
20405
20406                 final int status = PackageManager.installStatusToPublicStatus(returnCode);
20407                 switch (status) {
20408                     case PackageInstaller.STATUS_SUCCESS:
20409                         mMoveCallbacks.notifyStatusChanged(moveId,
20410                                 PackageManager.MOVE_SUCCEEDED);
20411                         break;
20412                     case PackageInstaller.STATUS_FAILURE_STORAGE:
20413                         mMoveCallbacks.notifyStatusChanged(moveId,
20414                                 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20415                         break;
20416                     default:
20417                         mMoveCallbacks.notifyStatusChanged(moveId,
20418                                 PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20419                         break;
20420                 }
20421             }
20422         };
20423
20424         final MoveInfo move;
20425         if (moveCompleteApp) {
20426             // Kick off a thread to report progress estimates
20427             new Thread() {
20428                 @Override
20429                 public void run() {
20430                     while (true) {
20431                         try {
20432                             if (installedLatch.await(1, TimeUnit.SECONDS)) {
20433                                 break;
20434                             }
20435                         } catch (InterruptedException ignored) {
20436                         }
20437
20438                         final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20439                         final int progress = 10 + (int) MathUtils.constrain(
20440                                 ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20441                         mMoveCallbacks.notifyStatusChanged(moveId, progress);
20442                     }
20443                 }
20444             }.start();
20445
20446             final String dataAppName = codeFile.getName();
20447             move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20448                     dataAppName, appId, seinfo, targetSdkVersion);
20449         } else {
20450             move = null;
20451         }
20452
20453         installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20454
20455         final Message msg = mHandler.obtainMessage(INIT_COPY);
20456         final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20457         final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20458                 installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20459                 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20460         params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20461         msg.obj = params;
20462
20463         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20464                 System.identityHashCode(msg.obj));
20465         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20466                 System.identityHashCode(msg.obj));
20467
20468         mHandler.sendMessage(msg);
20469     }
20470
20471     @Override
20472     public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20473         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20474
20475         final int realMoveId = mNextMoveId.getAndIncrement();
20476         final Bundle extras = new Bundle();
20477         extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20478         mMoveCallbacks.notifyCreated(realMoveId, extras);
20479
20480         final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20481             @Override
20482             public void onCreated(int moveId, Bundle extras) {
20483                 // Ignored
20484             }
20485
20486             @Override
20487             public void onStatusChanged(int moveId, int status, long estMillis) {
20488                 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20489             }
20490         };
20491
20492         final StorageManager storage = mContext.getSystemService(StorageManager.class);
20493         storage.setPrimaryStorageUuid(volumeUuid, callback);
20494         return realMoveId;
20495     }
20496
20497     @Override
20498     public int getMoveStatus(int moveId) {
20499         mContext.enforceCallingOrSelfPermission(
20500                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20501         return mMoveCallbacks.mLastStatus.get(moveId);
20502     }
20503
20504     @Override
20505     public void registerMoveCallback(IPackageMoveObserver callback) {
20506         mContext.enforceCallingOrSelfPermission(
20507                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20508         mMoveCallbacks.register(callback);
20509     }
20510
20511     @Override
20512     public void unregisterMoveCallback(IPackageMoveObserver callback) {
20513         mContext.enforceCallingOrSelfPermission(
20514                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20515         mMoveCallbacks.unregister(callback);
20516     }
20517
20518     @Override
20519     public boolean setInstallLocation(int loc) {
20520         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20521                 null);
20522         if (getInstallLocation() == loc) {
20523             return true;
20524         }
20525         if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20526                 || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20527             android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20528                     android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20529             return true;
20530         }
20531         return false;
20532    }
20533
20534     @Override
20535     public int getInstallLocation() {
20536         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20537                 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20538                 PackageHelper.APP_INSTALL_AUTO);
20539     }
20540
20541     /** Called by UserManagerService */
20542     void cleanUpUser(UserManagerService userManager, int userHandle) {
20543         synchronized (mPackages) {
20544             mDirtyUsers.remove(userHandle);
20545             mUserNeedsBadging.delete(userHandle);
20546             mSettings.removeUserLPw(userHandle);
20547             mPendingBroadcasts.remove(userHandle);
20548             mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20549             removeUnusedPackagesLPw(userManager, userHandle);
20550         }
20551     }
20552
20553     /**
20554      * We're removing userHandle and would like to remove any downloaded packages
20555      * that are no longer in use by any other user.
20556      * @param userHandle the user being removed
20557      */
20558     private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20559         final boolean DEBUG_CLEAN_APKS = false;
20560         int [] users = userManager.getUserIds();
20561         Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20562         while (psit.hasNext()) {
20563             PackageSetting ps = psit.next();
20564             if (ps.pkg == null) {
20565                 continue;
20566             }
20567             final String packageName = ps.pkg.packageName;
20568             // Skip over if system app
20569             if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20570                 continue;
20571             }
20572             if (DEBUG_CLEAN_APKS) {
20573                 Slog.i(TAG, "Checking package " + packageName);
20574             }
20575             boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20576             if (keep) {
20577                 if (DEBUG_CLEAN_APKS) {
20578                     Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20579                 }
20580             } else {
20581                 for (int i = 0; i < users.length; i++) {
20582                     if (users[i] != userHandle && ps.getInstalled(users[i])) {
20583                         keep = true;
20584                         if (DEBUG_CLEAN_APKS) {
20585                             Slog.i(TAG, "  Keeping package " + packageName + " for user "
20586                                     + users[i]);
20587                         }
20588                         break;
20589                     }
20590                 }
20591             }
20592             if (!keep) {
20593                 if (DEBUG_CLEAN_APKS) {
20594                     Slog.i(TAG, "  Removing package " + packageName);
20595                 }
20596                 mHandler.post(new Runnable() {
20597                     public void run() {
20598                         deletePackageX(packageName, userHandle, 0);
20599                     } //end run
20600                 });
20601             }
20602         }
20603     }
20604
20605     /** Called by UserManagerService */
20606     void createNewUser(int userId) {
20607         synchronized (mInstallLock) {
20608             mSettings.createNewUserLI(this, mInstaller, userId);
20609         }
20610         synchronized (mPackages) {
20611             scheduleWritePackageRestrictionsLocked(userId);
20612             scheduleWritePackageListLocked(userId);
20613             applyFactoryDefaultBrowserLPw(userId);
20614             primeDomainVerificationsLPw(userId);
20615         }
20616     }
20617
20618     void onNewUserCreated(final int userId) {
20619         mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20620         // If permission review for legacy apps is required, we represent
20621         // dagerous permissions for such apps as always granted runtime
20622         // permissions to keep per user flag state whether review is needed.
20623         // Hence, if a new user is added we have to propagate dangerous
20624         // permission grants for these legacy apps.
20625         if (mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) {
20626             updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20627                     | UPDATE_PERMISSIONS_REPLACE_ALL);
20628         }
20629     }
20630
20631     @Override
20632     public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20633         mContext.enforceCallingOrSelfPermission(
20634                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20635                 "Only package verification agents can read the verifier device identity");
20636
20637         synchronized (mPackages) {
20638             return mSettings.getVerifierDeviceIdentityLPw();
20639         }
20640     }
20641
20642     @Override
20643     public void setPermissionEnforced(String permission, boolean enforced) {
20644         // TODO: Now that we no longer change GID for storage, this should to away.
20645         mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20646                 "setPermissionEnforced");
20647         if (READ_EXTERNAL_STORAGE.equals(permission)) {
20648             synchronized (mPackages) {
20649                 if (mSettings.mReadExternalStorageEnforced == null
20650                         || mSettings.mReadExternalStorageEnforced != enforced) {
20651                     mSettings.mReadExternalStorageEnforced = enforced;
20652                     mSettings.writeLPr();
20653                 }
20654             }
20655             // kill any non-foreground processes so we restart them and
20656             // grant/revoke the GID.
20657             final IActivityManager am = ActivityManagerNative.getDefault();
20658             if (am != null) {
20659                 final long token = Binder.clearCallingIdentity();
20660                 try {
20661                     am.killProcessesBelowForeground("setPermissionEnforcement");
20662                 } catch (RemoteException e) {
20663                 } finally {
20664                     Binder.restoreCallingIdentity(token);
20665                 }
20666             }
20667         } else {
20668             throw new IllegalArgumentException("No selective enforcement for " + permission);
20669         }
20670     }
20671
20672     @Override
20673     @Deprecated
20674     public boolean isPermissionEnforced(String permission) {
20675         return true;
20676     }
20677
20678     @Override
20679     public boolean isStorageLow() {
20680         final long token = Binder.clearCallingIdentity();
20681         try {
20682             final DeviceStorageMonitorInternal
20683                     dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20684             if (dsm != null) {
20685                 return dsm.isMemoryLow();
20686             } else {
20687                 return false;
20688             }
20689         } finally {
20690             Binder.restoreCallingIdentity(token);
20691         }
20692     }
20693
20694     @Override
20695     public IPackageInstaller getPackageInstaller() {
20696         return mInstallerService;
20697     }
20698
20699     private boolean userNeedsBadging(int userId) {
20700         int index = mUserNeedsBadging.indexOfKey(userId);
20701         if (index < 0) {
20702             final UserInfo userInfo;
20703             final long token = Binder.clearCallingIdentity();
20704             try {
20705                 userInfo = sUserManager.getUserInfo(userId);
20706             } finally {
20707                 Binder.restoreCallingIdentity(token);
20708             }
20709             final boolean b;
20710             if (userInfo != null && userInfo.isManagedProfile()) {
20711                 b = true;
20712             } else {
20713                 b = false;
20714             }
20715             mUserNeedsBadging.put(userId, b);
20716             return b;
20717         }
20718         return mUserNeedsBadging.valueAt(index);
20719     }
20720
20721     @Override
20722     public KeySet getKeySetByAlias(String packageName, String alias) {
20723         if (packageName == null || alias == null) {
20724             return null;
20725         }
20726         synchronized(mPackages) {
20727             final PackageParser.Package pkg = mPackages.get(packageName);
20728             if (pkg == null) {
20729                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20730                 throw new IllegalArgumentException("Unknown package: " + packageName);
20731             }
20732             KeySetManagerService ksms = mSettings.mKeySetManagerService;
20733             return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20734         }
20735     }
20736
20737     @Override
20738     public KeySet getSigningKeySet(String packageName) {
20739         if (packageName == null) {
20740             return null;
20741         }
20742         synchronized(mPackages) {
20743             final PackageParser.Package pkg = mPackages.get(packageName);
20744             if (pkg == null) {
20745                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20746                 throw new IllegalArgumentException("Unknown package: " + packageName);
20747             }
20748             if (pkg.applicationInfo.uid != Binder.getCallingUid()
20749                     && Process.SYSTEM_UID != Binder.getCallingUid()) {
20750                 throw new SecurityException("May not access signing KeySet of other apps.");
20751             }
20752             KeySetManagerService ksms = mSettings.mKeySetManagerService;
20753             return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20754         }
20755     }
20756
20757     @Override
20758     public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20759         if (packageName == null || ks == null) {
20760             return false;
20761         }
20762         synchronized(mPackages) {
20763             final PackageParser.Package pkg = mPackages.get(packageName);
20764             if (pkg == null) {
20765                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20766                 throw new IllegalArgumentException("Unknown package: " + packageName);
20767             }
20768             IBinder ksh = ks.getToken();
20769             if (ksh instanceof KeySetHandle) {
20770                 KeySetManagerService ksms = mSettings.mKeySetManagerService;
20771                 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20772             }
20773             return false;
20774         }
20775     }
20776
20777     @Override
20778     public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20779         if (packageName == null || ks == null) {
20780             return false;
20781         }
20782         synchronized(mPackages) {
20783             final PackageParser.Package pkg = mPackages.get(packageName);
20784             if (pkg == null) {
20785                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20786                 throw new IllegalArgumentException("Unknown package: " + packageName);
20787             }
20788             IBinder ksh = ks.getToken();
20789             if (ksh instanceof KeySetHandle) {
20790                 KeySetManagerService ksms = mSettings.mKeySetManagerService;
20791                 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20792             }
20793             return false;
20794         }
20795     }
20796
20797     private void deletePackageIfUnusedLPr(final String packageName) {
20798         PackageSetting ps = mSettings.mPackages.get(packageName);
20799         if (ps == null) {
20800             return;
20801         }
20802         if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20803             // TODO Implement atomic delete if package is unused
20804             // It is currently possible that the package will be deleted even if it is installed
20805             // after this method returns.
20806             mHandler.post(new Runnable() {
20807                 public void run() {
20808                     deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20809                 }
20810             });
20811         }
20812     }
20813
20814     /**
20815      * Check and throw if the given before/after packages would be considered a
20816      * downgrade.
20817      */
20818     private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20819             throws PackageManagerException {
20820         if (after.versionCode < before.mVersionCode) {
20821             throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20822                     "Update version code " + after.versionCode + " is older than current "
20823                     + before.mVersionCode);
20824         } else if (after.versionCode == before.mVersionCode) {
20825             if (after.baseRevisionCode < before.baseRevisionCode) {
20826                 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20827                         "Update base revision code " + after.baseRevisionCode
20828                         + " is older than current " + before.baseRevisionCode);
20829             }
20830
20831             if (!ArrayUtils.isEmpty(after.splitNames)) {
20832                 for (int i = 0; i < after.splitNames.length; i++) {
20833                     final String splitName = after.splitNames[i];
20834                     final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20835                     if (j != -1) {
20836                         if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20837                             throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20838                                     "Update split " + splitName + " revision code "
20839                                     + after.splitRevisionCodes[i] + " is older than current "
20840                                     + before.splitRevisionCodes[j]);
20841                         }
20842                     }
20843                 }
20844             }
20845         }
20846     }
20847
20848     private static class MoveCallbacks extends Handler {
20849         private static final int MSG_CREATED = 1;
20850         private static final int MSG_STATUS_CHANGED = 2;
20851
20852         private final RemoteCallbackList<IPackageMoveObserver>
20853                 mCallbacks = new RemoteCallbackList<>();
20854
20855         private final SparseIntArray mLastStatus = new SparseIntArray();
20856
20857         public MoveCallbacks(Looper looper) {
20858             super(looper);
20859         }
20860
20861         public void register(IPackageMoveObserver callback) {
20862             mCallbacks.register(callback);
20863         }
20864
20865         public void unregister(IPackageMoveObserver callback) {
20866             mCallbacks.unregister(callback);
20867         }
20868
20869         @Override
20870         public void handleMessage(Message msg) {
20871             final SomeArgs args = (SomeArgs) msg.obj;
20872             final int n = mCallbacks.beginBroadcast();
20873             for (int i = 0; i < n; i++) {
20874                 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20875                 try {
20876                     invokeCallback(callback, msg.what, args);
20877                 } catch (RemoteException ignored) {
20878                 }
20879             }
20880             mCallbacks.finishBroadcast();
20881             args.recycle();
20882         }
20883
20884         private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20885                 throws RemoteException {
20886             switch (what) {
20887                 case MSG_CREATED: {
20888                     callback.onCreated(args.argi1, (Bundle) args.arg2);
20889                     break;
20890                 }
20891                 case MSG_STATUS_CHANGED: {
20892                     callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20893                     break;
20894                 }
20895             }
20896         }
20897
20898         private void notifyCreated(int moveId, Bundle extras) {
20899             Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20900
20901             final SomeArgs args = SomeArgs.obtain();
20902             args.argi1 = moveId;
20903             args.arg2 = extras;
20904             obtainMessage(MSG_CREATED, args).sendToTarget();
20905         }
20906
20907         private void notifyStatusChanged(int moveId, int status) {
20908             notifyStatusChanged(moveId, status, -1);
20909         }
20910
20911         private void notifyStatusChanged(int moveId, int status, long estMillis) {
20912             Slog.v(TAG, "Move " + moveId + " status " + status);
20913
20914             final SomeArgs args = SomeArgs.obtain();
20915             args.argi1 = moveId;
20916             args.argi2 = status;
20917             args.arg3 = estMillis;
20918             obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20919
20920             synchronized (mLastStatus) {
20921                 mLastStatus.put(moveId, status);
20922             }
20923         }
20924     }
20925
20926     private final static class OnPermissionChangeListeners extends Handler {
20927         private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20928
20929         private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20930                 new RemoteCallbackList<>();
20931
20932         public OnPermissionChangeListeners(Looper looper) {
20933             super(looper);
20934         }
20935
20936         @Override
20937         public void handleMessage(Message msg) {
20938             switch (msg.what) {
20939                 case MSG_ON_PERMISSIONS_CHANGED: {
20940                     final int uid = msg.arg1;
20941                     handleOnPermissionsChanged(uid);
20942                 } break;
20943             }
20944         }
20945
20946         public void addListenerLocked(IOnPermissionsChangeListener listener) {
20947             mPermissionListeners.register(listener);
20948
20949         }
20950
20951         public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20952             mPermissionListeners.unregister(listener);
20953         }
20954
20955         public void onPermissionsChanged(int uid) {
20956             if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20957                 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20958             }
20959         }
20960
20961         private void handleOnPermissionsChanged(int uid) {
20962             final int count = mPermissionListeners.beginBroadcast();
20963             try {
20964                 for (int i = 0; i < count; i++) {
20965                     IOnPermissionsChangeListener callback = mPermissionListeners
20966                             .getBroadcastItem(i);
20967                     try {
20968                         callback.onPermissionsChanged(uid);
20969                     } catch (RemoteException e) {
20970                         Log.e(TAG, "Permission listener is dead", e);
20971                     }
20972                 }
20973             } finally {
20974                 mPermissionListeners.finishBroadcast();
20975             }
20976         }
20977     }
20978
20979     private class PackageManagerInternalImpl extends PackageManagerInternal {
20980         @Override
20981         public void setLocationPackagesProvider(PackagesProvider provider) {
20982             synchronized (mPackages) {
20983                 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20984             }
20985         }
20986
20987         @Override
20988         public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20989             synchronized (mPackages) {
20990                 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20991             }
20992         }
20993
20994         @Override
20995         public void setSmsAppPackagesProvider(PackagesProvider provider) {
20996             synchronized (mPackages) {
20997                 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20998             }
20999         }
21000
21001         @Override
21002         public void setDialerAppPackagesProvider(PackagesProvider provider) {
21003             synchronized (mPackages) {
21004                 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
21005             }
21006         }
21007
21008         @Override
21009         public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
21010             synchronized (mPackages) {
21011                 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
21012             }
21013         }
21014
21015         @Override
21016         public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
21017             synchronized (mPackages) {
21018                 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
21019             }
21020         }
21021
21022         @Override
21023         public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
21024             synchronized (mPackages) {
21025                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
21026                         packageName, userId);
21027             }
21028         }
21029
21030         @Override
21031         public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
21032             synchronized (mPackages) {
21033                 mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
21034                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
21035                         packageName, userId);
21036             }
21037         }
21038
21039         @Override
21040         public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
21041             synchronized (mPackages) {
21042                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
21043                         packageName, userId);
21044             }
21045         }
21046
21047         @Override
21048         public void setKeepUninstalledPackages(final List<String> packageList) {
21049             Preconditions.checkNotNull(packageList);
21050             List<String> removedFromList = null;
21051             synchronized (mPackages) {
21052                 if (mKeepUninstalledPackages != null) {
21053                     final int packagesCount = mKeepUninstalledPackages.size();
21054                     for (int i = 0; i < packagesCount; i++) {
21055                         String oldPackage = mKeepUninstalledPackages.get(i);
21056                         if (packageList != null && packageList.contains(oldPackage)) {
21057                             continue;
21058                         }
21059                         if (removedFromList == null) {
21060                             removedFromList = new ArrayList<>();
21061                         }
21062                         removedFromList.add(oldPackage);
21063                     }
21064                 }
21065                 mKeepUninstalledPackages = new ArrayList<>(packageList);
21066                 if (removedFromList != null) {
21067                     final int removedCount = removedFromList.size();
21068                     for (int i = 0; i < removedCount; i++) {
21069                         deletePackageIfUnusedLPr(removedFromList.get(i));
21070                     }
21071                 }
21072             }
21073         }
21074
21075         @Override
21076         public boolean isPermissionsReviewRequired(String packageName, int userId) {
21077             synchronized (mPackages) {
21078                 // If we do not support permission review, done.
21079                 if (!mPermissionReviewRequired && !Build.PERMISSIONS_REVIEW_REQUIRED) {
21080                     return false;
21081                 }
21082
21083                 PackageSetting packageSetting = mSettings.mPackages.get(packageName);
21084                 if (packageSetting == null) {
21085                     return false;
21086                 }
21087
21088                 // Permission review applies only to apps not supporting the new permission model.
21089                 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
21090                     return false;
21091                 }
21092
21093                 // Legacy apps have the permission and get user consent on launch.
21094                 PermissionsState permissionsState = packageSetting.getPermissionsState();
21095                 return permissionsState.isPermissionReviewRequired(userId);
21096             }
21097         }
21098
21099         @Override
21100         public ApplicationInfo getApplicationInfo(String packageName, int userId) {
21101             return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
21102         }
21103
21104         @Override
21105         public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21106                 int userId) {
21107             return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
21108         }
21109
21110         @Override
21111         public void setDeviceAndProfileOwnerPackages(
21112                 int deviceOwnerUserId, String deviceOwnerPackage,
21113                 SparseArray<String> profileOwnerPackages) {
21114             mProtectedPackages.setDeviceAndProfileOwnerPackages(
21115                     deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
21116         }
21117
21118         @Override
21119         public boolean isPackageDataProtected(int userId, String packageName) {
21120             return mProtectedPackages.isPackageDataProtected(userId, packageName);
21121         }
21122
21123         @Override
21124         public boolean wasPackageEverLaunched(String packageName, int userId) {
21125             synchronized (mPackages) {
21126                 return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
21127             }
21128         }
21129     }
21130
21131     @Override
21132     public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
21133         enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
21134         synchronized (mPackages) {
21135             final long identity = Binder.clearCallingIdentity();
21136             try {
21137                 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
21138                         packageNames, userId);
21139             } finally {
21140                 Binder.restoreCallingIdentity(identity);
21141             }
21142         }
21143     }
21144
21145     private static void enforceSystemOrPhoneCaller(String tag) {
21146         int callingUid = Binder.getCallingUid();
21147         if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
21148             throw new SecurityException(
21149                     "Cannot call " + tag + " from UID " + callingUid);
21150         }
21151     }
21152
21153     boolean isHistoricalPackageUsageAvailable() {
21154         return mPackageUsage.isHistoricalPackageUsageAvailable();
21155     }
21156
21157     /**
21158      * Return a <b>copy</b> of the collection of packages known to the package manager.
21159      * @return A copy of the values of mPackages.
21160      */
21161     Collection<PackageParser.Package> getPackages() {
21162         synchronized (mPackages) {
21163             return new ArrayList<>(mPackages.values());
21164         }
21165     }
21166
21167     /**
21168      * Logs process start information (including base APK hash) to the security log.
21169      * @hide
21170      */
21171     public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
21172             String apkFile, int pid) {
21173         if (!SecurityLog.isLoggingEnabled()) {
21174             return;
21175         }
21176         Bundle data = new Bundle();
21177         data.putLong("startTimestamp", System.currentTimeMillis());
21178         data.putString("processName", processName);
21179         data.putInt("uid", uid);
21180         data.putString("seinfo", seinfo);
21181         data.putString("apkFile", apkFile);
21182         data.putInt("pid", pid);
21183         Message msg = mProcessLoggingHandler.obtainMessage(
21184                 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
21185         msg.setData(data);
21186         mProcessLoggingHandler.sendMessage(msg);
21187     }
21188
21189     public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
21190         return mCompilerStats.getPackageStats(pkgName);
21191     }
21192
21193     public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
21194         return getOrCreateCompilerPackageStats(pkg.packageName);
21195     }
21196
21197     public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
21198         return mCompilerStats.getOrCreatePackageStats(pkgName);
21199     }
21200
21201     public void deleteCompilerPackageStats(String pkgName) {
21202         mCompilerStats.deletePackageStats(pkgName);
21203     }
21204 }