OSDN Git Service

Merge "DO NOT MERGE. No direct Uri grants from system." into lmp-mr1-dev am: 6d3573e5...
[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_DEXOPT;
39 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
40 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
41 import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
42 import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
43 import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
44 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
45 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
46 import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
47 import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
48 import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
49 import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
50 import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
51 import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
52 import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
53 import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
54 import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
55 import static android.content.pm.PackageManager.INSTALL_INTERNAL;
56 import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
57 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
58 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
59 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
60 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
61 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
62 import static android.content.pm.PackageManager.MATCH_ALL;
63 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
65 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
66 import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
67 import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
68 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
69 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
70 import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
71 import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
72 import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
73 import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
74 import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
75 import static android.content.pm.PackageManager.PERMISSION_DENIED;
76 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
77 import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
78 import static android.content.pm.PackageParser.isApkFile;
79 import static android.os.Process.PACKAGE_INFO_GID;
80 import static android.os.Process.SYSTEM_UID;
81 import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
82 import static android.system.OsConstants.O_CREAT;
83 import static android.system.OsConstants.O_RDWR;
84
85 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
86 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
87 import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
88 import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
89 import static com.android.internal.util.ArrayUtils.appendInt;
90 import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
91 import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
92 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
93 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
94 import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
95 import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
96 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
97 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
98 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
99 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
100 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
101
102 import android.Manifest;
103 import android.annotation.NonNull;
104 import android.annotation.Nullable;
105 import android.annotation.UserIdInt;
106 import android.app.ActivityManager;
107 import android.app.ActivityManagerNative;
108 import android.app.IActivityManager;
109 import android.app.ResourcesManager;
110 import android.app.admin.IDevicePolicyManager;
111 import android.app.admin.SecurityLog;
112 import android.app.backup.IBackupManager;
113 import android.content.BroadcastReceiver;
114 import android.content.ComponentName;
115 import android.content.Context;
116 import android.content.IIntentReceiver;
117 import android.content.Intent;
118 import android.content.IntentFilter;
119 import android.content.IntentSender;
120 import android.content.IntentSender.SendIntentException;
121 import android.content.ServiceConnection;
122 import android.content.pm.ActivityInfo;
123 import android.content.pm.ApplicationInfo;
124 import android.content.pm.AppsQueryHelper;
125 import android.content.pm.ComponentInfo;
126 import android.content.pm.EphemeralApplicationInfo;
127 import android.content.pm.EphemeralResolveInfo;
128 import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
129 import android.content.pm.FeatureInfo;
130 import android.content.pm.IOnPermissionsChangeListener;
131 import android.content.pm.IPackageDataObserver;
132 import android.content.pm.IPackageDeleteObserver;
133 import android.content.pm.IPackageDeleteObserver2;
134 import android.content.pm.IPackageInstallObserver2;
135 import android.content.pm.IPackageInstaller;
136 import android.content.pm.IPackageManager;
137 import android.content.pm.IPackageMoveObserver;
138 import android.content.pm.IPackageStatsObserver;
139 import android.content.pm.InstrumentationInfo;
140 import android.content.pm.IntentFilterVerificationInfo;
141 import android.content.pm.KeySet;
142 import android.content.pm.PackageCleanItem;
143 import android.content.pm.PackageInfo;
144 import android.content.pm.PackageInfoLite;
145 import android.content.pm.PackageInstaller;
146 import android.content.pm.PackageManager;
147 import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
148 import android.content.pm.PackageManagerInternal;
149 import android.content.pm.PackageParser;
150 import android.content.pm.PackageParser.ActivityIntentInfo;
151 import android.content.pm.PackageParser.PackageLite;
152 import android.content.pm.PackageParser.PackageParserException;
153 import android.content.pm.PackageStats;
154 import android.content.pm.PackageUserState;
155 import android.content.pm.ParceledListSlice;
156 import android.content.pm.PermissionGroupInfo;
157 import android.content.pm.PermissionInfo;
158 import android.content.pm.ProviderInfo;
159 import android.content.pm.ResolveInfo;
160 import android.content.pm.ServiceInfo;
161 import android.content.pm.Signature;
162 import android.content.pm.UserInfo;
163 import android.content.pm.VerifierDeviceIdentity;
164 import android.content.pm.VerifierInfo;
165 import android.content.res.Resources;
166 import android.graphics.Bitmap;
167 import android.hardware.display.DisplayManager;
168 import android.net.Uri;
169 import android.os.Binder;
170 import android.os.Build;
171 import android.os.Bundle;
172 import android.os.Debug;
173 import android.os.Environment;
174 import android.os.Environment.UserEnvironment;
175 import android.os.FileUtils;
176 import android.os.Handler;
177 import android.os.IBinder;
178 import android.os.Looper;
179 import android.os.Message;
180 import android.os.Parcel;
181 import android.os.ParcelFileDescriptor;
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.security.KeyStore;
201 import android.security.SystemKeyStore;
202 import android.system.ErrnoException;
203 import android.system.Os;
204 import android.text.TextUtils;
205 import android.text.format.DateUtils;
206 import android.util.ArrayMap;
207 import android.util.ArraySet;
208 import android.util.AtomicFile;
209 import android.util.DisplayMetrics;
210 import android.util.EventLog;
211 import android.util.ExceptionUtils;
212 import android.util.Log;
213 import android.util.LogPrinter;
214 import android.util.MathUtils;
215 import android.util.PrintStreamPrinter;
216 import android.util.Slog;
217 import android.util.SparseArray;
218 import android.util.SparseBooleanArray;
219 import android.util.SparseIntArray;
220 import android.util.Xml;
221 import android.util.jar.StrictJarFile;
222 import android.view.Display;
223
224 import com.android.internal.R;
225 import com.android.internal.annotations.GuardedBy;
226 import com.android.internal.app.IMediaContainerService;
227 import com.android.internal.app.ResolverActivity;
228 import com.android.internal.content.NativeLibraryHelper;
229 import com.android.internal.content.PackageHelper;
230 import com.android.internal.logging.MetricsLogger;
231 import com.android.internal.os.IParcelFileDescriptorFactory;
232 import com.android.internal.os.InstallerConnection.InstallerException;
233 import com.android.internal.os.SomeArgs;
234 import com.android.internal.os.Zygote;
235 import com.android.internal.telephony.CarrierAppUtils;
236 import com.android.internal.util.ArrayUtils;
237 import com.android.internal.util.FastPrintWriter;
238 import com.android.internal.util.FastXmlSerializer;
239 import com.android.internal.util.IndentingPrintWriter;
240 import com.android.internal.util.Preconditions;
241 import com.android.internal.util.XmlUtils;
242 import com.android.server.AttributeCache;
243 import com.android.server.EventLogTags;
244 import com.android.server.FgThread;
245 import com.android.server.IntentResolver;
246 import com.android.server.LocalServices;
247 import com.android.server.ServiceThread;
248 import com.android.server.SystemConfig;
249 import com.android.server.Watchdog;
250 import com.android.server.net.NetworkPolicyManagerInternal;
251 import com.android.server.pm.PermissionsState.PermissionState;
252 import com.android.server.pm.Settings.DatabaseVersion;
253 import com.android.server.pm.Settings.VersionInfo;
254 import com.android.server.storage.DeviceStorageMonitorInternal;
255
256 import dalvik.system.CloseGuard;
257 import dalvik.system.DexFile;
258 import dalvik.system.VMRuntime;
259
260 import libcore.io.IoUtils;
261 import libcore.util.EmptyArray;
262
263 import org.xmlpull.v1.XmlPullParser;
264 import org.xmlpull.v1.XmlPullParserException;
265 import org.xmlpull.v1.XmlSerializer;
266
267 import java.io.BufferedInputStream;
268 import java.io.BufferedOutputStream;
269 import java.io.BufferedReader;
270 import java.io.ByteArrayInputStream;
271 import java.io.ByteArrayOutputStream;
272 import java.io.File;
273 import java.io.FileDescriptor;
274 import java.io.FileInputStream;
275 import java.io.FileNotFoundException;
276 import java.io.FileOutputStream;
277 import java.io.FileReader;
278 import java.io.FilenameFilter;
279 import java.io.IOException;
280 import java.io.InputStream;
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 import java.util.concurrent.atomic.AtomicLong;
308
309 /**
310  * Keep track of all those APKs everywhere.
311  * <p>
312  * Internally there are two important locks:
313  * <ul>
314  * <li>{@link #mPackages} is used to guard all in-memory parsed package details
315  * and other related state. It is a fine-grained lock that should only be held
316  * momentarily, as it's one of the most contended locks in the system.
317  * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
318  * operations typically involve heavy lifting of application data on disk. Since
319  * {@code installd} is single-threaded, and it's operations can often be slow,
320  * this lock should never be acquired while already holding {@link #mPackages}.
321  * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
322  * holding {@link #mInstallLock}.
323  * </ul>
324  * Many internal methods rely on the caller to hold the appropriate locks, and
325  * this contract is expressed through method name suffixes:
326  * <ul>
327  * <li>fooLI(): the caller must hold {@link #mInstallLock}
328  * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
329  * being modified must be frozen
330  * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
331  * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
332  * </ul>
333  * <p>
334  * Because this class is very central to the platform's security; please run all
335  * CTS and unit tests whenever making modifications:
336  *
337  * <pre>
338  * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
339  * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
340  * </pre>
341  */
342 public class PackageManagerService extends IPackageManager.Stub {
343     static final String TAG = "PackageManager";
344     static final boolean DEBUG_SETTINGS = false;
345     static final boolean DEBUG_PREFERRED = false;
346     static final boolean DEBUG_UPGRADE = false;
347     static final boolean DEBUG_DOMAIN_VERIFICATION = false;
348     private static final boolean DEBUG_BACKUP = false;
349     private static final boolean DEBUG_INSTALL = false;
350     private static final boolean DEBUG_REMOVE = false;
351     private static final boolean DEBUG_BROADCASTS = false;
352     private static final boolean DEBUG_SHOW_INFO = false;
353     private static final boolean DEBUG_PACKAGE_INFO = false;
354     private static final boolean DEBUG_INTENT_MATCHING = false;
355     private static final boolean DEBUG_PACKAGE_SCANNING = false;
356     private static final boolean DEBUG_VERIFY = false;
357     private static final boolean DEBUG_FILTERS = false;
358
359     // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
360     // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
361     // user, but by default initialize to this.
362     static final boolean DEBUG_DEXOPT = false;
363
364     private static final boolean DEBUG_ABI_SELECTION = false;
365     private static final boolean DEBUG_EPHEMERAL = false;
366     private static final boolean DEBUG_TRIAGED_MISSING = false;
367     private static final boolean DEBUG_APP_DATA = false;
368
369     static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
370
371     private static final boolean DISABLE_EPHEMERAL_APPS = 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 VENDOR_OVERLAY_DIR = "/vendor/overlay";
464
465     /** Permission grant: not grant the permission. */
466     private static final int GRANT_DENIED = 1;
467
468     /** Permission grant: grant the permission as an install permission. */
469     private static final int GRANT_INSTALL = 2;
470
471     /** Permission grant: grant the permission as a runtime one. */
472     private static final int GRANT_RUNTIME = 3;
473
474     /** Permission grant: grant as runtime a permission that was granted as an install time one. */
475     private static final int GRANT_UPGRADE = 4;
476
477     /** Canonical intent used to identify what counts as a "web browser" app */
478     private static final Intent sBrowserIntent;
479     static {
480         sBrowserIntent = new Intent();
481         sBrowserIntent.setAction(Intent.ACTION_VIEW);
482         sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
483         sBrowserIntent.setData(Uri.parse("http:"));
484     }
485
486     /**
487      * The set of all protected actions [i.e. those actions for which a high priority
488      * intent filter is disallowed].
489      */
490     private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
491     static {
492         PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
493         PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
494         PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
495         PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
496     }
497
498     // Compilation reasons.
499     public static final int REASON_FIRST_BOOT = 0;
500     public static final int REASON_BOOT = 1;
501     public static final int REASON_INSTALL = 2;
502     public static final int REASON_BACKGROUND_DEXOPT = 3;
503     public static final int REASON_AB_OTA = 4;
504     public static final int REASON_NON_SYSTEM_LIBRARY = 5;
505     public static final int REASON_SHARED_APK = 6;
506     public static final int REASON_FORCED_DEXOPT = 7;
507     public static final int REASON_CORE_APP = 8;
508
509     public static final int REASON_LAST = REASON_CORE_APP;
510
511     /** Special library name that skips shared libraries check during compilation. */
512     private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
513
514     final ServiceThread mHandlerThread;
515
516     final PackageHandler mHandler;
517
518     private final ProcessLoggingHandler mProcessLoggingHandler;
519
520     /**
521      * Messages for {@link #mHandler} that need to wait for system ready before
522      * being dispatched.
523      */
524     private ArrayList<Message> mPostSystemReadyMessages;
525
526     final int mSdkVersion = Build.VERSION.SDK_INT;
527
528     final Context mContext;
529     final boolean mFactoryTest;
530     final boolean mOnlyCore;
531     final DisplayMetrics mMetrics;
532     final int mDefParseFlags;
533     final String[] mSeparateProcesses;
534     final boolean mIsUpgrade;
535     final boolean mIsPreNUpgrade;
536
537     /** The location for ASEC container files on internal storage. */
538     final String mAsecInternalPath;
539
540     // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
541     // LOCK HELD.  Can be called with mInstallLock held.
542     @GuardedBy("mInstallLock")
543     final Installer mInstaller;
544
545     /** Directory where installed third-party apps stored */
546     final File mAppInstallDir;
547     final File mEphemeralInstallDir;
548
549     /**
550      * Directory to which applications installed internally have their
551      * 32 bit native libraries copied.
552      */
553     private File mAppLib32InstallDir;
554
555     // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
556     // apps.
557     final File mDrmAppPrivateInstallDir;
558
559     // ----------------------------------------------------------------
560
561     // Lock for state used when installing and doing other long running
562     // operations.  Methods that must be called with this lock held have
563     // the suffix "LI".
564     final Object mInstallLock = new Object();
565
566     // ----------------------------------------------------------------
567
568     // Keys are String (package name), values are Package.  This also serves
569     // as the lock for the global state.  Methods that must be called with
570     // this lock held have the prefix "LP".
571     @GuardedBy("mPackages")
572     final ArrayMap<String, PackageParser.Package> mPackages =
573             new ArrayMap<String, PackageParser.Package>();
574
575     final ArrayMap<String, Set<String>> mKnownCodebase =
576             new ArrayMap<String, Set<String>>();
577
578     // Tracks available target package names -> overlay package paths.
579     final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
580         new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
581
582     /**
583      * Tracks new system packages [received in an OTA] that we expect to
584      * find updated user-installed versions. Keys are package name, values
585      * are package location.
586      */
587     final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
588     /**
589      * Tracks high priority intent filters for protected actions. During boot, certain
590      * filter actions are protected and should never be allowed to have a high priority
591      * intent filter for them. However, there is one, and only one exception -- the
592      * setup wizard. It must be able to define a high priority intent filter for these
593      * actions to ensure there are no escapes from the wizard. We need to delay processing
594      * of these during boot as we need to look at all of the system packages in order
595      * to know which component is the setup wizard.
596      */
597     private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
598     /**
599      * Whether or not processing protected filters should be deferred.
600      */
601     private boolean mDeferProtectedFilters = true;
602
603     /**
604      * Tracks existing system packages prior to receiving an OTA. Keys are package name.
605      */
606     final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
607     /**
608      * Whether or not system app permissions should be promoted from install to runtime.
609      */
610     boolean mPromoteSystemApps;
611
612     @GuardedBy("mPackages")
613     final Settings mSettings;
614
615     /**
616      * Set of package names that are currently "frozen", which means active
617      * surgery is being done on the code/data for that package. The platform
618      * will refuse to launch frozen packages to avoid race conditions.
619      *
620      * @see PackageFreezer
621      */
622     @GuardedBy("mPackages")
623     final ArraySet<String> mFrozenPackages = new ArraySet<>();
624
625     final ProtectedPackages mProtectedPackages = new ProtectedPackages();
626
627     boolean mRestoredSettings;
628
629     // System configuration read by SystemConfig.
630     final int[] mGlobalGids;
631     final SparseArray<ArraySet<String>> mSystemPermissions;
632     final ArrayMap<String, FeatureInfo> mAvailableFeatures;
633
634     // If mac_permissions.xml was found for seinfo labeling.
635     boolean mFoundPolicyFile;
636
637     private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
638
639     public static final class SharedLibraryEntry {
640         public final String path;
641         public final String apk;
642
643         SharedLibraryEntry(String _path, String _apk) {
644             path = _path;
645             apk = _apk;
646         }
647     }
648
649     // Currently known shared libraries.
650     final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
651             new ArrayMap<String, SharedLibraryEntry>();
652
653     // All available activities, for your resolving pleasure.
654     final ActivityIntentResolver mActivities =
655             new ActivityIntentResolver();
656
657     // All available receivers, for your resolving pleasure.
658     final ActivityIntentResolver mReceivers =
659             new ActivityIntentResolver();
660
661     // All available services, for your resolving pleasure.
662     final ServiceIntentResolver mServices = new ServiceIntentResolver();
663
664     // All available providers, for your resolving pleasure.
665     final ProviderIntentResolver mProviders = new ProviderIntentResolver();
666
667     // Mapping from provider base names (first directory in content URI codePath)
668     // to the provider information.
669     final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
670             new ArrayMap<String, PackageParser.Provider>();
671
672     // Mapping from instrumentation class names to info about them.
673     final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
674             new ArrayMap<ComponentName, PackageParser.Instrumentation>();
675
676     // Mapping from permission names to info about them.
677     final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
678             new ArrayMap<String, PackageParser.PermissionGroup>();
679
680     // Packages whose data we have transfered into another package, thus
681     // should no longer exist.
682     final ArraySet<String> mTransferedPackages = new ArraySet<String>();
683
684     // Broadcast actions that are only available to the system.
685     final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
686
687     /** List of packages waiting for verification. */
688     final SparseArray<PackageVerificationState> mPendingVerification
689             = new SparseArray<PackageVerificationState>();
690
691     /** Set of packages associated with each app op permission. */
692     final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
693
694     final PackageInstallerService mInstallerService;
695
696     private final PackageDexOptimizer mPackageDexOptimizer;
697
698     private AtomicInteger mNextMoveId = new AtomicInteger();
699     private final MoveCallbacks mMoveCallbacks;
700
701     private final OnPermissionChangeListeners mOnPermissionChangeListeners;
702
703     // Cache of users who need badging.
704     SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
705
706     /** Token for keys in mPendingVerification. */
707     private int mPendingVerificationToken = 0;
708
709     volatile boolean mSystemReady;
710     volatile boolean mSafeMode;
711     volatile boolean mHasSystemUidErrors;
712
713     ApplicationInfo mAndroidApplication;
714     final ActivityInfo mResolveActivity = new ActivityInfo();
715     final ResolveInfo mResolveInfo = new ResolveInfo();
716     ComponentName mResolveComponentName;
717     PackageParser.Package mPlatformPackage;
718     ComponentName mCustomResolverComponentName;
719
720     boolean mResolverReplaced = false;
721
722     private final @Nullable ComponentName mIntentFilterVerifierComponent;
723     private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
724
725     private int mIntentFilterVerificationToken = 0;
726
727     /** Component that knows whether or not an ephemeral application exists */
728     final ComponentName mEphemeralResolverComponent;
729     /** The service connection to the ephemeral resolver */
730     final EphemeralResolverConnection mEphemeralResolverConnection;
731
732     /** Component used to install ephemeral applications */
733     final ComponentName mEphemeralInstallerComponent;
734     final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
735     final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
736
737     final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
738             = new SparseArray<IntentFilterVerificationState>();
739
740     final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
741             new DefaultPermissionGrantPolicy(this);
742
743     // List of packages names to keep cached, even if they are uninstalled for all users
744     private List<String> mKeepUninstalledPackages;
745
746     private UserManagerInternal mUserManagerInternal;
747
748     private static class IFVerificationParams {
749         PackageParser.Package pkg;
750         boolean replacing;
751         int userId;
752         int verifierUid;
753
754         public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
755                 int _userId, int _verifierUid) {
756             pkg = _pkg;
757             replacing = _replacing;
758             userId = _userId;
759             replacing = _replacing;
760             verifierUid = _verifierUid;
761         }
762     }
763
764     private interface IntentFilterVerifier<T extends IntentFilter> {
765         boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
766                                                T filter, String packageName);
767         void startVerifications(int userId);
768         void receiveVerificationResponse(int verificationId);
769     }
770
771     private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
772         private Context mContext;
773         private ComponentName mIntentFilterVerifierComponent;
774         private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
775
776         public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
777             mContext = context;
778             mIntentFilterVerifierComponent = verifierComponent;
779         }
780
781         private String getDefaultScheme() {
782             return IntentFilter.SCHEME_HTTPS;
783         }
784
785         @Override
786         public void startVerifications(int userId) {
787             // Launch verifications requests
788             int count = mCurrentIntentFilterVerifications.size();
789             for (int n=0; n<count; n++) {
790                 int verificationId = mCurrentIntentFilterVerifications.get(n);
791                 final IntentFilterVerificationState ivs =
792                         mIntentFilterVerificationStates.get(verificationId);
793
794                 String packageName = ivs.getPackageName();
795
796                 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
797                 final int filterCount = filters.size();
798                 ArraySet<String> domainsSet = new ArraySet<>();
799                 for (int m=0; m<filterCount; m++) {
800                     PackageParser.ActivityIntentInfo filter = filters.get(m);
801                     domainsSet.addAll(filter.getHostsList());
802                 }
803                 ArrayList<String> domainsList = new ArrayList<>(domainsSet);
804                 synchronized (mPackages) {
805                     if (mSettings.createIntentFilterVerificationIfNeededLPw(
806                             packageName, domainsList) != null) {
807                         scheduleWriteSettingsLocked();
808                     }
809                 }
810                 sendVerificationRequest(userId, verificationId, ivs);
811             }
812             mCurrentIntentFilterVerifications.clear();
813         }
814
815         private void sendVerificationRequest(int userId, int verificationId,
816                 IntentFilterVerificationState ivs) {
817
818             Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
819             verificationIntent.putExtra(
820                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
821                     verificationId);
822             verificationIntent.putExtra(
823                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
824                     getDefaultScheme());
825             verificationIntent.putExtra(
826                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
827                     ivs.getHostsString());
828             verificationIntent.putExtra(
829                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
830                     ivs.getPackageName());
831             verificationIntent.setComponent(mIntentFilterVerifierComponent);
832             verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
833
834             UserHandle user = new UserHandle(userId);
835             mContext.sendBroadcastAsUser(verificationIntent, user);
836             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
837                     "Sending IntentFilter verification broadcast");
838         }
839
840         public void receiveVerificationResponse(int verificationId) {
841             IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
842
843             final boolean verified = ivs.isVerified();
844
845             ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
846             final int count = filters.size();
847             if (DEBUG_DOMAIN_VERIFICATION) {
848                 Slog.i(TAG, "Received verification response " + verificationId
849                         + " for " + count + " filters, verified=" + verified);
850             }
851             for (int n=0; n<count; n++) {
852                 PackageParser.ActivityIntentInfo filter = filters.get(n);
853                 filter.setVerified(verified);
854
855                 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
856                         + " verified with result:" + verified + " and hosts:"
857                         + ivs.getHostsString());
858             }
859
860             mIntentFilterVerificationStates.remove(verificationId);
861
862             final String packageName = ivs.getPackageName();
863             IntentFilterVerificationInfo ivi = null;
864
865             synchronized (mPackages) {
866                 ivi = mSettings.getIntentFilterVerificationLPr(packageName);
867             }
868             if (ivi == null) {
869                 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
870                         + verificationId + " packageName:" + packageName);
871                 return;
872             }
873             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
874                     "Updating IntentFilterVerificationInfo for package " + packageName
875                             +" verificationId:" + verificationId);
876
877             synchronized (mPackages) {
878                 if (verified) {
879                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
880                 } else {
881                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
882                 }
883                 scheduleWriteSettingsLocked();
884
885                 final int userId = ivs.getUserId();
886                 if (userId != UserHandle.USER_ALL) {
887                     final int userStatus =
888                             mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
889
890                     int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
891                     boolean needUpdate = false;
892
893                     // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
894                     // already been set by the User thru the Disambiguation dialog
895                     switch (userStatus) {
896                         case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
897                             if (verified) {
898                                 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
899                             } else {
900                                 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
901                             }
902                             needUpdate = true;
903                             break;
904
905                         case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
906                             if (verified) {
907                                 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
908                                 needUpdate = true;
909                             }
910                             break;
911
912                         default:
913                             // Nothing to do
914                     }
915
916                     if (needUpdate) {
917                         mSettings.updateIntentFilterVerificationStatusLPw(
918                                 packageName, updatedStatus, userId);
919                         scheduleWritePackageRestrictionsLocked(userId);
920                     }
921                 }
922             }
923         }
924
925         @Override
926         public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
927                     ActivityIntentInfo filter, String packageName) {
928             if (!hasValidDomains(filter)) {
929                 return false;
930             }
931             IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
932             if (ivs == null) {
933                 ivs = createDomainVerificationState(verifierUid, userId, verificationId,
934                         packageName);
935             }
936             if (DEBUG_DOMAIN_VERIFICATION) {
937                 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
938             }
939             ivs.addFilter(filter);
940             return true;
941         }
942
943         private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
944                 int userId, int verificationId, String packageName) {
945             IntentFilterVerificationState ivs = new IntentFilterVerificationState(
946                     verifierUid, userId, packageName);
947             ivs.setPendingState();
948             synchronized (mPackages) {
949                 mIntentFilterVerificationStates.append(verificationId, ivs);
950                 mCurrentIntentFilterVerifications.add(verificationId);
951             }
952             return ivs;
953         }
954     }
955
956     private static boolean hasValidDomains(ActivityIntentInfo filter) {
957         return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
958                 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
959                         filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
960     }
961
962     // Set of pending broadcasts for aggregating enable/disable of components.
963     static class PendingPackageBroadcasts {
964         // for each user id, a map of <package name -> components within that package>
965         final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
966
967         public PendingPackageBroadcasts() {
968             mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
969         }
970
971         public ArrayList<String> get(int userId, String packageName) {
972             ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
973             return packages.get(packageName);
974         }
975
976         public void put(int userId, String packageName, ArrayList<String> components) {
977             ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
978             packages.put(packageName, components);
979         }
980
981         public void remove(int userId, String packageName) {
982             ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
983             if (packages != null) {
984                 packages.remove(packageName);
985             }
986         }
987
988         public void remove(int userId) {
989             mUidMap.remove(userId);
990         }
991
992         public int userIdCount() {
993             return mUidMap.size();
994         }
995
996         public int userIdAt(int n) {
997             return mUidMap.keyAt(n);
998         }
999
1000         public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1001             return mUidMap.get(userId);
1002         }
1003
1004         public int size() {
1005             // total number of pending broadcast entries across all userIds
1006             int num = 0;
1007             for (int i = 0; i< mUidMap.size(); i++) {
1008                 num += mUidMap.valueAt(i).size();
1009             }
1010             return num;
1011         }
1012
1013         public void clear() {
1014             mUidMap.clear();
1015         }
1016
1017         private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1018             ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1019             if (map == null) {
1020                 map = new ArrayMap<String, ArrayList<String>>();
1021                 mUidMap.put(userId, map);
1022             }
1023             return map;
1024         }
1025     }
1026     final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1027
1028     // Service Connection to remote media container service to copy
1029     // package uri's from external media onto secure containers
1030     // or internal storage.
1031     private IMediaContainerService mContainerService = null;
1032
1033     static final int SEND_PENDING_BROADCAST = 1;
1034     static final int MCS_BOUND = 3;
1035     static final int END_COPY = 4;
1036     static final int INIT_COPY = 5;
1037     static final int MCS_UNBIND = 6;
1038     static final int START_CLEANING_PACKAGE = 7;
1039     static final int FIND_INSTALL_LOC = 8;
1040     static final int POST_INSTALL = 9;
1041     static final int MCS_RECONNECT = 10;
1042     static final int MCS_GIVE_UP = 11;
1043     static final int UPDATED_MEDIA_STATUS = 12;
1044     static final int WRITE_SETTINGS = 13;
1045     static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1046     static final int PACKAGE_VERIFIED = 15;
1047     static final int CHECK_PENDING_VERIFICATION = 16;
1048     static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1049     static final int INTENT_FILTER_VERIFIED = 18;
1050     static final int WRITE_PACKAGE_LIST = 19;
1051
1052     static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1053
1054     // Delay time in millisecs
1055     static final int BROADCAST_DELAY = 10 * 1000;
1056
1057     static UserManagerService sUserManager;
1058
1059     // Stores a list of users whose package restrictions file needs to be updated
1060     private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1061
1062     final private DefaultContainerConnection mDefContainerConn =
1063             new DefaultContainerConnection();
1064     class DefaultContainerConnection implements ServiceConnection {
1065         public void onServiceConnected(ComponentName name, IBinder service) {
1066             if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1067             IMediaContainerService imcs =
1068                 IMediaContainerService.Stub.asInterface(service);
1069             mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1070         }
1071
1072         public void onServiceDisconnected(ComponentName name) {
1073             if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1074         }
1075     }
1076
1077     // Recordkeeping of restore-after-install operations that are currently in flight
1078     // between the Package Manager and the Backup Manager
1079     static class PostInstallData {
1080         public InstallArgs args;
1081         public PackageInstalledInfo res;
1082
1083         PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1084             args = _a;
1085             res = _r;
1086         }
1087     }
1088
1089     final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1090     int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1091
1092     // XML tags for backup/restore of various bits of state
1093     private static final String TAG_PREFERRED_BACKUP = "pa";
1094     private static final String TAG_DEFAULT_APPS = "da";
1095     private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1096
1097     private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1098     private static final String TAG_ALL_GRANTS = "rt-grants";
1099     private static final String TAG_GRANT = "grant";
1100     private static final String ATTR_PACKAGE_NAME = "pkg";
1101
1102     private static final String TAG_PERMISSION = "perm";
1103     private static final String ATTR_PERMISSION_NAME = "name";
1104     private static final String ATTR_IS_GRANTED = "g";
1105     private static final String ATTR_USER_SET = "set";
1106     private static final String ATTR_USER_FIXED = "fixed";
1107     private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1108
1109     // System/policy permission grants are not backed up
1110     private static final int SYSTEM_RUNTIME_GRANT_MASK =
1111             FLAG_PERMISSION_POLICY_FIXED
1112             | FLAG_PERMISSION_SYSTEM_FIXED
1113             | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1114
1115     // And we back up these user-adjusted states
1116     private static final int USER_RUNTIME_GRANT_MASK =
1117             FLAG_PERMISSION_USER_SET
1118             | FLAG_PERMISSION_USER_FIXED
1119             | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1120
1121     final @Nullable String mRequiredVerifierPackage;
1122     final @NonNull String mRequiredInstallerPackage;
1123     final @Nullable String mSetupWizardPackage;
1124     final @NonNull String mServicesSystemSharedLibraryPackageName;
1125     final @NonNull String mSharedSystemSharedLibraryPackageName;
1126
1127     private final PackageUsage mPackageUsage = new PackageUsage();
1128
1129     private class PackageUsage {
1130         private static final int WRITE_INTERVAL
1131             = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1132
1133         private final Object mFileLock = new Object();
1134         private final AtomicLong mLastWritten = new AtomicLong(0);
1135         private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1136
1137         private boolean mIsHistoricalPackageUsageAvailable = true;
1138
1139         boolean isHistoricalPackageUsageAvailable() {
1140             return mIsHistoricalPackageUsageAvailable;
1141         }
1142
1143         void write(boolean force) {
1144             if (force) {
1145                 writeInternal();
1146                 return;
1147             }
1148             if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1149                 && !DEBUG_DEXOPT) {
1150                 return;
1151             }
1152             if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1153                 new Thread("PackageUsage_DiskWriter") {
1154                     @Override
1155                     public void run() {
1156                         try {
1157                             writeInternal();
1158                         } finally {
1159                             mBackgroundWriteRunning.set(false);
1160                         }
1161                     }
1162                 }.start();
1163             }
1164         }
1165
1166         private void writeInternal() {
1167             synchronized (mPackages) {
1168                 synchronized (mFileLock) {
1169                     AtomicFile file = getFile();
1170                     FileOutputStream f = null;
1171                     try {
1172                         f = file.startWrite();
1173                         BufferedOutputStream out = new BufferedOutputStream(f);
1174                         FileUtils.setPermissions(file.getBaseFile().getPath(),
1175                                 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1176                         StringBuilder sb = new StringBuilder();
1177
1178                         sb.append(USAGE_FILE_MAGIC_VERSION_1);
1179                         sb.append('\n');
1180                         out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1181
1182                         for (PackageParser.Package pkg : mPackages.values()) {
1183                             if (pkg.getLatestPackageUseTimeInMills() == 0L) {
1184                                 continue;
1185                             }
1186                             sb.setLength(0);
1187                             sb.append(pkg.packageName);
1188                             for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) {
1189                                 sb.append(' ');
1190                                 sb.append(usageTimeInMillis);
1191                             }
1192                             sb.append('\n');
1193                             out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1194                         }
1195                         out.flush();
1196                         file.finishWrite(f);
1197                     } catch (IOException e) {
1198                         if (f != null) {
1199                             file.failWrite(f);
1200                         }
1201                         Log.e(TAG, "Failed to write package usage times", e);
1202                     }
1203                 }
1204             }
1205             mLastWritten.set(SystemClock.elapsedRealtime());
1206         }
1207
1208         void readLP() {
1209             synchronized (mFileLock) {
1210                 AtomicFile file = getFile();
1211                 BufferedInputStream in = null;
1212                 try {
1213                     in = new BufferedInputStream(file.openRead());
1214                     StringBuffer sb = new StringBuffer();
1215
1216                     String firstLine = readLine(in, sb);
1217                     if (firstLine == null) {
1218                         // Empty file. Do nothing.
1219                     } else if (USAGE_FILE_MAGIC_VERSION_1.equals(firstLine)) {
1220                         readVersion1LP(in, sb);
1221                     } else {
1222                         readVersion0LP(in, sb, firstLine);
1223                     }
1224                 } catch (FileNotFoundException expected) {
1225                     mIsHistoricalPackageUsageAvailable = false;
1226                 } catch (IOException e) {
1227                     Log.w(TAG, "Failed to read package usage times", e);
1228                 } finally {
1229                     IoUtils.closeQuietly(in);
1230                 }
1231             }
1232             mLastWritten.set(SystemClock.elapsedRealtime());
1233         }
1234
1235         private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine)
1236                 throws IOException {
1237             // Initial version of the file had no version number and stored one
1238             // package-timestamp pair per line.
1239             // Note that the first line has already been read from the InputStream.
1240             for (String line = firstLine; line != null; line = readLine(in, sb)) {
1241                 String[] tokens = line.split(" ");
1242                 if (tokens.length != 2) {
1243                     throw new IOException("Failed to parse " + line +
1244                             " as package-timestamp pair.");
1245                 }
1246
1247                 String packageName = tokens[0];
1248                 PackageParser.Package pkg = mPackages.get(packageName);
1249                 if (pkg == null) {
1250                     continue;
1251                 }
1252
1253                 long timestamp = parseAsLong(tokens[1]);
1254                 for (int reason = 0;
1255                         reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1256                         reason++) {
1257                     pkg.mLastPackageUsageTimeInMills[reason] = timestamp;
1258                 }
1259             }
1260         }
1261
1262         private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException {
1263             // Version 1 of the file started with the corresponding version
1264             // number and then stored a package name and eight timestamps per line.
1265             String line;
1266             while ((line = readLine(in, sb)) != null) {
1267                 String[] tokens = line.split(" ");
1268                 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) {
1269                     throw new IOException("Failed to parse " + line + " as a timestamp array.");
1270                 }
1271
1272                 String packageName = tokens[0];
1273                 PackageParser.Package pkg = mPackages.get(packageName);
1274                 if (pkg == null) {
1275                     continue;
1276                 }
1277
1278                 for (int reason = 0;
1279                         reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1280                         reason++) {
1281                     pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]);
1282                 }
1283             }
1284         }
1285
1286         private long parseAsLong(String token) throws IOException {
1287             try {
1288                 return Long.parseLong(token);
1289             } catch (NumberFormatException e) {
1290                 throw new IOException("Failed to parse " + token + " as a long.", e);
1291             }
1292         }
1293
1294         private String readLine(InputStream in, StringBuffer sb) throws IOException {
1295             return readToken(in, sb, '\n');
1296         }
1297
1298         private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1299                 throws IOException {
1300             sb.setLength(0);
1301             while (true) {
1302                 int ch = in.read();
1303                 if (ch == -1) {
1304                     if (sb.length() == 0) {
1305                         return null;
1306                     }
1307                     throw new IOException("Unexpected EOF");
1308                 }
1309                 if (ch == endOfToken) {
1310                     return sb.toString();
1311                 }
1312                 sb.append((char)ch);
1313             }
1314         }
1315
1316         private AtomicFile getFile() {
1317             File dataDir = Environment.getDataDirectory();
1318             File systemDir = new File(dataDir, "system");
1319             File fname = new File(systemDir, "package-usage.list");
1320             return new AtomicFile(fname);
1321         }
1322
1323         private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_";
1324         private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1";
1325     }
1326
1327     class PackageHandler extends Handler {
1328         private boolean mBound = false;
1329         final ArrayList<HandlerParams> mPendingInstalls =
1330             new ArrayList<HandlerParams>();
1331
1332         private boolean connectToService() {
1333             if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1334                     " DefaultContainerService");
1335             Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1336             Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1337             if (mContext.bindServiceAsUser(service, mDefContainerConn,
1338                     Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1339                 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1340                 mBound = true;
1341                 return true;
1342             }
1343             Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1344             return false;
1345         }
1346
1347         private void disconnectService() {
1348             mContainerService = null;
1349             mBound = false;
1350             Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1351             mContext.unbindService(mDefContainerConn);
1352             Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1353         }
1354
1355         PackageHandler(Looper looper) {
1356             super(looper);
1357         }
1358
1359         public void handleMessage(Message msg) {
1360             try {
1361                 doHandleMessage(msg);
1362             } finally {
1363                 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1364             }
1365         }
1366
1367         void doHandleMessage(Message msg) {
1368             switch (msg.what) {
1369                 case INIT_COPY: {
1370                     HandlerParams params = (HandlerParams) msg.obj;
1371                     int idx = mPendingInstalls.size();
1372                     if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1373                     // If a bind was already initiated we dont really
1374                     // need to do anything. The pending install
1375                     // will be processed later on.
1376                     if (!mBound) {
1377                         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1378                                 System.identityHashCode(mHandler));
1379                         // If this is the only one pending we might
1380                         // have to bind to the service again.
1381                         if (!connectToService()) {
1382                             Slog.e(TAG, "Failed to bind to media container service");
1383                             params.serviceError();
1384                             Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1385                                     System.identityHashCode(mHandler));
1386                             if (params.traceMethod != null) {
1387                                 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1388                                         params.traceCookie);
1389                             }
1390                             return;
1391                         } else {
1392                             // Once we bind to the service, the first
1393                             // pending request will be processed.
1394                             mPendingInstalls.add(idx, params);
1395                         }
1396                     } else {
1397                         mPendingInstalls.add(idx, params);
1398                         // Already bound to the service. Just make
1399                         // sure we trigger off processing the first request.
1400                         if (idx == 0) {
1401                             mHandler.sendEmptyMessage(MCS_BOUND);
1402                         }
1403                     }
1404                     break;
1405                 }
1406                 case MCS_BOUND: {
1407                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1408                     if (msg.obj != null) {
1409                         mContainerService = (IMediaContainerService) msg.obj;
1410                         Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1411                                 System.identityHashCode(mHandler));
1412                     }
1413                     if (mContainerService == null) {
1414                         if (!mBound) {
1415                             // Something seriously wrong since we are not bound and we are not
1416                             // waiting for connection. Bail out.
1417                             Slog.e(TAG, "Cannot bind to media container service");
1418                             for (HandlerParams params : mPendingInstalls) {
1419                                 // Indicate service bind error
1420                                 params.serviceError();
1421                                 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1422                                         System.identityHashCode(params));
1423                                 if (params.traceMethod != null) {
1424                                     Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1425                                             params.traceMethod, params.traceCookie);
1426                                 }
1427                                 return;
1428                             }
1429                             mPendingInstalls.clear();
1430                         } else {
1431                             Slog.w(TAG, "Waiting to connect to media container service");
1432                         }
1433                     } else if (mPendingInstalls.size() > 0) {
1434                         HandlerParams params = mPendingInstalls.get(0);
1435                         if (params != null) {
1436                             Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1437                                     System.identityHashCode(params));
1438                             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1439                             if (params.startCopy()) {
1440                                 // We are done...  look for more work or to
1441                                 // go idle.
1442                                 if (DEBUG_SD_INSTALL) Log.i(TAG,
1443                                         "Checking for more work or unbind...");
1444                                 // Delete pending install
1445                                 if (mPendingInstalls.size() > 0) {
1446                                     mPendingInstalls.remove(0);
1447                                 }
1448                                 if (mPendingInstalls.size() == 0) {
1449                                     if (mBound) {
1450                                         if (DEBUG_SD_INSTALL) Log.i(TAG,
1451                                                 "Posting delayed MCS_UNBIND");
1452                                         removeMessages(MCS_UNBIND);
1453                                         Message ubmsg = obtainMessage(MCS_UNBIND);
1454                                         // Unbind after a little delay, to avoid
1455                                         // continual thrashing.
1456                                         sendMessageDelayed(ubmsg, 10000);
1457                                     }
1458                                 } else {
1459                                     // There are more pending requests in queue.
1460                                     // Just post MCS_BOUND message to trigger processing
1461                                     // of next pending install.
1462                                     if (DEBUG_SD_INSTALL) Log.i(TAG,
1463                                             "Posting MCS_BOUND for next work");
1464                                     mHandler.sendEmptyMessage(MCS_BOUND);
1465                                 }
1466                             }
1467                             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1468                         }
1469                     } else {
1470                         // Should never happen ideally.
1471                         Slog.w(TAG, "Empty queue");
1472                     }
1473                     break;
1474                 }
1475                 case MCS_RECONNECT: {
1476                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1477                     if (mPendingInstalls.size() > 0) {
1478                         if (mBound) {
1479                             disconnectService();
1480                         }
1481                         if (!connectToService()) {
1482                             Slog.e(TAG, "Failed to bind to media container service");
1483                             for (HandlerParams params : mPendingInstalls) {
1484                                 // Indicate service bind error
1485                                 params.serviceError();
1486                                 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1487                                         System.identityHashCode(params));
1488                             }
1489                             mPendingInstalls.clear();
1490                         }
1491                     }
1492                     break;
1493                 }
1494                 case MCS_UNBIND: {
1495                     // If there is no actual work left, then time to unbind.
1496                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1497
1498                     if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1499                         if (mBound) {
1500                             if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1501
1502                             disconnectService();
1503                         }
1504                     } else if (mPendingInstalls.size() > 0) {
1505                         // There are more pending requests in queue.
1506                         // Just post MCS_BOUND message to trigger processing
1507                         // of next pending install.
1508                         mHandler.sendEmptyMessage(MCS_BOUND);
1509                     }
1510
1511                     break;
1512                 }
1513                 case MCS_GIVE_UP: {
1514                     if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1515                     HandlerParams params = mPendingInstalls.remove(0);
1516                     Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1517                             System.identityHashCode(params));
1518                     break;
1519                 }
1520                 case SEND_PENDING_BROADCAST: {
1521                     String packages[];
1522                     ArrayList<String> components[];
1523                     int size = 0;
1524                     int uids[];
1525                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1526                     synchronized (mPackages) {
1527                         if (mPendingBroadcasts == null) {
1528                             return;
1529                         }
1530                         size = mPendingBroadcasts.size();
1531                         if (size <= 0) {
1532                             // Nothing to be done. Just return
1533                             return;
1534                         }
1535                         packages = new String[size];
1536                         components = new ArrayList[size];
1537                         uids = new int[size];
1538                         int i = 0;  // filling out the above arrays
1539
1540                         for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1541                             int packageUserId = mPendingBroadcasts.userIdAt(n);
1542                             Iterator<Map.Entry<String, ArrayList<String>>> it
1543                                     = mPendingBroadcasts.packagesForUserId(packageUserId)
1544                                             .entrySet().iterator();
1545                             while (it.hasNext() && i < size) {
1546                                 Map.Entry<String, ArrayList<String>> ent = it.next();
1547                                 packages[i] = ent.getKey();
1548                                 components[i] = ent.getValue();
1549                                 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1550                                 uids[i] = (ps != null)
1551                                         ? UserHandle.getUid(packageUserId, ps.appId)
1552                                         : -1;
1553                                 i++;
1554                             }
1555                         }
1556                         size = i;
1557                         mPendingBroadcasts.clear();
1558                     }
1559                     // Send broadcasts
1560                     for (int i = 0; i < size; i++) {
1561                         sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1562                     }
1563                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1564                     break;
1565                 }
1566                 case START_CLEANING_PACKAGE: {
1567                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1568                     final String packageName = (String)msg.obj;
1569                     final int userId = msg.arg1;
1570                     final boolean andCode = msg.arg2 != 0;
1571                     synchronized (mPackages) {
1572                         if (userId == UserHandle.USER_ALL) {
1573                             int[] users = sUserManager.getUserIds();
1574                             for (int user : users) {
1575                                 mSettings.addPackageToCleanLPw(
1576                                         new PackageCleanItem(user, packageName, andCode));
1577                             }
1578                         } else {
1579                             mSettings.addPackageToCleanLPw(
1580                                     new PackageCleanItem(userId, packageName, andCode));
1581                         }
1582                     }
1583                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1584                     startCleaningPackages();
1585                 } break;
1586                 case POST_INSTALL: {
1587                     if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1588
1589                     PostInstallData data = mRunningInstalls.get(msg.arg1);
1590                     final boolean didRestore = (msg.arg2 != 0);
1591                     mRunningInstalls.delete(msg.arg1);
1592
1593                     if (data != null) {
1594                         InstallArgs args = data.args;
1595                         PackageInstalledInfo parentRes = data.res;
1596
1597                         final boolean grantPermissions = (args.installFlags
1598                                 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1599                         final boolean killApp = (args.installFlags
1600                                 & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1601                         final String[] grantedPermissions = args.installGrantPermissions;
1602
1603                         // Handle the parent package
1604                         handlePackagePostInstall(parentRes, grantPermissions, killApp,
1605                                 grantedPermissions, didRestore, args.installerPackageName,
1606                                 args.observer);
1607
1608                         // Handle the child packages
1609                         final int childCount = (parentRes.addedChildPackages != null)
1610                                 ? parentRes.addedChildPackages.size() : 0;
1611                         for (int i = 0; i < childCount; i++) {
1612                             PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1613                             handlePackagePostInstall(childRes, grantPermissions, killApp,
1614                                     grantedPermissions, false, args.installerPackageName,
1615                                     args.observer);
1616                         }
1617
1618                         // Log tracing if needed
1619                         if (args.traceMethod != null) {
1620                             Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1621                                     args.traceCookie);
1622                         }
1623                     } else {
1624                         Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1625                     }
1626
1627                     Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1628                 } break;
1629                 case UPDATED_MEDIA_STATUS: {
1630                     if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1631                     boolean reportStatus = msg.arg1 == 1;
1632                     boolean doGc = msg.arg2 == 1;
1633                     if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1634                     if (doGc) {
1635                         // Force a gc to clear up stale containers.
1636                         Runtime.getRuntime().gc();
1637                     }
1638                     if (msg.obj != null) {
1639                         @SuppressWarnings("unchecked")
1640                         Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1641                         if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1642                         // Unload containers
1643                         unloadAllContainers(args);
1644                     }
1645                     if (reportStatus) {
1646                         try {
1647                             if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1648                             PackageHelper.getMountService().finishMediaUpdate();
1649                         } catch (RemoteException e) {
1650                             Log.e(TAG, "MountService not running?");
1651                         }
1652                     }
1653                 } break;
1654                 case WRITE_SETTINGS: {
1655                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1656                     synchronized (mPackages) {
1657                         removeMessages(WRITE_SETTINGS);
1658                         removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1659                         mSettings.writeLPr();
1660                         mDirtyUsers.clear();
1661                     }
1662                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1663                 } break;
1664                 case WRITE_PACKAGE_RESTRICTIONS: {
1665                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1666                     synchronized (mPackages) {
1667                         removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1668                         for (int userId : mDirtyUsers) {
1669                             mSettings.writePackageRestrictionsLPr(userId);
1670                         }
1671                         mDirtyUsers.clear();
1672                     }
1673                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1674                 } break;
1675                 case WRITE_PACKAGE_LIST: {
1676                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1677                     synchronized (mPackages) {
1678                         removeMessages(WRITE_PACKAGE_LIST);
1679                         mSettings.writePackageListLPr(msg.arg1);
1680                     }
1681                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1682                 } break;
1683                 case CHECK_PENDING_VERIFICATION: {
1684                     final int verificationId = msg.arg1;
1685                     final PackageVerificationState state = mPendingVerification.get(verificationId);
1686
1687                     if ((state != null) && !state.timeoutExtended()) {
1688                         final InstallArgs args = state.getInstallArgs();
1689                         final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1690
1691                         Slog.i(TAG, "Verification timed out for " + originUri);
1692                         mPendingVerification.remove(verificationId);
1693
1694                         int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1695
1696                         if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1697                             Slog.i(TAG, "Continuing with installation of " + originUri);
1698                             state.setVerifierResponse(Binder.getCallingUid(),
1699                                     PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1700                             broadcastPackageVerified(verificationId, originUri,
1701                                     PackageManager.VERIFICATION_ALLOW,
1702                                     state.getInstallArgs().getUser());
1703                             try {
1704                                 ret = args.copyApk(mContainerService, true);
1705                             } catch (RemoteException e) {
1706                                 Slog.e(TAG, "Could not contact the ContainerService");
1707                             }
1708                         } else {
1709                             broadcastPackageVerified(verificationId, originUri,
1710                                     PackageManager.VERIFICATION_REJECT,
1711                                     state.getInstallArgs().getUser());
1712                         }
1713
1714                         Trace.asyncTraceEnd(
1715                                 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1716
1717                         processPendingInstall(args, ret);
1718                         mHandler.sendEmptyMessage(MCS_UNBIND);
1719                     }
1720                     break;
1721                 }
1722                 case PACKAGE_VERIFIED: {
1723                     final int verificationId = msg.arg1;
1724
1725                     final PackageVerificationState state = mPendingVerification.get(verificationId);
1726                     if (state == null) {
1727                         Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1728                         break;
1729                     }
1730
1731                     final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1732
1733                     state.setVerifierResponse(response.callerUid, response.code);
1734
1735                     if (state.isVerificationComplete()) {
1736                         mPendingVerification.remove(verificationId);
1737
1738                         final InstallArgs args = state.getInstallArgs();
1739                         final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1740
1741                         int ret;
1742                         if (state.isInstallAllowed()) {
1743                             ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1744                             broadcastPackageVerified(verificationId, originUri,
1745                                     response.code, state.getInstallArgs().getUser());
1746                             try {
1747                                 ret = args.copyApk(mContainerService, true);
1748                             } catch (RemoteException e) {
1749                                 Slog.e(TAG, "Could not contact the ContainerService");
1750                             }
1751                         } else {
1752                             ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1753                         }
1754
1755                         Trace.asyncTraceEnd(
1756                                 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1757
1758                         processPendingInstall(args, ret);
1759                         mHandler.sendEmptyMessage(MCS_UNBIND);
1760                     }
1761
1762                     break;
1763                 }
1764                 case START_INTENT_FILTER_VERIFICATIONS: {
1765                     IFVerificationParams params = (IFVerificationParams) msg.obj;
1766                     verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1767                             params.replacing, params.pkg);
1768                     break;
1769                 }
1770                 case INTENT_FILTER_VERIFIED: {
1771                     final int verificationId = msg.arg1;
1772
1773                     final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1774                             verificationId);
1775                     if (state == null) {
1776                         Slog.w(TAG, "Invalid IntentFilter verification token "
1777                                 + verificationId + " received");
1778                         break;
1779                     }
1780
1781                     final int userId = state.getUserId();
1782
1783                     if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1784                             "Processing IntentFilter verification with token:"
1785                             + verificationId + " and userId:" + userId);
1786
1787                     final IntentFilterVerificationResponse response =
1788                             (IntentFilterVerificationResponse) msg.obj;
1789
1790                     state.setVerifierResponse(response.callerUid, response.code);
1791
1792                     if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1793                             "IntentFilter verification with token:" + verificationId
1794                             + " and userId:" + userId
1795                             + " is settings verifier response with response code:"
1796                             + response.code);
1797
1798                     if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1799                         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1800                                 + response.getFailedDomainsString());
1801                     }
1802
1803                     if (state.isVerificationComplete()) {
1804                         mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1805                     } else {
1806                         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1807                                 "IntentFilter verification with token:" + verificationId
1808                                 + " was not said to be complete");
1809                     }
1810
1811                     break;
1812                 }
1813             }
1814         }
1815     }
1816
1817     private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1818             boolean killApp, String[] grantedPermissions,
1819             boolean launchedForRestore, String installerPackage,
1820             IPackageInstallObserver2 installObserver) {
1821         if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1822             // Send the removed broadcasts
1823             if (res.removedInfo != null) {
1824                 res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1825             }
1826
1827             // Now that we successfully installed the package, grant runtime
1828             // permissions if requested before broadcasting the install.
1829             if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1830                     >= Build.VERSION_CODES.M) {
1831                 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1832             }
1833
1834             final boolean update = res.removedInfo != null
1835                     && res.removedInfo.removedPackage != null;
1836
1837             // If this is the first time we have child packages for a disabled privileged
1838             // app that had no children, we grant requested runtime permissions to the new
1839             // children if the parent on the system image had them already granted.
1840             if (res.pkg.parentPackage != null) {
1841                 synchronized (mPackages) {
1842                     grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1843                 }
1844             }
1845
1846             synchronized (mPackages) {
1847                 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1848             }
1849
1850             final String packageName = res.pkg.applicationInfo.packageName;
1851             Bundle extras = new Bundle(1);
1852             extras.putInt(Intent.EXTRA_UID, res.uid);
1853
1854             // Determine the set of users who are adding this package for
1855             // the first time vs. those who are seeing an update.
1856             int[] firstUsers = EMPTY_INT_ARRAY;
1857             int[] updateUsers = EMPTY_INT_ARRAY;
1858             if (res.origUsers == null || res.origUsers.length == 0) {
1859                 firstUsers = res.newUsers;
1860             } else {
1861                 for (int newUser : res.newUsers) {
1862                     boolean isNew = true;
1863                     for (int origUser : res.origUsers) {
1864                         if (origUser == newUser) {
1865                             isNew = false;
1866                             break;
1867                         }
1868                     }
1869                     if (isNew) {
1870                         firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1871                     } else {
1872                         updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1873                     }
1874                 }
1875             }
1876
1877             // Send installed broadcasts if the install/update is not ephemeral
1878             if (!isEphemeral(res.pkg)) {
1879                 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1880
1881                 // Send added for users that see the package for the first time
1882                 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1883                         extras, 0 /*flags*/, null /*targetPackage*/,
1884                         null /*finishedReceiver*/, firstUsers);
1885
1886                 // Send added for users that don't see the package for the first time
1887                 if (update) {
1888                     extras.putBoolean(Intent.EXTRA_REPLACING, true);
1889                 }
1890                 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1891                         extras, 0 /*flags*/, null /*targetPackage*/,
1892                         null /*finishedReceiver*/, updateUsers);
1893
1894                 // Send replaced for users that don't see the package for the first time
1895                 if (update) {
1896                     sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1897                             packageName, extras, 0 /*flags*/,
1898                             null /*targetPackage*/, null /*finishedReceiver*/,
1899                             updateUsers);
1900                     sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1901                             null /*package*/, null /*extras*/, 0 /*flags*/,
1902                             packageName /*targetPackage*/,
1903                             null /*finishedReceiver*/, updateUsers);
1904                 } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1905                     // First-install and we did a restore, so we're responsible for the
1906                     // first-launch broadcast.
1907                     if (DEBUG_BACKUP) {
1908                         Slog.i(TAG, "Post-restore of " + packageName
1909                                 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1910                     }
1911                     sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1912                 }
1913
1914                 // Send broadcast package appeared if forward locked/external for all users
1915                 // treat asec-hosted packages like removable media on upgrade
1916                 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1917                     if (DEBUG_INSTALL) {
1918                         Slog.i(TAG, "upgrading pkg " + res.pkg
1919                                 + " is ASEC-hosted -> AVAILABLE");
1920                     }
1921                     final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1922                     ArrayList<String> pkgList = new ArrayList<>(1);
1923                     pkgList.add(packageName);
1924                     sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1925                 }
1926             }
1927
1928             // Work that needs to happen on first install within each user
1929             if (firstUsers != null && firstUsers.length > 0) {
1930                 synchronized (mPackages) {
1931                     for (int userId : firstUsers) {
1932                         // If this app is a browser and it's newly-installed for some
1933                         // users, clear any default-browser state in those users. The
1934                         // app's nature doesn't depend on the user, so we can just check
1935                         // its browser nature in any user and generalize.
1936                         if (packageIsBrowser(packageName, userId)) {
1937                             mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1938                         }
1939
1940                         // We may also need to apply pending (restored) runtime
1941                         // permission grants within these users.
1942                         mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1943                     }
1944                 }
1945             }
1946
1947             // Log current value of "unknown sources" setting
1948             EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1949                     getUnknownSourcesSettings());
1950
1951             // Force a gc to clear up things
1952             Runtime.getRuntime().gc();
1953
1954             // Remove the replaced package's older resources safely now
1955             // We delete after a gc for applications  on sdcard.
1956             if (res.removedInfo != null && res.removedInfo.args != null) {
1957                 synchronized (mInstallLock) {
1958                     res.removedInfo.args.doPostDeleteLI(true);
1959                 }
1960             }
1961         }
1962
1963         // If someone is watching installs - notify them
1964         if (installObserver != null) {
1965             try {
1966                 Bundle extras = extrasForInstallResult(res);
1967                 installObserver.onPackageInstalled(res.name, res.returnCode,
1968                         res.returnMsg, extras);
1969             } catch (RemoteException e) {
1970                 Slog.i(TAG, "Observer no longer exists.");
1971             }
1972         }
1973     }
1974
1975     private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1976             PackageParser.Package pkg) {
1977         if (pkg.parentPackage == null) {
1978             return;
1979         }
1980         if (pkg.requestedPermissions == null) {
1981             return;
1982         }
1983         final PackageSetting disabledSysParentPs = mSettings
1984                 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1985         if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1986                 || !disabledSysParentPs.isPrivileged()
1987                 || (disabledSysParentPs.childPackageNames != null
1988                         && !disabledSysParentPs.childPackageNames.isEmpty())) {
1989             return;
1990         }
1991         final int[] allUserIds = sUserManager.getUserIds();
1992         final int permCount = pkg.requestedPermissions.size();
1993         for (int i = 0; i < permCount; i++) {
1994             String permission = pkg.requestedPermissions.get(i);
1995             BasePermission bp = mSettings.mPermissions.get(permission);
1996             if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1997                 continue;
1998             }
1999             for (int userId : allUserIds) {
2000                 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2001                         permission, userId)) {
2002                     grantRuntimePermission(pkg.packageName, permission, userId);
2003                 }
2004             }
2005         }
2006     }
2007
2008     private StorageEventListener mStorageListener = new StorageEventListener() {
2009         @Override
2010         public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2011             if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2012                 if (vol.state == VolumeInfo.STATE_MOUNTED) {
2013                     final String volumeUuid = vol.getFsUuid();
2014
2015                     // Clean up any users or apps that were removed or recreated
2016                     // while this volume was missing
2017                     reconcileUsers(volumeUuid);
2018                     reconcileApps(volumeUuid);
2019
2020                     // Clean up any install sessions that expired or were
2021                     // cancelled while this volume was missing
2022                     mInstallerService.onPrivateVolumeMounted(volumeUuid);
2023
2024                     loadPrivatePackages(vol);
2025
2026                 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2027                     unloadPrivatePackages(vol);
2028                 }
2029             }
2030
2031             if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2032                 if (vol.state == VolumeInfo.STATE_MOUNTED) {
2033                     updateExternalMediaStatus(true, false);
2034                 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2035                     updateExternalMediaStatus(false, false);
2036                 }
2037             }
2038         }
2039
2040         @Override
2041         public void onVolumeForgotten(String fsUuid) {
2042             if (TextUtils.isEmpty(fsUuid)) {
2043                 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2044                 return;
2045             }
2046
2047             // Remove any apps installed on the forgotten volume
2048             synchronized (mPackages) {
2049                 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2050                 for (PackageSetting ps : packages) {
2051                     Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2052                     deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
2053                             UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2054                 }
2055
2056                 mSettings.onVolumeForgotten(fsUuid);
2057                 mSettings.writeLPr();
2058             }
2059         }
2060     };
2061
2062     private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2063             String[] grantedPermissions) {
2064         for (int userId : userIds) {
2065             grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2066         }
2067
2068         // We could have touched GID membership, so flush out packages.list
2069         synchronized (mPackages) {
2070             mSettings.writePackageListLPr();
2071         }
2072     }
2073
2074     private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2075             String[] grantedPermissions) {
2076         SettingBase sb = (SettingBase) pkg.mExtras;
2077         if (sb == null) {
2078             return;
2079         }
2080
2081         PermissionsState permissionsState = sb.getPermissionsState();
2082
2083         final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2084                 | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2085
2086         for (String permission : pkg.requestedPermissions) {
2087             final BasePermission bp;
2088             synchronized (mPackages) {
2089                 bp = mSettings.mPermissions.get(permission);
2090             }
2091             if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2092                     && (grantedPermissions == null
2093                            || ArrayUtils.contains(grantedPermissions, permission))) {
2094                 final int flags = permissionsState.getPermissionFlags(permission, userId);
2095                 // Installer cannot change immutable permissions.
2096                 if ((flags & immutableFlags) == 0) {
2097                     grantRuntimePermission(pkg.packageName, permission, userId);
2098                 }
2099             }
2100         }
2101     }
2102
2103     Bundle extrasForInstallResult(PackageInstalledInfo res) {
2104         Bundle extras = null;
2105         switch (res.returnCode) {
2106             case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2107                 extras = new Bundle();
2108                 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2109                         res.origPermission);
2110                 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2111                         res.origPackage);
2112                 break;
2113             }
2114             case PackageManager.INSTALL_SUCCEEDED: {
2115                 extras = new Bundle();
2116                 extras.putBoolean(Intent.EXTRA_REPLACING,
2117                         res.removedInfo != null && res.removedInfo.removedPackage != null);
2118                 break;
2119             }
2120         }
2121         return extras;
2122     }
2123
2124     void scheduleWriteSettingsLocked() {
2125         if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2126             mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2127         }
2128     }
2129
2130     void scheduleWritePackageListLocked(int userId) {
2131         if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2132             Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2133             msg.arg1 = userId;
2134             mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2135         }
2136     }
2137
2138     void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2139         final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2140         scheduleWritePackageRestrictionsLocked(userId);
2141     }
2142
2143     void scheduleWritePackageRestrictionsLocked(int userId) {
2144         final int[] userIds = (userId == UserHandle.USER_ALL)
2145                 ? sUserManager.getUserIds() : new int[]{userId};
2146         for (int nextUserId : userIds) {
2147             if (!sUserManager.exists(nextUserId)) return;
2148             mDirtyUsers.add(nextUserId);
2149             if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2150                 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2151             }
2152         }
2153     }
2154
2155     public static PackageManagerService main(Context context, Installer installer,
2156             boolean factoryTest, boolean onlyCore) {
2157         // Self-check for initial settings.
2158         PackageManagerServiceCompilerMapping.checkProperties();
2159
2160         PackageManagerService m = new PackageManagerService(context, installer,
2161                 factoryTest, onlyCore);
2162         m.enableSystemUserPackages();
2163         // Disable any carrier apps. We do this very early in boot to prevent the apps from being
2164         // disabled after already being started.
2165         CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
2166                 UserHandle.USER_SYSTEM);
2167         ServiceManager.addService("package", m);
2168         return m;
2169     }
2170
2171     private void enableSystemUserPackages() {
2172         if (!UserManager.isSplitSystemUser()) {
2173             return;
2174         }
2175         // For system user, enable apps based on the following conditions:
2176         // - app is whitelisted or belong to one of these groups:
2177         //   -- system app which has no launcher icons
2178         //   -- system app which has INTERACT_ACROSS_USERS permission
2179         //   -- system IME app
2180         // - app is not in the blacklist
2181         AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2182         Set<String> enableApps = new ArraySet<>();
2183         enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2184                 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2185                 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2186         ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2187         enableApps.addAll(wlApps);
2188         enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2189                 /* systemAppsOnly */ false, UserHandle.SYSTEM));
2190         ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2191         enableApps.removeAll(blApps);
2192         Log.i(TAG, "Applications installed for system user: " + enableApps);
2193         List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2194                 UserHandle.SYSTEM);
2195         final int allAppsSize = allAps.size();
2196         synchronized (mPackages) {
2197             for (int i = 0; i < allAppsSize; i++) {
2198                 String pName = allAps.get(i);
2199                 PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2200                 // Should not happen, but we shouldn't be failing if it does
2201                 if (pkgSetting == null) {
2202                     continue;
2203                 }
2204                 boolean install = enableApps.contains(pName);
2205                 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2206                     Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2207                             + " for system user");
2208                     pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2209                 }
2210             }
2211         }
2212     }
2213
2214     private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2215         DisplayManager displayManager = (DisplayManager) context.getSystemService(
2216                 Context.DISPLAY_SERVICE);
2217         displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2218     }
2219
2220     public PackageManagerService(Context context, Installer installer,
2221             boolean factoryTest, boolean onlyCore) {
2222         EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2223                 SystemClock.uptimeMillis());
2224
2225         if (mSdkVersion <= 0) {
2226             Slog.w(TAG, "**** ro.build.version.sdk not set!");
2227         }
2228
2229         mContext = context;
2230         mFactoryTest = factoryTest;
2231         mOnlyCore = onlyCore;
2232         mMetrics = new DisplayMetrics();
2233         mSettings = new Settings(mPackages);
2234         mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2235                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2236         mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2237                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2238         mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2239                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2240         mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2241                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2242         mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2243                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2244         mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2245                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2246
2247         String separateProcesses = SystemProperties.get("debug.separate_processes");
2248         if (separateProcesses != null && separateProcesses.length() > 0) {
2249             if ("*".equals(separateProcesses)) {
2250                 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2251                 mSeparateProcesses = null;
2252                 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2253             } else {
2254                 mDefParseFlags = 0;
2255                 mSeparateProcesses = separateProcesses.split(",");
2256                 Slog.w(TAG, "Running with debug.separate_processes: "
2257                         + separateProcesses);
2258             }
2259         } else {
2260             mDefParseFlags = 0;
2261             mSeparateProcesses = null;
2262         }
2263
2264         mInstaller = installer;
2265         mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2266                 "*dexopt*");
2267         mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2268
2269         mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2270                 FgThread.get().getLooper());
2271
2272         getDefaultDisplayMetrics(context, mMetrics);
2273
2274         SystemConfig systemConfig = SystemConfig.getInstance();
2275         mGlobalGids = systemConfig.getGlobalGids();
2276         mSystemPermissions = systemConfig.getSystemPermissions();
2277         mAvailableFeatures = systemConfig.getAvailableFeatures();
2278
2279         synchronized (mInstallLock) {
2280         // writer
2281         synchronized (mPackages) {
2282             mHandlerThread = new ServiceThread(TAG,
2283                     Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2284             mHandlerThread.start();
2285             mHandler = new PackageHandler(mHandlerThread.getLooper());
2286             mProcessLoggingHandler = new ProcessLoggingHandler();
2287             Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2288
2289             File dataDir = Environment.getDataDirectory();
2290             mAppInstallDir = new File(dataDir, "app");
2291             mAppLib32InstallDir = new File(dataDir, "app-lib");
2292             mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2293             mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2294             mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2295
2296             sUserManager = new UserManagerService(context, this, mPackages);
2297
2298             // Propagate permission configuration in to package manager.
2299             ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2300                     = systemConfig.getPermissions();
2301             for (int i=0; i<permConfig.size(); i++) {
2302                 SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2303                 BasePermission bp = mSettings.mPermissions.get(perm.name);
2304                 if (bp == null) {
2305                     bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2306                     mSettings.mPermissions.put(perm.name, bp);
2307                 }
2308                 if (perm.gids != null) {
2309                     bp.setGids(perm.gids, perm.perUser);
2310                 }
2311             }
2312
2313             ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2314             for (int i=0; i<libConfig.size(); i++) {
2315                 mSharedLibraries.put(libConfig.keyAt(i),
2316                         new SharedLibraryEntry(libConfig.valueAt(i), null));
2317             }
2318
2319             mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2320
2321             mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2322
2323             String customResolverActivity = Resources.getSystem().getString(
2324                     R.string.config_customResolverActivity);
2325             if (TextUtils.isEmpty(customResolverActivity)) {
2326                 customResolverActivity = null;
2327             } else {
2328                 mCustomResolverComponentName = ComponentName.unflattenFromString(
2329                         customResolverActivity);
2330             }
2331
2332             long startTime = SystemClock.uptimeMillis();
2333
2334             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2335                     startTime);
2336
2337             // Set flag to monitor and not change apk file paths when
2338             // scanning install directories.
2339             final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2340
2341             final String bootClassPath = System.getenv("BOOTCLASSPATH");
2342             final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2343
2344             if (bootClassPath == null) {
2345                 Slog.w(TAG, "No BOOTCLASSPATH found!");
2346             }
2347
2348             if (systemServerClassPath == null) {
2349                 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2350             }
2351
2352             final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2353             final String[] dexCodeInstructionSets =
2354                     getDexCodeInstructionSets(
2355                             allInstructionSets.toArray(new String[allInstructionSets.size()]));
2356
2357             /**
2358              * Ensure all external libraries have had dexopt run on them.
2359              */
2360             if (mSharedLibraries.size() > 0) {
2361                 // NOTE: For now, we're compiling these system "shared libraries"
2362                 // (and framework jars) into all available architectures. It's possible
2363                 // to compile them only when we come across an app that uses them (there's
2364                 // already logic for that in scanPackageLI) but that adds some complexity.
2365                 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2366                     for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2367                         final String lib = libEntry.path;
2368                         if (lib == null) {
2369                             continue;
2370                         }
2371
2372                         try {
2373                             // Shared libraries do not have profiles so we perform a full
2374                             // AOT compilation (if needed).
2375                             int dexoptNeeded = DexFile.getDexOptNeeded(
2376                                     lib, dexCodeInstructionSet,
2377                                     getCompilerFilterForReason(REASON_SHARED_APK),
2378                                     false /* newProfile */);
2379                             if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2380                                 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2381                                         dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2382                                         getCompilerFilterForReason(REASON_SHARED_APK),
2383                                         StorageManager.UUID_PRIVATE_INTERNAL,
2384                                         SKIP_SHARED_LIBRARY_CHECK);
2385                             }
2386                         } catch (FileNotFoundException e) {
2387                             Slog.w(TAG, "Library not found: " + lib);
2388                         } catch (IOException | InstallerException e) {
2389                             Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2390                                     + e.getMessage());
2391                         }
2392                     }
2393                 }
2394             }
2395
2396             File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2397
2398             final VersionInfo ver = mSettings.getInternalVersion();
2399             mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2400
2401             // when upgrading from pre-M, promote system app permissions from install to runtime
2402             mPromoteSystemApps =
2403                     mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2404
2405             // When upgrading from pre-N, we need to handle package extraction like first boot,
2406             // as there is no profiling data available.
2407             mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2408
2409             // save off the names of pre-existing system packages prior to scanning; we don't
2410             // want to automatically grant runtime permissions for new system apps
2411             if (mPromoteSystemApps) {
2412                 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2413                 while (pkgSettingIter.hasNext()) {
2414                     PackageSetting ps = pkgSettingIter.next();
2415                     if (isSystemApp(ps)) {
2416                         mExistingSystemPackages.add(ps.name);
2417                     }
2418                 }
2419             }
2420
2421             // Collect vendor overlay packages.
2422             // (Do this before scanning any apps.)
2423             // For security and version matching reason, only consider
2424             // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2425             File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2426             scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2427                     | PackageParser.PARSE_IS_SYSTEM
2428                     | PackageParser.PARSE_IS_SYSTEM_DIR
2429                     | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2430
2431             // Find base frameworks (resource packages without code).
2432             scanDirTracedLI(frameworkDir, mDefParseFlags
2433                     | PackageParser.PARSE_IS_SYSTEM
2434                     | PackageParser.PARSE_IS_SYSTEM_DIR
2435                     | PackageParser.PARSE_IS_PRIVILEGED,
2436                     scanFlags | SCAN_NO_DEX, 0);
2437
2438             // Collected privileged system packages.
2439             final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2440             scanDirTracedLI(privilegedAppDir, mDefParseFlags
2441                     | PackageParser.PARSE_IS_SYSTEM
2442                     | PackageParser.PARSE_IS_SYSTEM_DIR
2443                     | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2444
2445             // Collect ordinary system packages.
2446             final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2447             scanDirTracedLI(systemAppDir, mDefParseFlags
2448                     | PackageParser.PARSE_IS_SYSTEM
2449                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2450
2451             // Collect all vendor packages.
2452             File vendorAppDir = new File("/vendor/app");
2453             try {
2454                 vendorAppDir = vendorAppDir.getCanonicalFile();
2455             } catch (IOException e) {
2456                 // failed to look up canonical path, continue with original one
2457             }
2458             scanDirTracedLI(vendorAppDir, mDefParseFlags
2459                     | PackageParser.PARSE_IS_SYSTEM
2460                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2461
2462             // Collect all OEM packages.
2463             final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2464             scanDirTracedLI(oemAppDir, mDefParseFlags
2465                     | PackageParser.PARSE_IS_SYSTEM
2466                     | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2467
2468             // Prune any system packages that no longer exist.
2469             final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2470             if (!mOnlyCore) {
2471                 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2472                 while (psit.hasNext()) {
2473                     PackageSetting ps = psit.next();
2474
2475                     /*
2476                      * If this is not a system app, it can't be a
2477                      * disable system app.
2478                      */
2479                     if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2480                         continue;
2481                     }
2482
2483                     /*
2484                      * If the package is scanned, it's not erased.
2485                      */
2486                     final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2487                     if (scannedPkg != null) {
2488                         /*
2489                          * If the system app is both scanned and in the
2490                          * disabled packages list, then it must have been
2491                          * added via OTA. Remove it from the currently
2492                          * scanned package so the previously user-installed
2493                          * application can be scanned.
2494                          */
2495                         if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2496                             logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2497                                     + ps.name + "; removing system app.  Last known codePath="
2498                                     + ps.codePathString + ", installStatus=" + ps.installStatus
2499                                     + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2500                                     + scannedPkg.mVersionCode);
2501                             removePackageLI(scannedPkg, true);
2502                             mExpectingBetter.put(ps.name, ps.codePath);
2503                         }
2504
2505                         continue;
2506                     }
2507
2508                     if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2509                         psit.remove();
2510                         logCriticalInfo(Log.WARN, "System package " + ps.name
2511                                 + " no longer exists; it's data will be wiped");
2512                         // Actual deletion of code and data will be handled by later
2513                         // reconciliation step
2514                     } else {
2515                         final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2516                         if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2517                             possiblyDeletedUpdatedSystemApps.add(ps.name);
2518                         }
2519                     }
2520                 }
2521             }
2522
2523             //look for any incomplete package installations
2524             ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2525             for (int i = 0; i < deletePkgsList.size(); i++) {
2526                 // Actual deletion of code and data will be handled by later
2527                 // reconciliation step
2528                 final String packageName = deletePkgsList.get(i).name;
2529                 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2530                 synchronized (mPackages) {
2531                     mSettings.removePackageLPw(packageName);
2532                 }
2533             }
2534
2535             //delete tmp files
2536             deleteTempPackageFiles();
2537
2538             // Remove any shared userIDs that have no associated packages
2539             mSettings.pruneSharedUsersLPw();
2540
2541             if (!mOnlyCore) {
2542                 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2543                         SystemClock.uptimeMillis());
2544                 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2545
2546                 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2547                         | PackageParser.PARSE_FORWARD_LOCK,
2548                         scanFlags | SCAN_REQUIRE_KNOWN, 0);
2549
2550                 scanDirLI(mEphemeralInstallDir, mDefParseFlags
2551                         | PackageParser.PARSE_IS_EPHEMERAL,
2552                         scanFlags | SCAN_REQUIRE_KNOWN, 0);
2553
2554                 /**
2555                  * Remove disable package settings for any updated system
2556                  * apps that were removed via an OTA. If they're not a
2557                  * previously-updated app, remove them completely.
2558                  * Otherwise, just revoke their system-level permissions.
2559                  */
2560                 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2561                     PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2562                     mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2563
2564                     String msg;
2565                     if (deletedPkg == null) {
2566                         msg = "Updated system package " + deletedAppName
2567                                 + " no longer exists; it's data will be wiped";
2568                         // Actual deletion of code and data will be handled by later
2569                         // reconciliation step
2570                     } else {
2571                         msg = "Updated system app + " + deletedAppName
2572                                 + " no longer present; removing system privileges for "
2573                                 + deletedAppName;
2574
2575                         deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2576
2577                         PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2578                         deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2579                     }
2580                     logCriticalInfo(Log.WARN, msg);
2581                 }
2582
2583                 /**
2584                  * Make sure all system apps that we expected to appear on
2585                  * the userdata partition actually showed up. If they never
2586                  * appeared, crawl back and revive the system version.
2587                  */
2588                 for (int i = 0; i < mExpectingBetter.size(); i++) {
2589                     final String packageName = mExpectingBetter.keyAt(i);
2590                     if (!mPackages.containsKey(packageName)) {
2591                         final File scanFile = mExpectingBetter.valueAt(i);
2592
2593                         logCriticalInfo(Log.WARN, "Expected better " + packageName
2594                                 + " but never showed up; reverting to system");
2595
2596                         int reparseFlags = mDefParseFlags;
2597                         if (FileUtils.contains(privilegedAppDir, scanFile)) {
2598                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2599                                     | PackageParser.PARSE_IS_SYSTEM_DIR
2600                                     | PackageParser.PARSE_IS_PRIVILEGED;
2601                         } else if (FileUtils.contains(systemAppDir, scanFile)) {
2602                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2603                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
2604                         } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2605                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2606                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
2607                         } else if (FileUtils.contains(oemAppDir, scanFile)) {
2608                             reparseFlags = PackageParser.PARSE_IS_SYSTEM
2609                                     | PackageParser.PARSE_IS_SYSTEM_DIR;
2610                         } else {
2611                             Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2612                             continue;
2613                         }
2614
2615                         mSettings.enableSystemPackageLPw(packageName);
2616
2617                         try {
2618                             scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2619                         } catch (PackageManagerException e) {
2620                             Slog.e(TAG, "Failed to parse original system package: "
2621                                     + e.getMessage());
2622                         }
2623                     }
2624                 }
2625             }
2626             mExpectingBetter.clear();
2627
2628             // Resolve protected action filters. Only the setup wizard is allowed to
2629             // have a high priority filter for these actions.
2630             mSetupWizardPackage = getSetupWizardPackageName();
2631             if (mProtectedFilters.size() > 0) {
2632                 if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2633                     Slog.i(TAG, "No setup wizard;"
2634                         + " All protected intents capped to priority 0");
2635                 }
2636                 for (ActivityIntentInfo filter : mProtectedFilters) {
2637                     if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2638                         if (DEBUG_FILTERS) {
2639                             Slog.i(TAG, "Found setup wizard;"
2640                                 + " allow priority " + filter.getPriority() + ";"
2641                                 + " package: " + filter.activity.info.packageName
2642                                 + " activity: " + filter.activity.className
2643                                 + " priority: " + filter.getPriority());
2644                         }
2645                         // skip setup wizard; allow it to keep the high priority filter
2646                         continue;
2647                     }
2648                     Slog.w(TAG, "Protected action; cap priority to 0;"
2649                             + " package: " + filter.activity.info.packageName
2650                             + " activity: " + filter.activity.className
2651                             + " origPrio: " + filter.getPriority());
2652                     filter.setPriority(0);
2653                 }
2654             }
2655             mDeferProtectedFilters = false;
2656             mProtectedFilters.clear();
2657
2658             // Now that we know all of the shared libraries, update all clients to have
2659             // the correct library paths.
2660             updateAllSharedLibrariesLPw();
2661
2662             for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2663                 // NOTE: We ignore potential failures here during a system scan (like
2664                 // the rest of the commands above) because there's precious little we
2665                 // can do about it. A settings error is reported, though.
2666                 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2667                         false /* boot complete */);
2668             }
2669
2670             // Now that we know all the packages we are keeping,
2671             // read and update their last usage times.
2672             mPackageUsage.readLP();
2673
2674             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2675                     SystemClock.uptimeMillis());
2676             Slog.i(TAG, "Time to scan packages: "
2677                     + ((SystemClock.uptimeMillis()-startTime)/1000f)
2678                     + " seconds");
2679
2680             // If the platform SDK has changed since the last time we booted,
2681             // we need to re-grant app permission to catch any new ones that
2682             // appear.  This is really a hack, and means that apps can in some
2683             // cases get permissions that the user didn't initially explicitly
2684             // allow...  it would be nice to have some better way to handle
2685             // this situation.
2686             int updateFlags = UPDATE_PERMISSIONS_ALL;
2687             if (ver.sdkVersion != mSdkVersion) {
2688                 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2689                         + mSdkVersion + "; regranting permissions for internal storage");
2690                 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2691             }
2692             updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2693             ver.sdkVersion = mSdkVersion;
2694
2695             // If this is the first boot or an update from pre-M, and it is a normal
2696             // boot, then we need to initialize the default preferred apps across
2697             // all defined users.
2698             if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2699                 for (UserInfo user : sUserManager.getUsers(true)) {
2700                     mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2701                     applyFactoryDefaultBrowserLPw(user.id);
2702                     primeDomainVerificationsLPw(user.id);
2703                 }
2704             }
2705
2706             // Prepare storage for system user really early during boot,
2707             // since core system apps like SettingsProvider and SystemUI
2708             // can't wait for user to start
2709             final int storageFlags;
2710             if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2711                 storageFlags = StorageManager.FLAG_STORAGE_DE;
2712             } else {
2713                 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2714             }
2715             reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2716                     storageFlags);
2717
2718             // If this is first boot after an OTA, and a normal boot, then
2719             // we need to clear code cache directories.
2720             // Note that we do *not* clear the application profiles. These remain valid
2721             // across OTAs and are used to drive profile verification (post OTA) and
2722             // profile compilation (without waiting to collect a fresh set of profiles).
2723             if (mIsUpgrade && !onlyCore) {
2724                 Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2725                 for (int i = 0; i < mSettings.mPackages.size(); i++) {
2726                     final PackageSetting ps = mSettings.mPackages.valueAt(i);
2727                     if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2728                         // No apps are running this early, so no need to freeze
2729                         clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2730                                 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2731                                         | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2732                     }
2733                 }
2734                 ver.fingerprint = Build.FINGERPRINT;
2735             }
2736
2737             checkDefaultBrowser();
2738
2739             // clear only after permissions and other defaults have been updated
2740             mExistingSystemPackages.clear();
2741             mPromoteSystemApps = false;
2742
2743             // All the changes are done during package scanning.
2744             ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2745
2746             // can downgrade to reader
2747             mSettings.writeLPr();
2748
2749             // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2750             // early on (before the package manager declares itself as early) because other
2751             // components in the system server might ask for package contexts for these apps.
2752             //
2753             // Note that "onlyCore" in this context means the system is encrypted or encrypting
2754             // (i.e, that the data partition is unavailable).
2755             if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2756                 long start = System.nanoTime();
2757                 List<PackageParser.Package> coreApps = new ArrayList<>();
2758                 for (PackageParser.Package pkg : mPackages.values()) {
2759                     if (pkg.coreApp) {
2760                         coreApps.add(pkg);
2761                     }
2762                 }
2763
2764                 int[] stats = performDexOpt(coreApps, false,
2765                         getCompilerFilterForReason(REASON_CORE_APP));
2766
2767                 final int elapsedTimeSeconds =
2768                         (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2769                 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2770
2771                 if (DEBUG_DEXOPT) {
2772                     Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2773                             stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2774                 }
2775
2776
2777                 // TODO: Should we log these stats to tron too ?
2778                 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2779                 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2780                 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2781                 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2782             }
2783
2784             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2785                     SystemClock.uptimeMillis());
2786
2787             if (!mOnlyCore) {
2788                 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2789                 mRequiredInstallerPackage = getRequiredInstallerLPr();
2790                 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2791                 mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2792                         mIntentFilterVerifierComponent);
2793                 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2794                         PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2795                 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2796                         PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2797             } else {
2798                 mRequiredVerifierPackage = null;
2799                 mRequiredInstallerPackage = null;
2800                 mIntentFilterVerifierComponent = null;
2801                 mIntentFilterVerifier = null;
2802                 mServicesSystemSharedLibraryPackageName = null;
2803                 mSharedSystemSharedLibraryPackageName = null;
2804             }
2805
2806             mInstallerService = new PackageInstallerService(context, this);
2807
2808             final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2809             final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2810             // both the installer and resolver must be present to enable ephemeral
2811             if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2812                 if (DEBUG_EPHEMERAL) {
2813                     Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2814                             + " installer:" + ephemeralInstallerComponent);
2815                 }
2816                 mEphemeralResolverComponent = ephemeralResolverComponent;
2817                 mEphemeralInstallerComponent = ephemeralInstallerComponent;
2818                 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2819                 mEphemeralResolverConnection =
2820                         new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2821             } else {
2822                 if (DEBUG_EPHEMERAL) {
2823                     final String missingComponent =
2824                             (ephemeralResolverComponent == null)
2825                             ? (ephemeralInstallerComponent == null)
2826                                     ? "resolver and installer"
2827                                     : "resolver"
2828                             : "installer";
2829                     Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2830                 }
2831                 mEphemeralResolverComponent = null;
2832                 mEphemeralInstallerComponent = null;
2833                 mEphemeralResolverConnection = null;
2834             }
2835
2836             mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2837         } // synchronized (mPackages)
2838         } // synchronized (mInstallLock)
2839
2840         // Now after opening every single application zip, make sure they
2841         // are all flushed.  Not really needed, but keeps things nice and
2842         // tidy.
2843         Runtime.getRuntime().gc();
2844
2845         // The initial scanning above does many calls into installd while
2846         // holding the mPackages lock, but we're mostly interested in yelling
2847         // once we have a booted system.
2848         mInstaller.setWarnIfHeld(mPackages);
2849
2850         // Expose private service for system components to use.
2851         LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2852     }
2853
2854     @Override
2855     public boolean isFirstBoot() {
2856         return !mRestoredSettings;
2857     }
2858
2859     @Override
2860     public boolean isOnlyCoreApps() {
2861         return mOnlyCore;
2862     }
2863
2864     @Override
2865     public boolean isUpgrade() {
2866         return mIsUpgrade;
2867     }
2868
2869     private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2870         final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2871
2872         final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2873                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2874                 UserHandle.USER_SYSTEM);
2875         if (matches.size() == 1) {
2876             return matches.get(0).getComponentInfo().packageName;
2877         } else {
2878             Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2879             return null;
2880         }
2881     }
2882
2883     private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2884         synchronized (mPackages) {
2885             SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2886             if (libraryEntry == null) {
2887                 throw new IllegalStateException("Missing required shared library:" + libraryName);
2888             }
2889             return libraryEntry.apk;
2890         }
2891     }
2892
2893     private @NonNull String getRequiredInstallerLPr() {
2894         final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2895         intent.addCategory(Intent.CATEGORY_DEFAULT);
2896         intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2897
2898         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2899                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2900                 UserHandle.USER_SYSTEM);
2901         if (matches.size() == 1) {
2902             ResolveInfo resolveInfo = matches.get(0);
2903             if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2904                 throw new RuntimeException("The installer must be a privileged app");
2905             }
2906             return matches.get(0).getComponentInfo().packageName;
2907         } else {
2908             throw new RuntimeException("There must be exactly one installer; found " + matches);
2909         }
2910     }
2911
2912     private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2913         final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2914
2915         final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2916                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2917                 UserHandle.USER_SYSTEM);
2918         ResolveInfo best = null;
2919         final int N = matches.size();
2920         for (int i = 0; i < N; i++) {
2921             final ResolveInfo cur = matches.get(i);
2922             final String packageName = cur.getComponentInfo().packageName;
2923             if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2924                     packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2925                 continue;
2926             }
2927
2928             if (best == null || cur.priority > best.priority) {
2929                 best = cur;
2930             }
2931         }
2932
2933         if (best != null) {
2934             return best.getComponentInfo().getComponentName();
2935         } else {
2936             throw new RuntimeException("There must be at least one intent filter verifier");
2937         }
2938     }
2939
2940     private @Nullable ComponentName getEphemeralResolverLPr() {
2941         final String[] packageArray =
2942                 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2943         if (packageArray.length == 0) {
2944             if (DEBUG_EPHEMERAL) {
2945                 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2946             }
2947             return null;
2948         }
2949
2950         final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2951         final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2952                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2953                 UserHandle.USER_SYSTEM);
2954
2955         final int N = resolvers.size();
2956         if (N == 0) {
2957             if (DEBUG_EPHEMERAL) {
2958                 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2959             }
2960             return null;
2961         }
2962
2963         final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2964         for (int i = 0; i < N; i++) {
2965             final ResolveInfo info = resolvers.get(i);
2966
2967             if (info.serviceInfo == null) {
2968                 continue;
2969             }
2970
2971             final String packageName = info.serviceInfo.packageName;
2972             if (!possiblePackages.contains(packageName)) {
2973                 if (DEBUG_EPHEMERAL) {
2974                     Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2975                             + " pkg: " + packageName + ", info:" + info);
2976                 }
2977                 continue;
2978             }
2979
2980             if (DEBUG_EPHEMERAL) {
2981                 Slog.v(TAG, "Ephemeral resolver found;"
2982                         + " pkg: " + packageName + ", info:" + info);
2983             }
2984             return new ComponentName(packageName, info.serviceInfo.name);
2985         }
2986         if (DEBUG_EPHEMERAL) {
2987             Slog.v(TAG, "Ephemeral resolver NOT found");
2988         }
2989         return null;
2990     }
2991
2992     private @Nullable ComponentName getEphemeralInstallerLPr() {
2993         final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2994         intent.addCategory(Intent.CATEGORY_DEFAULT);
2995         intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2996
2997         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2998                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2999                 UserHandle.USER_SYSTEM);
3000         if (matches.size() == 0) {
3001             return null;
3002         } else if (matches.size() == 1) {
3003             return matches.get(0).getComponentInfo().getComponentName();
3004         } else {
3005             throw new RuntimeException(
3006                     "There must be at most one ephemeral installer; found " + matches);
3007         }
3008     }
3009
3010     private void primeDomainVerificationsLPw(int userId) {
3011         if (DEBUG_DOMAIN_VERIFICATION) {
3012             Slog.d(TAG, "Priming domain verifications in user " + userId);
3013         }
3014
3015         SystemConfig systemConfig = SystemConfig.getInstance();
3016         ArraySet<String> packages = systemConfig.getLinkedApps();
3017         ArraySet<String> domains = new ArraySet<String>();
3018
3019         for (String packageName : packages) {
3020             PackageParser.Package pkg = mPackages.get(packageName);
3021             if (pkg != null) {
3022                 if (!pkg.isSystemApp()) {
3023                     Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3024                     continue;
3025                 }
3026
3027                 domains.clear();
3028                 for (PackageParser.Activity a : pkg.activities) {
3029                     for (ActivityIntentInfo filter : a.intents) {
3030                         if (hasValidDomains(filter)) {
3031                             domains.addAll(filter.getHostsList());
3032                         }
3033                     }
3034                 }
3035
3036                 if (domains.size() > 0) {
3037                     if (DEBUG_DOMAIN_VERIFICATION) {
3038                         Slog.v(TAG, "      + " + packageName);
3039                     }
3040                     // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3041                     // state w.r.t. the formal app-linkage "no verification attempted" state;
3042                     // and then 'always' in the per-user state actually used for intent resolution.
3043                     final IntentFilterVerificationInfo ivi;
3044                     ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
3045                             new ArrayList<String>(domains));
3046                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3047                     mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3048                             INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3049                 } else {
3050                     Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3051                             + "' does not handle web links");
3052                 }
3053             } else {
3054                 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3055             }
3056         }
3057
3058         scheduleWritePackageRestrictionsLocked(userId);
3059         scheduleWriteSettingsLocked();
3060     }
3061
3062     private void applyFactoryDefaultBrowserLPw(int userId) {
3063         // The default browser app's package name is stored in a string resource,
3064         // with a product-specific overlay used for vendor customization.
3065         String browserPkg = mContext.getResources().getString(
3066                 com.android.internal.R.string.default_browser);
3067         if (!TextUtils.isEmpty(browserPkg)) {
3068             // non-empty string => required to be a known package
3069             PackageSetting ps = mSettings.mPackages.get(browserPkg);
3070             if (ps == null) {
3071                 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3072                 browserPkg = null;
3073             } else {
3074                 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3075             }
3076         }
3077
3078         // Nothing valid explicitly set? Make the factory-installed browser the explicit
3079         // default.  If there's more than one, just leave everything alone.
3080         if (browserPkg == null) {
3081             calculateDefaultBrowserLPw(userId);
3082         }
3083     }
3084
3085     private void calculateDefaultBrowserLPw(int userId) {
3086         List<String> allBrowsers = resolveAllBrowserApps(userId);
3087         final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3088         mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3089     }
3090
3091     private List<String> resolveAllBrowserApps(int userId) {
3092         // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3093         List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3094                 PackageManager.MATCH_ALL, userId);
3095
3096         final int count = list.size();
3097         List<String> result = new ArrayList<String>(count);
3098         for (int i=0; i<count; i++) {
3099             ResolveInfo info = list.get(i);
3100             if (info.activityInfo == null
3101                     || !info.handleAllWebDataURI
3102                     || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3103                     || result.contains(info.activityInfo.packageName)) {
3104                 continue;
3105             }
3106             result.add(info.activityInfo.packageName);
3107         }
3108
3109         return result;
3110     }
3111
3112     private boolean packageIsBrowser(String packageName, int userId) {
3113         List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3114                 PackageManager.MATCH_ALL, userId);
3115         final int N = list.size();
3116         for (int i = 0; i < N; i++) {
3117             ResolveInfo info = list.get(i);
3118             if (packageName.equals(info.activityInfo.packageName)) {
3119                 return true;
3120             }
3121         }
3122         return false;
3123     }
3124
3125     private void checkDefaultBrowser() {
3126         final int myUserId = UserHandle.myUserId();
3127         final String packageName = getDefaultBrowserPackageName(myUserId);
3128         if (packageName != null) {
3129             PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3130             if (info == null) {
3131                 Slog.w(TAG, "Default browser no longer installed: " + packageName);
3132                 synchronized (mPackages) {
3133                     applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3134                 }
3135             }
3136         }
3137     }
3138
3139     @Override
3140     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3141             throws RemoteException {
3142         try {
3143             return super.onTransact(code, data, reply, flags);
3144         } catch (RuntimeException e) {
3145             if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3146                 Slog.wtf(TAG, "Package Manager Crash", e);
3147             }
3148             throw e;
3149         }
3150     }
3151
3152     static int[] appendInts(int[] cur, int[] add) {
3153         if (add == null) return cur;
3154         if (cur == null) return add;
3155         final int N = add.length;
3156         for (int i=0; i<N; i++) {
3157             cur = appendInt(cur, add[i]);
3158         }
3159         return cur;
3160     }
3161
3162     private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3163         if (!sUserManager.exists(userId)) return null;
3164         if (ps == null) {
3165             return null;
3166         }
3167         final PackageParser.Package p = ps.pkg;
3168         if (p == null) {
3169             return null;
3170         }
3171
3172         final PermissionsState permissionsState = ps.getPermissionsState();
3173
3174         final int[] gids = permissionsState.computeGids(userId);
3175         final Set<String> permissions = permissionsState.getPermissions(userId);
3176         final PackageUserState state = ps.readUserState(userId);
3177
3178         return PackageParser.generatePackageInfo(p, gids, flags,
3179                 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3180     }
3181
3182     @Override
3183     public void checkPackageStartable(String packageName, int userId) {
3184         final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3185
3186         synchronized (mPackages) {
3187             final PackageSetting ps = mSettings.mPackages.get(packageName);
3188             if (ps == null) {
3189                 throw new SecurityException("Package " + packageName + " was not found!");
3190             }
3191
3192             if (!ps.getInstalled(userId)) {
3193                 throw new SecurityException(
3194                         "Package " + packageName + " was not installed for user " + userId + "!");
3195             }
3196
3197             if (mSafeMode && !ps.isSystem()) {
3198                 throw new SecurityException("Package " + packageName + " not a system app!");
3199             }
3200
3201             if (mFrozenPackages.contains(packageName)) {
3202                 throw new SecurityException("Package " + packageName + " is currently frozen!");
3203             }
3204
3205             if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3206                     || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3207                 throw new SecurityException("Package " + packageName + " is not encryption aware!");
3208             }
3209         }
3210     }
3211
3212     @Override
3213     public boolean isPackageAvailable(String packageName, int userId) {
3214         if (!sUserManager.exists(userId)) return false;
3215         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3216                 false /* requireFullPermission */, false /* checkShell */, "is package available");
3217         synchronized (mPackages) {
3218             PackageParser.Package p = mPackages.get(packageName);
3219             if (p != null) {
3220                 final PackageSetting ps = (PackageSetting) p.mExtras;
3221                 if (ps != null) {
3222                     final PackageUserState state = ps.readUserState(userId);
3223                     if (state != null) {
3224                         return PackageParser.isAvailable(state);
3225                     }
3226                 }
3227             }
3228         }
3229         return false;
3230     }
3231
3232     @Override
3233     public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3234         if (!sUserManager.exists(userId)) return null;
3235         flags = updateFlagsForPackage(flags, userId, packageName);
3236         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3237                 false /* requireFullPermission */, false /* checkShell */, "get package info");
3238         // reader
3239         synchronized (mPackages) {
3240             final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3241             PackageParser.Package p = null;
3242             if (matchFactoryOnly) {
3243                 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3244                 if (ps != null) {
3245                     return generatePackageInfo(ps, flags, userId);
3246                 }
3247             }
3248             if (p == null) {
3249                 p = mPackages.get(packageName);
3250                 if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3251                     return null;
3252                 }
3253             }
3254             if (DEBUG_PACKAGE_INFO)
3255                 Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3256             if (p != null) {
3257                 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3258             }
3259             if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3260                 final PackageSetting ps = mSettings.mPackages.get(packageName);
3261                 return generatePackageInfo(ps, flags, userId);
3262             }
3263         }
3264         return null;
3265     }
3266
3267     @Override
3268     public String[] currentToCanonicalPackageNames(String[] names) {
3269         String[] out = new String[names.length];
3270         // reader
3271         synchronized (mPackages) {
3272             for (int i=names.length-1; i>=0; i--) {
3273                 PackageSetting ps = mSettings.mPackages.get(names[i]);
3274                 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3275             }
3276         }
3277         return out;
3278     }
3279
3280     @Override
3281     public String[] canonicalToCurrentPackageNames(String[] names) {
3282         String[] out = new String[names.length];
3283         // reader
3284         synchronized (mPackages) {
3285             for (int i=names.length-1; i>=0; i--) {
3286                 String cur = mSettings.mRenamedPackages.get(names[i]);
3287                 out[i] = cur != null ? cur : names[i];
3288             }
3289         }
3290         return out;
3291     }
3292
3293     @Override
3294     public int getPackageUid(String packageName, int flags, int userId) {
3295         if (!sUserManager.exists(userId)) return -1;
3296         flags = updateFlagsForPackage(flags, userId, packageName);
3297         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3298                 false /* requireFullPermission */, false /* checkShell */, "get package uid");
3299
3300         // reader
3301         synchronized (mPackages) {
3302             final PackageParser.Package p = mPackages.get(packageName);
3303             if (p != null && p.isMatch(flags)) {
3304                 return UserHandle.getUid(userId, p.applicationInfo.uid);
3305             }
3306             if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3307                 final PackageSetting ps = mSettings.mPackages.get(packageName);
3308                 if (ps != null && ps.isMatch(flags)) {
3309                     return UserHandle.getUid(userId, ps.appId);
3310                 }
3311             }
3312         }
3313
3314         return -1;
3315     }
3316
3317     @Override
3318     public int[] getPackageGids(String packageName, int flags, int userId) {
3319         if (!sUserManager.exists(userId)) return null;
3320         flags = updateFlagsForPackage(flags, userId, packageName);
3321         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3322                 false /* requireFullPermission */, false /* checkShell */,
3323                 "getPackageGids");
3324
3325         // reader
3326         synchronized (mPackages) {
3327             final PackageParser.Package p = mPackages.get(packageName);
3328             if (p != null && p.isMatch(flags)) {
3329                 PackageSetting ps = (PackageSetting) p.mExtras;
3330                 return ps.getPermissionsState().computeGids(userId);
3331             }
3332             if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3333                 final PackageSetting ps = mSettings.mPackages.get(packageName);
3334                 if (ps != null && ps.isMatch(flags)) {
3335                     return ps.getPermissionsState().computeGids(userId);
3336                 }
3337             }
3338         }
3339
3340         return null;
3341     }
3342
3343     static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3344         if (bp.perm != null) {
3345             return PackageParser.generatePermissionInfo(bp.perm, flags);
3346         }
3347         PermissionInfo pi = new PermissionInfo();
3348         pi.name = bp.name;
3349         pi.packageName = bp.sourcePackage;
3350         pi.nonLocalizedLabel = bp.name;
3351         pi.protectionLevel = bp.protectionLevel;
3352         return pi;
3353     }
3354
3355     @Override
3356     public PermissionInfo getPermissionInfo(String name, int flags) {
3357         // reader
3358         synchronized (mPackages) {
3359             final BasePermission p = mSettings.mPermissions.get(name);
3360             if (p != null) {
3361                 return generatePermissionInfo(p, flags);
3362             }
3363             return null;
3364         }
3365     }
3366
3367     @Override
3368     public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3369             int flags) {
3370         // reader
3371         synchronized (mPackages) {
3372             if (group != null && !mPermissionGroups.containsKey(group)) {
3373                 // This is thrown as NameNotFoundException
3374                 return null;
3375             }
3376
3377             ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3378             for (BasePermission p : mSettings.mPermissions.values()) {
3379                 if (group == null) {
3380                     if (p.perm == null || p.perm.info.group == null) {
3381                         out.add(generatePermissionInfo(p, flags));
3382                     }
3383                 } else {
3384                     if (p.perm != null && group.equals(p.perm.info.group)) {
3385                         out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3386                     }
3387                 }
3388             }
3389             return new ParceledListSlice<>(out);
3390         }
3391     }
3392
3393     @Override
3394     public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3395         // reader
3396         synchronized (mPackages) {
3397             return PackageParser.generatePermissionGroupInfo(
3398                     mPermissionGroups.get(name), flags);
3399         }
3400     }
3401
3402     @Override
3403     public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3404         // reader
3405         synchronized (mPackages) {
3406             final int N = mPermissionGroups.size();
3407             ArrayList<PermissionGroupInfo> out
3408                     = new ArrayList<PermissionGroupInfo>(N);
3409             for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3410                 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3411             }
3412             return new ParceledListSlice<>(out);
3413         }
3414     }
3415
3416     private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3417             int userId) {
3418         if (!sUserManager.exists(userId)) return null;
3419         PackageSetting ps = mSettings.mPackages.get(packageName);
3420         if (ps != null) {
3421             if (ps.pkg == null) {
3422                 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3423                 if (pInfo != null) {
3424                     return pInfo.applicationInfo;
3425                 }
3426                 return null;
3427             }
3428             return PackageParser.generateApplicationInfo(ps.pkg, flags,
3429                     ps.readUserState(userId), userId);
3430         }
3431         return null;
3432     }
3433
3434     @Override
3435     public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3436         if (!sUserManager.exists(userId)) return null;
3437         flags = updateFlagsForApplication(flags, userId, packageName);
3438         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3439                 false /* requireFullPermission */, false /* checkShell */, "get application info");
3440         // writer
3441         synchronized (mPackages) {
3442             PackageParser.Package p = mPackages.get(packageName);
3443             if (DEBUG_PACKAGE_INFO) Log.v(
3444                     TAG, "getApplicationInfo " + packageName
3445                     + ": " + p);
3446             if (p != null) {
3447                 PackageSetting ps = mSettings.mPackages.get(packageName);
3448                 if (ps == null) return null;
3449                 // Note: isEnabledLP() does not apply here - always return info
3450                 return PackageParser.generateApplicationInfo(
3451                         p, flags, ps.readUserState(userId), userId);
3452             }
3453             if ("android".equals(packageName)||"system".equals(packageName)) {
3454                 return mAndroidApplication;
3455             }
3456             if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3457                 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3458             }
3459         }
3460         return null;
3461     }
3462
3463     @Override
3464     public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3465             final IPackageDataObserver observer) {
3466         mContext.enforceCallingOrSelfPermission(
3467                 android.Manifest.permission.CLEAR_APP_CACHE, null);
3468         // Queue up an async operation since clearing cache may take a little while.
3469         mHandler.post(new Runnable() {
3470             public void run() {
3471                 mHandler.removeCallbacks(this);
3472                 boolean success = true;
3473                 synchronized (mInstallLock) {
3474                     try {
3475                         mInstaller.freeCache(volumeUuid, freeStorageSize);
3476                     } catch (InstallerException e) {
3477                         Slog.w(TAG, "Couldn't clear application caches: " + e);
3478                         success = false;
3479                     }
3480                 }
3481                 if (observer != null) {
3482                     try {
3483                         observer.onRemoveCompleted(null, success);
3484                     } catch (RemoteException e) {
3485                         Slog.w(TAG, "RemoveException when invoking call back");
3486                     }
3487                 }
3488             }
3489         });
3490     }
3491
3492     @Override
3493     public void freeStorage(final String volumeUuid, final long freeStorageSize,
3494             final IntentSender pi) {
3495         mContext.enforceCallingOrSelfPermission(
3496                 android.Manifest.permission.CLEAR_APP_CACHE, null);
3497         // Queue up an async operation since clearing cache may take a little while.
3498         mHandler.post(new Runnable() {
3499             public void run() {
3500                 mHandler.removeCallbacks(this);
3501                 boolean success = true;
3502                 synchronized (mInstallLock) {
3503                     try {
3504                         mInstaller.freeCache(volumeUuid, freeStorageSize);
3505                     } catch (InstallerException e) {
3506                         Slog.w(TAG, "Couldn't clear application caches: " + e);
3507                         success = false;
3508                     }
3509                 }
3510                 if(pi != null) {
3511                     try {
3512                         // Callback via pending intent
3513                         int code = success ? 1 : 0;
3514                         pi.sendIntent(null, code, null,
3515                                 null, null);
3516                     } catch (SendIntentException e1) {
3517                         Slog.i(TAG, "Failed to send pending intent");
3518                     }
3519                 }
3520             }
3521         });
3522     }
3523
3524     void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3525         synchronized (mInstallLock) {
3526             try {
3527                 mInstaller.freeCache(volumeUuid, freeStorageSize);
3528             } catch (InstallerException e) {
3529                 throw new IOException("Failed to free enough space", e);
3530             }
3531         }
3532     }
3533
3534     /**
3535      * Update given flags based on encryption status of current user.
3536      */
3537     private int updateFlags(int flags, int userId) {
3538         if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3539                 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3540             // Caller expressed an explicit opinion about what encryption
3541             // aware/unaware components they want to see, so fall through and
3542             // give them what they want
3543         } else {
3544             // Caller expressed no opinion, so match based on user state
3545             if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3546                 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3547             } else {
3548                 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3549             }
3550         }
3551         return flags;
3552     }
3553
3554     private UserManagerInternal getUserManagerInternal() {
3555         if (mUserManagerInternal == null) {
3556             mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3557         }
3558         return mUserManagerInternal;
3559     }
3560
3561     /**
3562      * Update given flags when being used to request {@link PackageInfo}.
3563      */
3564     private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3565         boolean triaged = true;
3566         if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3567                 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3568             // Caller is asking for component details, so they'd better be
3569             // asking for specific encryption matching behavior, or be triaged
3570             if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3571                     | PackageManager.MATCH_DIRECT_BOOT_AWARE
3572                     | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3573                 triaged = false;
3574             }
3575         }
3576         if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3577                 | PackageManager.MATCH_SYSTEM_ONLY
3578                 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3579             triaged = false;
3580         }
3581         if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3582             Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3583                     + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3584         }
3585         return updateFlags(flags, userId);
3586     }
3587
3588     /**
3589      * Update given flags when being used to request {@link ApplicationInfo}.
3590      */
3591     private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3592         return updateFlagsForPackage(flags, userId, cookie);
3593     }
3594
3595     /**
3596      * Update given flags when being used to request {@link ComponentInfo}.
3597      */
3598     private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3599         if (cookie instanceof Intent) {
3600             if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3601                 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3602             }
3603         }
3604
3605         boolean triaged = true;
3606         // Caller is asking for component details, so they'd better be
3607         // asking for specific encryption matching behavior, or be triaged
3608         if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3609                 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3610                 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3611             triaged = false;
3612         }
3613         if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3614             Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3615                     + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3616         }
3617
3618         return updateFlags(flags, userId);
3619     }
3620
3621     /**
3622      * Update given flags when being used to request {@link ResolveInfo}.
3623      */
3624     int updateFlagsForResolve(int flags, int userId, Object cookie) {
3625         // Safe mode means we shouldn't match any third-party components
3626         if (mSafeMode) {
3627             flags |= PackageManager.MATCH_SYSTEM_ONLY;
3628         }
3629
3630         return updateFlagsForComponent(flags, userId, cookie);
3631     }
3632
3633     @Override
3634     public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3635         if (!sUserManager.exists(userId)) return null;
3636         flags = updateFlagsForComponent(flags, userId, component);
3637         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3638                 false /* requireFullPermission */, false /* checkShell */, "get activity info");
3639         synchronized (mPackages) {
3640             PackageParser.Activity a = mActivities.mActivities.get(component);
3641
3642             if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3643             if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3644                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3645                 if (ps == null) return null;
3646                 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3647                         userId);
3648             }
3649             if (mResolveComponentName.equals(component)) {
3650                 return PackageParser.generateActivityInfo(mResolveActivity, flags,
3651                         new PackageUserState(), userId);
3652             }
3653         }
3654         return null;
3655     }
3656
3657     @Override
3658     public boolean activitySupportsIntent(ComponentName component, Intent intent,
3659             String resolvedType) {
3660         synchronized (mPackages) {
3661             if (component.equals(mResolveComponentName)) {
3662                 // The resolver supports EVERYTHING!
3663                 return true;
3664             }
3665             PackageParser.Activity a = mActivities.mActivities.get(component);
3666             if (a == null) {
3667                 return false;
3668             }
3669             for (int i=0; i<a.intents.size(); i++) {
3670                 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3671                         intent.getData(), intent.getCategories(), TAG) >= 0) {
3672                     return true;
3673                 }
3674             }
3675             return false;
3676         }
3677     }
3678
3679     @Override
3680     public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3681         if (!sUserManager.exists(userId)) return null;
3682         flags = updateFlagsForComponent(flags, userId, component);
3683         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3684                 false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3685         synchronized (mPackages) {
3686             PackageParser.Activity a = mReceivers.mActivities.get(component);
3687             if (DEBUG_PACKAGE_INFO) Log.v(
3688                 TAG, "getReceiverInfo " + component + ": " + a);
3689             if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3690                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3691                 if (ps == null) return null;
3692                 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3693                         userId);
3694             }
3695         }
3696         return null;
3697     }
3698
3699     @Override
3700     public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3701         if (!sUserManager.exists(userId)) return null;
3702         flags = updateFlagsForComponent(flags, userId, component);
3703         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3704                 false /* requireFullPermission */, false /* checkShell */, "get service info");
3705         synchronized (mPackages) {
3706             PackageParser.Service s = mServices.mServices.get(component);
3707             if (DEBUG_PACKAGE_INFO) Log.v(
3708                 TAG, "getServiceInfo " + component + ": " + s);
3709             if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3710                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3711                 if (ps == null) return null;
3712                 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3713                         userId);
3714             }
3715         }
3716         return null;
3717     }
3718
3719     @Override
3720     public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3721         if (!sUserManager.exists(userId)) return null;
3722         flags = updateFlagsForComponent(flags, userId, component);
3723         enforceCrossUserPermission(Binder.getCallingUid(), userId,
3724                 false /* requireFullPermission */, false /* checkShell */, "get provider info");
3725         synchronized (mPackages) {
3726             PackageParser.Provider p = mProviders.mProviders.get(component);
3727             if (DEBUG_PACKAGE_INFO) Log.v(
3728                 TAG, "getProviderInfo " + component + ": " + p);
3729             if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3730                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3731                 if (ps == null) return null;
3732                 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3733                         userId);
3734             }
3735         }
3736         return null;
3737     }
3738
3739     @Override
3740     public String[] getSystemSharedLibraryNames() {
3741         Set<String> libSet;
3742         synchronized (mPackages) {
3743             libSet = mSharedLibraries.keySet();
3744             int size = libSet.size();
3745             if (size > 0) {
3746                 String[] libs = new String[size];
3747                 libSet.toArray(libs);
3748                 return libs;
3749             }
3750         }
3751         return null;
3752     }
3753
3754     @Override
3755     public @NonNull String getServicesSystemSharedLibraryPackageName() {
3756         synchronized (mPackages) {
3757             return mServicesSystemSharedLibraryPackageName;
3758         }
3759     }
3760
3761     @Override
3762     public @NonNull String getSharedSystemSharedLibraryPackageName() {
3763         synchronized (mPackages) {
3764             return mSharedSystemSharedLibraryPackageName;
3765         }
3766     }
3767
3768     @Override
3769     public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3770         synchronized (mPackages) {
3771             final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3772
3773             final FeatureInfo fi = new FeatureInfo();
3774             fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3775                     FeatureInfo.GL_ES_VERSION_UNDEFINED);
3776             res.add(fi);
3777
3778             return new ParceledListSlice<>(res);
3779         }
3780     }
3781
3782     @Override
3783     public boolean hasSystemFeature(String name, int version) {
3784         synchronized (mPackages) {
3785             final FeatureInfo feat = mAvailableFeatures.get(name);
3786             if (feat == null) {
3787                 return false;
3788             } else {
3789                 return feat.version >= version;
3790             }
3791         }
3792     }
3793
3794     @Override
3795     public int checkPermission(String permName, String pkgName, int userId) {
3796         if (!sUserManager.exists(userId)) {
3797             return PackageManager.PERMISSION_DENIED;
3798         }
3799
3800         synchronized (mPackages) {
3801             final PackageParser.Package p = mPackages.get(pkgName);
3802             if (p != null && p.mExtras != null) {
3803                 final PackageSetting ps = (PackageSetting) p.mExtras;
3804                 final PermissionsState permissionsState = ps.getPermissionsState();
3805                 if (permissionsState.hasPermission(permName, userId)) {
3806                     return PackageManager.PERMISSION_GRANTED;
3807                 }
3808                 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3809                 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3810                         .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3811                     return PackageManager.PERMISSION_GRANTED;
3812                 }
3813             }
3814         }
3815
3816         return PackageManager.PERMISSION_DENIED;
3817     }
3818
3819     @Override
3820     public int checkUidPermission(String permName, int uid) {
3821         final int userId = UserHandle.getUserId(uid);
3822
3823         if (!sUserManager.exists(userId)) {
3824             return PackageManager.PERMISSION_DENIED;
3825         }
3826
3827         synchronized (mPackages) {
3828             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3829             if (obj != null) {
3830                 final SettingBase ps = (SettingBase) obj;
3831                 final PermissionsState permissionsState = ps.getPermissionsState();
3832                 if (permissionsState.hasPermission(permName, userId)) {
3833                     return PackageManager.PERMISSION_GRANTED;
3834                 }
3835                 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3836                 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3837                         .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3838                     return PackageManager.PERMISSION_GRANTED;
3839                 }
3840             } else {
3841                 ArraySet<String> perms = mSystemPermissions.get(uid);
3842                 if (perms != null) {
3843                     if (perms.contains(permName)) {
3844                         return PackageManager.PERMISSION_GRANTED;
3845                     }
3846                     if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3847                             .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3848                         return PackageManager.PERMISSION_GRANTED;
3849                     }
3850                 }
3851             }
3852         }
3853
3854         return PackageManager.PERMISSION_DENIED;
3855     }
3856
3857     @Override
3858     public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3859         if (UserHandle.getCallingUserId() != userId) {
3860             mContext.enforceCallingPermission(
3861                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3862                     "isPermissionRevokedByPolicy for user " + userId);
3863         }
3864
3865         if (checkPermission(permission, packageName, userId)
3866                 == PackageManager.PERMISSION_GRANTED) {
3867             return false;
3868         }
3869
3870         final long identity = Binder.clearCallingIdentity();
3871         try {
3872             final int flags = getPermissionFlags(permission, packageName, userId);
3873             return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3874         } finally {
3875             Binder.restoreCallingIdentity(identity);
3876         }
3877     }
3878
3879     @Override
3880     public String getPermissionControllerPackageName() {
3881         synchronized (mPackages) {
3882             return mRequiredInstallerPackage;
3883         }
3884     }
3885
3886     /**
3887      * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3888      * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3889      * @param checkShell whether to prevent shell from access if there's a debugging restriction
3890      * @param message the message to log on security exception
3891      */
3892     void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3893             boolean checkShell, String message) {
3894         if (userId < 0) {
3895             throw new IllegalArgumentException("Invalid userId " + userId);
3896         }
3897         if (checkShell) {
3898             enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3899         }
3900         if (userId == UserHandle.getUserId(callingUid)) return;
3901         if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3902             if (requireFullPermission) {
3903                 mContext.enforceCallingOrSelfPermission(
3904                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3905             } else {
3906                 try {
3907                     mContext.enforceCallingOrSelfPermission(
3908                             android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3909                 } catch (SecurityException se) {
3910                     mContext.enforceCallingOrSelfPermission(
3911                             android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3912                 }
3913             }
3914         }
3915     }
3916
3917     void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3918         if (callingUid == Process.SHELL_UID) {
3919             if (userHandle >= 0
3920                     && sUserManager.hasUserRestriction(restriction, userHandle)) {
3921                 throw new SecurityException("Shell does not have permission to access user "
3922                         + userHandle);
3923             } else if (userHandle < 0) {
3924                 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3925                         + Debug.getCallers(3));
3926             }
3927         }
3928     }
3929
3930     private BasePermission findPermissionTreeLP(String permName) {
3931         for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3932             if (permName.startsWith(bp.name) &&
3933                     permName.length() > bp.name.length() &&
3934                     permName.charAt(bp.name.length()) == '.') {
3935                 return bp;
3936             }
3937         }
3938         return null;
3939     }
3940
3941     private BasePermission checkPermissionTreeLP(String permName) {
3942         if (permName != null) {
3943             BasePermission bp = findPermissionTreeLP(permName);
3944             if (bp != null) {
3945                 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3946                     return bp;
3947                 }
3948                 throw new SecurityException("Calling uid "
3949                         + Binder.getCallingUid()
3950                         + " is not allowed to add to permission tree "
3951                         + bp.name + " owned by uid " + bp.uid);
3952             }
3953         }
3954         throw new SecurityException("No permission tree found for " + permName);
3955     }
3956
3957     static boolean compareStrings(CharSequence s1, CharSequence s2) {
3958         if (s1 == null) {
3959             return s2 == null;
3960         }
3961         if (s2 == null) {
3962             return false;
3963         }
3964         if (s1.getClass() != s2.getClass()) {
3965             return false;
3966         }
3967         return s1.equals(s2);
3968     }
3969
3970     static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3971         if (pi1.icon != pi2.icon) return false;
3972         if (pi1.logo != pi2.logo) return false;
3973         if (pi1.protectionLevel != pi2.protectionLevel) return false;
3974         if (!compareStrings(pi1.name, pi2.name)) return false;
3975         if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3976         // We'll take care of setting this one.
3977         if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3978         // These are not currently stored in settings.
3979         //if (!compareStrings(pi1.group, pi2.group)) return false;
3980         //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3981         //if (pi1.labelRes != pi2.labelRes) return false;
3982         //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3983         return true;
3984     }
3985
3986     int permissionInfoFootprint(PermissionInfo info) {
3987         int size = info.name.length();
3988         if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3989         if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3990         return size;
3991     }
3992
3993     int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3994         int size = 0;
3995         for (BasePermission perm : mSettings.mPermissions.values()) {
3996             if (perm.uid == tree.uid) {
3997                 size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3998             }
3999         }
4000         return size;
4001     }
4002
4003     void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4004         // We calculate the max size of permissions defined by this uid and throw
4005         // if that plus the size of 'info' would exceed our stated maximum.
4006         if (tree.uid != Process.SYSTEM_UID) {
4007             final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4008             if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4009                 throw new SecurityException("Permission tree size cap exceeded");
4010             }
4011         }
4012     }
4013
4014     boolean addPermissionLocked(PermissionInfo info, boolean async) {
4015         if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4016             throw new SecurityException("Label must be specified in permission");
4017         }
4018         BasePermission tree = checkPermissionTreeLP(info.name);
4019         BasePermission bp = mSettings.mPermissions.get(info.name);
4020         boolean added = bp == null;
4021         boolean changed = true;
4022         int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4023         if (added) {
4024             enforcePermissionCapLocked(info, tree);
4025             bp = new BasePermission(info.name, tree.sourcePackage,
4026                     BasePermission.TYPE_DYNAMIC);
4027         } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4028             throw new SecurityException(
4029                     "Not allowed to modify non-dynamic permission "
4030                     + info.name);
4031         } else {
4032             if (bp.protectionLevel == fixedLevel
4033                     && bp.perm.owner.equals(tree.perm.owner)
4034                     && bp.uid == tree.uid
4035                     && comparePermissionInfos(bp.perm.info, info)) {
4036                 changed = false;
4037             }
4038         }
4039         bp.protectionLevel = fixedLevel;
4040         info = new PermissionInfo(info);
4041         info.protectionLevel = fixedLevel;
4042         bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4043         bp.perm.info.packageName = tree.perm.info.packageName;
4044         bp.uid = tree.uid;
4045         if (added) {
4046             mSettings.mPermissions.put(info.name, bp);
4047         }
4048         if (changed) {
4049             if (!async) {
4050                 mSettings.writeLPr();
4051             } else {
4052                 scheduleWriteSettingsLocked();
4053             }
4054         }
4055         return added;
4056     }
4057
4058     @Override
4059     public boolean addPermission(PermissionInfo info) {
4060         synchronized (mPackages) {
4061             return addPermissionLocked(info, false);
4062         }
4063     }
4064
4065     @Override
4066     public boolean addPermissionAsync(PermissionInfo info) {
4067         synchronized (mPackages) {
4068             return addPermissionLocked(info, true);
4069         }
4070     }
4071
4072     @Override
4073     public void removePermission(String name) {
4074         synchronized (mPackages) {
4075             checkPermissionTreeLP(name);
4076             BasePermission bp = mSettings.mPermissions.get(name);
4077             if (bp != null) {
4078                 if (bp.type != BasePermission.TYPE_DYNAMIC) {
4079                     throw new SecurityException(
4080                             "Not allowed to modify non-dynamic permission "
4081                             + name);
4082                 }
4083                 mSettings.mPermissions.remove(name);
4084                 mSettings.writeLPr();
4085             }
4086         }
4087     }
4088
4089     private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4090             BasePermission bp) {
4091         int index = pkg.requestedPermissions.indexOf(bp.name);
4092         if (index == -1) {
4093             throw new SecurityException("Package " + pkg.packageName
4094                     + " has not requested permission " + bp.name);
4095         }
4096         if (!bp.isRuntime() && !bp.isDevelopment()) {
4097             throw new SecurityException("Permission " + bp.name
4098                     + " is not a changeable permission type");
4099         }
4100     }
4101
4102     @Override
4103     public void grantRuntimePermission(String packageName, String name, final int userId) {
4104         if (!sUserManager.exists(userId)) {
4105             Log.e(TAG, "No such user:" + userId);
4106             return;
4107         }
4108
4109         mContext.enforceCallingOrSelfPermission(
4110                 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4111                 "grantRuntimePermission");
4112
4113         enforceCrossUserPermission(Binder.getCallingUid(), userId,
4114                 true /* requireFullPermission */, true /* checkShell */,
4115                 "grantRuntimePermission");
4116
4117         final int uid;
4118         final SettingBase sb;
4119
4120         synchronized (mPackages) {
4121             final PackageParser.Package pkg = mPackages.get(packageName);
4122             if (pkg == null) {
4123                 throw new IllegalArgumentException("Unknown package: " + packageName);
4124             }
4125
4126             final BasePermission bp = mSettings.mPermissions.get(name);
4127             if (bp == null) {
4128                 throw new IllegalArgumentException("Unknown permission: " + name);
4129             }
4130
4131             enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4132
4133             // If a permission review is required for legacy apps we represent
4134             // their permissions as always granted runtime ones since we need
4135             // to keep the review required permission flag per user while an
4136             // install permission's state is shared across all users.
4137             if (Build.PERMISSIONS_REVIEW_REQUIRED
4138                     && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4139                     && bp.isRuntime()) {
4140                 return;
4141             }
4142
4143             uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4144             sb = (SettingBase) pkg.mExtras;
4145             if (sb == null) {
4146                 throw new IllegalArgumentException("Unknown package: " + packageName);
4147             }
4148
4149             final PermissionsState permissionsState = sb.getPermissionsState();
4150
4151             final int flags = permissionsState.getPermissionFlags(name, userId);
4152             if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4153                 throw new SecurityException("Cannot grant system fixed permission "
4154                         + name + " for package " + packageName);
4155             }
4156
4157             if (bp.isDevelopment()) {
4158                 // Development permissions must be handled specially, since they are not
4159                 // normal runtime permissions.  For now they apply to all users.
4160                 if (permissionsState.grantInstallPermission(bp) !=
4161                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
4162                     scheduleWriteSettingsLocked();
4163                 }
4164                 return;
4165             }
4166
4167             if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4168                 Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4169                 return;
4170             }
4171
4172             final int result = permissionsState.grantRuntimePermission(bp, userId);
4173             switch (result) {
4174                 case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4175                     return;
4176                 }
4177
4178                 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4179                     final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4180                     mHandler.post(new Runnable() {
4181                         @Override
4182                         public void run() {
4183                             killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4184                         }
4185                     });
4186                 }
4187                 break;
4188             }
4189
4190             mOnPermissionChangeListeners.onPermissionsChanged(uid);
4191
4192             // Not critical if that is lost - app has to request again.
4193             mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4194         }
4195
4196         // Only need to do this if user is initialized. Otherwise it's a new user
4197         // and there are no processes running as the user yet and there's no need
4198         // to make an expensive call to remount processes for the changed permissions.
4199         if (READ_EXTERNAL_STORAGE.equals(name)
4200                 || WRITE_EXTERNAL_STORAGE.equals(name)) {
4201             final long token = Binder.clearCallingIdentity();
4202             try {
4203                 if (sUserManager.isInitialized(userId)) {
4204                     MountServiceInternal mountServiceInternal = LocalServices.getService(
4205                             MountServiceInternal.class);
4206                     mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4207                 }
4208             } finally {
4209                 Binder.restoreCallingIdentity(token);
4210             }
4211         }
4212     }
4213
4214     @Override
4215     public void revokeRuntimePermission(String packageName, String name, int userId) {
4216         if (!sUserManager.exists(userId)) {
4217             Log.e(TAG, "No such user:" + userId);
4218             return;
4219         }
4220
4221         mContext.enforceCallingOrSelfPermission(
4222                 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4223                 "revokeRuntimePermission");
4224
4225         enforceCrossUserPermission(Binder.getCallingUid(), userId,
4226                 true /* requireFullPermission */, true /* checkShell */,
4227                 "revokeRuntimePermission");
4228
4229         final int appId;
4230
4231         synchronized (mPackages) {
4232             final PackageParser.Package pkg = mPackages.get(packageName);
4233             if (pkg == null) {
4234                 throw new IllegalArgumentException("Unknown package: " + packageName);
4235             }
4236
4237             final BasePermission bp = mSettings.mPermissions.get(name);
4238             if (bp == null) {
4239                 throw new IllegalArgumentException("Unknown permission: " + name);
4240             }
4241
4242             enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4243
4244             // If a permission review is required for legacy apps we represent
4245             // their permissions as always granted runtime ones since we need
4246             // to keep the review required permission flag per user while an
4247             // install permission's state is shared across all users.
4248             if (Build.PERMISSIONS_REVIEW_REQUIRED
4249                     && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4250                     && bp.isRuntime()) {
4251                 return;
4252             }
4253
4254             SettingBase sb = (SettingBase) pkg.mExtras;
4255             if (sb == null) {
4256                 throw new IllegalArgumentException("Unknown package: " + packageName);
4257             }
4258
4259             final PermissionsState permissionsState = sb.getPermissionsState();
4260
4261             final int flags = permissionsState.getPermissionFlags(name, userId);
4262             if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4263                 throw new SecurityException("Cannot revoke system fixed permission "
4264                         + name + " for package " + packageName);
4265             }
4266
4267             if (bp.isDevelopment()) {
4268                 // Development permissions must be handled specially, since they are not
4269                 // normal runtime permissions.  For now they apply to all users.
4270                 if (permissionsState.revokeInstallPermission(bp) !=
4271                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
4272                     scheduleWriteSettingsLocked();
4273                 }
4274                 return;
4275             }
4276
4277             if (permissionsState.revokeRuntimePermission(bp, userId) ==
4278                     PermissionsState.PERMISSION_OPERATION_FAILURE) {
4279                 return;
4280             }
4281
4282             mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4283
4284             // Critical, after this call app should never have the permission.
4285             mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4286
4287             appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4288         }
4289
4290         killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4291     }
4292
4293     @Override
4294     public void resetRuntimePermissions() {
4295         mContext.enforceCallingOrSelfPermission(
4296                 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4297                 "revokeRuntimePermission");
4298
4299         int callingUid = Binder.getCallingUid();
4300         if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4301             mContext.enforceCallingOrSelfPermission(
4302                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4303                     "resetRuntimePermissions");
4304         }
4305
4306         synchronized (mPackages) {
4307             updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4308             for (int userId : UserManagerService.getInstance().getUserIds()) {
4309                 final int packageCount = mPackages.size();
4310                 for (int i = 0; i < packageCount; i++) {
4311                     PackageParser.Package pkg = mPackages.valueAt(i);
4312                     if (!(pkg.mExtras instanceof PackageSetting)) {
4313                         continue;
4314                     }
4315                     PackageSetting ps = (PackageSetting) pkg.mExtras;
4316                     resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4317                 }
4318             }
4319         }
4320     }
4321
4322     @Override
4323     public int getPermissionFlags(String name, String packageName, int userId) {
4324         if (!sUserManager.exists(userId)) {
4325             return 0;
4326         }
4327
4328         enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4329
4330         enforceCrossUserPermission(Binder.getCallingUid(), userId,
4331                 true /* requireFullPermission */, false /* checkShell */,
4332                 "getPermissionFlags");
4333
4334         synchronized (mPackages) {
4335             final PackageParser.Package pkg = mPackages.get(packageName);
4336             if (pkg == null) {
4337                 return 0;
4338             }
4339
4340             final BasePermission bp = mSettings.mPermissions.get(name);
4341             if (bp == null) {
4342                 return 0;
4343             }
4344
4345             SettingBase sb = (SettingBase) pkg.mExtras;
4346             if (sb == null) {
4347                 return 0;
4348             }
4349
4350             PermissionsState permissionsState = sb.getPermissionsState();
4351             return permissionsState.getPermissionFlags(name, userId);
4352         }
4353     }
4354
4355     @Override
4356     public void updatePermissionFlags(String name, String packageName, int flagMask,
4357             int flagValues, int userId) {
4358         if (!sUserManager.exists(userId)) {
4359             return;
4360         }
4361
4362         enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4363
4364         enforceCrossUserPermission(Binder.getCallingUid(), userId,
4365                 true /* requireFullPermission */, true /* checkShell */,
4366                 "updatePermissionFlags");
4367
4368         // Only the system can change these flags and nothing else.
4369         if (getCallingUid() != Process.SYSTEM_UID) {
4370             flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4371             flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4372             flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4373             flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4374             flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4375         }
4376
4377         synchronized (mPackages) {
4378             final PackageParser.Package pkg = mPackages.get(packageName);
4379             if (pkg == null) {
4380                 throw new IllegalArgumentException("Unknown package: " + packageName);
4381             }
4382
4383             final BasePermission bp = mSettings.mPermissions.get(name);
4384             if (bp == null) {
4385                 throw new IllegalArgumentException("Unknown permission: " + name);
4386             }
4387
4388             SettingBase sb = (SettingBase) pkg.mExtras;
4389             if (sb == null) {
4390                 throw new IllegalArgumentException("Unknown package: " + packageName);
4391             }
4392
4393             PermissionsState permissionsState = sb.getPermissionsState();
4394
4395             boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4396
4397             if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4398                 // Install and runtime permissions are stored in different places,
4399                 // so figure out what permission changed and persist the change.
4400                 if (permissionsState.getInstallPermissionState(name) != null) {
4401                     scheduleWriteSettingsLocked();
4402                 } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4403                         || hadState) {
4404                     mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4405                 }
4406             }
4407         }
4408     }
4409
4410     /**
4411      * Update the permission flags for all packages and runtime permissions of a user in order
4412      * to allow device or profile owner to remove POLICY_FIXED.
4413      */
4414     @Override
4415     public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4416         if (!sUserManager.exists(userId)) {
4417             return;
4418         }
4419
4420         enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4421
4422         enforceCrossUserPermission(Binder.getCallingUid(), userId,
4423                 true /* requireFullPermission */, true /* checkShell */,
4424                 "updatePermissionFlagsForAllApps");
4425
4426         // Only the system can change system fixed flags.
4427         if (getCallingUid() != Process.SYSTEM_UID) {
4428             flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4429             flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4430         }
4431
4432         synchronized (mPackages) {
4433             boolean changed = false;
4434             final int packageCount = mPackages.size();
4435             for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4436                 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4437                 SettingBase sb = (SettingBase) pkg.mExtras;
4438                 if (sb == null) {
4439                     continue;
4440                 }
4441                 PermissionsState permissionsState = sb.getPermissionsState();
4442                 changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4443                         userId, flagMask, flagValues);
4444             }
4445             if (changed) {
4446                 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4447             }
4448         }
4449     }
4450
4451     private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4452         if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4453                 != PackageManager.PERMISSION_GRANTED
4454             && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4455                 != PackageManager.PERMISSION_GRANTED) {
4456             throw new SecurityException(message + " requires "
4457                     + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4458                     + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4459         }
4460     }
4461
4462     @Override
4463     public boolean shouldShowRequestPermissionRationale(String permissionName,
4464             String packageName, int userId) {
4465         if (UserHandle.getCallingUserId() != userId) {
4466             mContext.enforceCallingPermission(
4467                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4468                     "canShowRequestPermissionRationale for user " + userId);
4469         }
4470
4471         final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4472         if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4473             return false;
4474         }
4475
4476         if (checkPermission(permissionName, packageName, userId)
4477                 == PackageManager.PERMISSION_GRANTED) {
4478             return false;
4479         }
4480
4481         final int flags;
4482
4483         final long identity = Binder.clearCallingIdentity();
4484         try {
4485             flags = getPermissionFlags(permissionName,
4486                     packageName, userId);
4487         } finally {
4488             Binder.restoreCallingIdentity(identity);
4489         }
4490
4491         final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4492                 | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4493                 | PackageManager.FLAG_PERMISSION_USER_FIXED;
4494
4495         if ((flags & fixedFlags) != 0) {
4496             return false;
4497         }
4498
4499         return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4500     }
4501
4502     @Override
4503     public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4504         mContext.enforceCallingOrSelfPermission(
4505                 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4506                 "addOnPermissionsChangeListener");
4507
4508         synchronized (mPackages) {
4509             mOnPermissionChangeListeners.addListenerLocked(listener);
4510         }
4511     }
4512
4513     @Override
4514     public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4515         synchronized (mPackages) {
4516             mOnPermissionChangeListeners.removeListenerLocked(listener);
4517         }
4518     }
4519
4520     @Override
4521     public boolean isProtectedBroadcast(String actionName) {
4522         synchronized (mPackages) {
4523             if (mProtectedBroadcasts.contains(actionName)) {
4524                 return true;
4525             } else if (actionName != null) {
4526                 // TODO: remove these terrible hacks
4527                 if (actionName.startsWith("android.net.netmon.lingerExpired")
4528                         || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4529                         || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4530                         || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4531                     return true;
4532                 }
4533             }
4534         }
4535         return false;
4536     }
4537
4538     @Override
4539     public int checkSignatures(String pkg1, String pkg2) {
4540         synchronized (mPackages) {
4541             final PackageParser.Package p1 = mPackages.get(pkg1);
4542             final PackageParser.Package p2 = mPackages.get(pkg2);
4543             if (p1 == null || p1.mExtras == null
4544                     || p2 == null || p2.mExtras == null) {
4545                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4546             }
4547             return compareSignatures(p1.mSignatures, p2.mSignatures);
4548         }
4549     }
4550
4551     @Override
4552     public int checkUidSignatures(int uid1, int uid2) {
4553         // Map to base uids.
4554         uid1 = UserHandle.getAppId(uid1);
4555         uid2 = UserHandle.getAppId(uid2);
4556         // reader
4557         synchronized (mPackages) {
4558             Signature[] s1;
4559             Signature[] s2;
4560             Object obj = mSettings.getUserIdLPr(uid1);
4561             if (obj != null) {
4562                 if (obj instanceof SharedUserSetting) {
4563                     s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4564                 } else if (obj instanceof PackageSetting) {
4565                     s1 = ((PackageSetting)obj).signatures.mSignatures;
4566                 } else {
4567                     return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4568                 }
4569             } else {
4570                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4571             }
4572             obj = mSettings.getUserIdLPr(uid2);
4573             if (obj != null) {
4574                 if (obj instanceof SharedUserSetting) {
4575                     s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4576                 } else if (obj instanceof PackageSetting) {
4577                     s2 = ((PackageSetting)obj).signatures.mSignatures;
4578                 } else {
4579                     return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4580                 }
4581             } else {
4582                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4583             }
4584             return compareSignatures(s1, s2);
4585         }
4586     }
4587
4588     /**
4589      * This method should typically only be used when granting or revoking
4590      * permissions, since the app may immediately restart after this call.
4591      * <p>
4592      * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4593      * guard your work against the app being relaunched.
4594      */
4595     private void killUid(int appId, int userId, String reason) {
4596         final long identity = Binder.clearCallingIdentity();
4597         try {
4598             IActivityManager am = ActivityManagerNative.getDefault();
4599             if (am != null) {
4600                 try {
4601                     am.killUid(appId, userId, reason);
4602                 } catch (RemoteException e) {
4603                     /* ignore - same process */
4604                 }
4605             }
4606         } finally {
4607             Binder.restoreCallingIdentity(identity);
4608         }
4609     }
4610
4611     /**
4612      * Compares two sets of signatures. Returns:
4613      * <br />
4614      * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4615      * <br />
4616      * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4617      * <br />
4618      * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4619      * <br />
4620      * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4621      * <br />
4622      * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4623      */
4624     static int compareSignatures(Signature[] s1, Signature[] s2) {
4625         if (s1 == null) {
4626             return s2 == null
4627                     ? PackageManager.SIGNATURE_NEITHER_SIGNED
4628                     : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4629         }
4630
4631         if (s2 == null) {
4632             return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4633         }
4634
4635         if (s1.length != s2.length) {
4636             return PackageManager.SIGNATURE_NO_MATCH;
4637         }
4638
4639         // Since both signature sets are of size 1, we can compare without HashSets.
4640         if (s1.length == 1) {
4641             return s1[0].equals(s2[0]) ?
4642                     PackageManager.SIGNATURE_MATCH :
4643                     PackageManager.SIGNATURE_NO_MATCH;
4644         }
4645
4646         ArraySet<Signature> set1 = new ArraySet<Signature>();
4647         for (Signature sig : s1) {
4648             set1.add(sig);
4649         }
4650         ArraySet<Signature> set2 = new ArraySet<Signature>();
4651         for (Signature sig : s2) {
4652             set2.add(sig);
4653         }
4654         // Make sure s2 contains all signatures in s1.
4655         if (set1.equals(set2)) {
4656             return PackageManager.SIGNATURE_MATCH;
4657         }
4658         return PackageManager.SIGNATURE_NO_MATCH;
4659     }
4660
4661     /**
4662      * If the database version for this type of package (internal storage or
4663      * external storage) is less than the version where package signatures
4664      * were updated, return true.
4665      */
4666     private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4667         final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4668         return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4669     }
4670
4671     /**
4672      * Used for backward compatibility to make sure any packages with
4673      * certificate chains get upgraded to the new style. {@code existingSigs}
4674      * will be in the old format (since they were stored on disk from before the
4675      * system upgrade) and {@code scannedSigs} will be in the newer format.
4676      */
4677     private int compareSignaturesCompat(PackageSignatures existingSigs,
4678             PackageParser.Package scannedPkg) {
4679         if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4680             return PackageManager.SIGNATURE_NO_MATCH;
4681         }
4682
4683         ArraySet<Signature> existingSet = new ArraySet<Signature>();
4684         for (Signature sig : existingSigs.mSignatures) {
4685             existingSet.add(sig);
4686         }
4687         ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4688         for (Signature sig : scannedPkg.mSignatures) {
4689             try {
4690                 Signature[] chainSignatures = sig.getChainSignatures();
4691                 for (Signature chainSig : chainSignatures) {
4692                     scannedCompatSet.add(chainSig);
4693                 }
4694             } catch (CertificateEncodingException e) {
4695                 scannedCompatSet.add(sig);
4696             }
4697         }
4698         /*
4699          * Make sure the expanded scanned set contains all signatures in the
4700          * existing one.
4701          */
4702         if (scannedCompatSet.equals(existingSet)) {
4703             // Migrate the old signatures to the new scheme.
4704             existingSigs.assignSignatures(scannedPkg.mSignatures);
4705             // The new KeySets will be re-added later in the scanning process.
4706             synchronized (mPackages) {
4707                 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4708             }
4709             return PackageManager.SIGNATURE_MATCH;
4710         }
4711         return PackageManager.SIGNATURE_NO_MATCH;
4712     }
4713
4714     private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4715         final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4716         return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4717     }
4718
4719     private int compareSignaturesRecover(PackageSignatures existingSigs,
4720             PackageParser.Package scannedPkg) {
4721         if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4722             return PackageManager.SIGNATURE_NO_MATCH;
4723         }
4724
4725         String msg = null;
4726         try {
4727             if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4728                 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4729                         + scannedPkg.packageName);
4730                 return PackageManager.SIGNATURE_MATCH;
4731             }
4732         } catch (CertificateException e) {
4733             msg = e.getMessage();
4734         }
4735
4736         logCriticalInfo(Log.INFO,
4737                 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4738         return PackageManager.SIGNATURE_NO_MATCH;
4739     }
4740
4741     @Override
4742     public List<String> getAllPackages() {
4743         synchronized (mPackages) {
4744             return new ArrayList<String>(mPackages.keySet());
4745         }
4746     }
4747
4748     @Override
4749     public String[] getPackagesForUid(int uid) {
4750         uid = UserHandle.getAppId(uid);
4751         // reader
4752         synchronized (mPackages) {
4753             Object obj = mSettings.getUserIdLPr(uid);
4754             if (obj instanceof SharedUserSetting) {
4755                 final SharedUserSetting sus = (SharedUserSetting) obj;
4756                 final int N = sus.packages.size();
4757                 final String[] res = new String[N];
4758                 for (int i = 0; i < N; i++) {
4759                     res[i] = sus.packages.valueAt(i).name;
4760                 }
4761                 return res;
4762             } else if (obj instanceof PackageSetting) {
4763                 final PackageSetting ps = (PackageSetting) obj;
4764                 return new String[] { ps.name };
4765             }
4766         }
4767         return null;
4768     }
4769
4770     @Override
4771     public String getNameForUid(int uid) {
4772         // reader
4773         synchronized (mPackages) {
4774             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4775             if (obj instanceof SharedUserSetting) {
4776                 final SharedUserSetting sus = (SharedUserSetting) obj;
4777                 return sus.name + ":" + sus.userId;
4778             } else if (obj instanceof PackageSetting) {
4779                 final PackageSetting ps = (PackageSetting) obj;
4780                 return ps.name;
4781             }
4782         }
4783         return null;
4784     }
4785
4786     @Override
4787     public int getUidForSharedUser(String sharedUserName) {
4788         if(sharedUserName == null) {
4789             return -1;
4790         }
4791         // reader
4792         synchronized (mPackages) {
4793             final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4794             if (suid == null) {
4795                 return -1;
4796             }
4797             return suid.userId;
4798         }
4799     }
4800
4801     @Override
4802     public int getFlagsForUid(int uid) {
4803         synchronized (mPackages) {
4804             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4805             if (obj instanceof SharedUserSetting) {
4806                 final SharedUserSetting sus = (SharedUserSetting) obj;
4807                 return sus.pkgFlags;
4808             } else if (obj instanceof PackageSetting) {
4809                 final PackageSetting ps = (PackageSetting) obj;
4810                 return ps.pkgFlags;
4811             }
4812         }
4813         return 0;
4814     }
4815
4816     @Override
4817     public int getPrivateFlagsForUid(int uid) {
4818         synchronized (mPackages) {
4819             Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4820             if (obj instanceof SharedUserSetting) {
4821                 final SharedUserSetting sus = (SharedUserSetting) obj;
4822                 return sus.pkgPrivateFlags;
4823             } else if (obj instanceof PackageSetting) {
4824                 final PackageSetting ps = (PackageSetting) obj;
4825                 return ps.pkgPrivateFlags;
4826             }
4827         }
4828         return 0;
4829     }
4830
4831     @Override
4832     public boolean isUidPrivileged(int uid) {
4833         uid = UserHandle.getAppId(uid);
4834         // reader
4835         synchronized (mPackages) {
4836             Object obj = mSettings.getUserIdLPr(uid);
4837             if (obj instanceof SharedUserSetting) {
4838                 final SharedUserSetting sus = (SharedUserSetting) obj;
4839                 final Iterator<PackageSetting> it = sus.packages.iterator();
4840                 while (it.hasNext()) {
4841                     if (it.next().isPrivileged()) {
4842                         return true;
4843                     }
4844                 }
4845             } else if (obj instanceof PackageSetting) {
4846                 final PackageSetting ps = (PackageSetting) obj;
4847                 return ps.isPrivileged();
4848             }
4849         }
4850         return false;
4851     }
4852
4853     @Override
4854     public String[] getAppOpPermissionPackages(String permissionName) {
4855         synchronized (mPackages) {
4856             ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4857             if (pkgs == null) {
4858                 return null;
4859             }
4860             return pkgs.toArray(new String[pkgs.size()]);
4861         }
4862     }
4863
4864     @Override
4865     public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4866             int flags, int userId) {
4867         try {
4868             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4869
4870             if (!sUserManager.exists(userId)) return null;
4871             flags = updateFlagsForResolve(flags, userId, intent);
4872             enforceCrossUserPermission(Binder.getCallingUid(), userId,
4873                     false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4874
4875             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4876             final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4877                     flags, userId);
4878             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4879
4880             final ResolveInfo bestChoice =
4881                     chooseBestActivity(intent, resolvedType, flags, query, userId);
4882
4883             if (isEphemeralAllowed(intent, query, userId)) {
4884                 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4885                 final EphemeralResolveInfo ai =
4886                         getEphemeralResolveInfo(intent, resolvedType, userId);
4887                 if (ai != null) {
4888                     if (DEBUG_EPHEMERAL) {
4889                         Slog.v(TAG, "Returning an EphemeralResolveInfo");
4890                     }
4891                     bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4892                     bestChoice.ephemeralResolveInfo = ai;
4893                 }
4894                 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4895             }
4896             return bestChoice;
4897         } finally {
4898             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4899         }
4900     }
4901
4902     @Override
4903     public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4904             IntentFilter filter, int match, ComponentName activity) {
4905         final int userId = UserHandle.getCallingUserId();
4906         if (DEBUG_PREFERRED) {
4907             Log.v(TAG, "setLastChosenActivity intent=" + intent
4908                 + " resolvedType=" + resolvedType
4909                 + " flags=" + flags
4910                 + " filter=" + filter
4911                 + " match=" + match
4912                 + " activity=" + activity);
4913             filter.dump(new PrintStreamPrinter(System.out), "    ");
4914         }
4915         intent.setComponent(null);
4916         final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4917                 userId);
4918         // Find any earlier preferred or last chosen entries and nuke them
4919         findPreferredActivity(intent, resolvedType,
4920                 flags, query, 0, false, true, false, userId);
4921         // Add the new activity as the last chosen for this filter
4922         addPreferredActivityInternal(filter, match, null, activity, false, userId,
4923                 "Setting last chosen");
4924     }
4925
4926     @Override
4927     public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4928         final int userId = UserHandle.getCallingUserId();
4929         if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4930         final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4931                 userId);
4932         return findPreferredActivity(intent, resolvedType, flags, query, 0,
4933                 false, false, false, userId);
4934     }
4935
4936
4937     private boolean isEphemeralAllowed(
4938             Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4939         // Short circuit and return early if possible.
4940         if (DISABLE_EPHEMERAL_APPS) {
4941             return false;
4942         }
4943         final int callingUser = UserHandle.getCallingUserId();
4944         if (callingUser != UserHandle.USER_SYSTEM) {
4945             return false;
4946         }
4947         if (mEphemeralResolverConnection == null) {
4948             return false;
4949         }
4950         if (intent.getComponent() != null) {
4951             return false;
4952         }
4953         if (intent.getPackage() != null) {
4954             return false;
4955         }
4956         final boolean isWebUri = hasWebURI(intent);
4957         if (!isWebUri) {
4958             return false;
4959         }
4960         // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4961         synchronized (mPackages) {
4962             final int count = resolvedActivites.size();
4963             for (int n = 0; n < count; n++) {
4964                 ResolveInfo info = resolvedActivites.get(n);
4965                 String packageName = info.activityInfo.packageName;
4966                 PackageSetting ps = mSettings.mPackages.get(packageName);
4967                 if (ps != null) {
4968                     // Try to get the status from User settings first
4969                     long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4970                     int status = (int) (packedStatus >> 32);
4971                     if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4972                             || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4973                         if (DEBUG_EPHEMERAL) {
4974                             Slog.v(TAG, "DENY ephemeral apps;"
4975                                 + " pkg: " + packageName + ", status: " + status);
4976                         }
4977                         return false;
4978                     }
4979                 }
4980             }
4981         }
4982         // We've exhausted all ways to deny ephemeral application; let the system look for them.
4983         return true;
4984     }
4985
4986     private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4987             int userId) {
4988         MessageDigest digest = null;
4989         try {
4990             digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4991         } catch (NoSuchAlgorithmException e) {
4992             // If we can't create a digest, ignore ephemeral apps.
4993             return null;
4994         }
4995
4996         final byte[] hostBytes = intent.getData().getHost().getBytes();
4997         final byte[] digestBytes = digest.digest(hostBytes);
4998         int shaPrefix =
4999                 digestBytes[0] << 24
5000                 | digestBytes[1] << 16
5001                 | digestBytes[2] << 8
5002                 | digestBytes[3] << 0;
5003         final List<EphemeralResolveInfo> ephemeralResolveInfoList =
5004                 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
5005         if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
5006             // No hash prefix match; there are no ephemeral apps for this domain.
5007             return null;
5008         }
5009         for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
5010             EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
5011             if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
5012                 continue;
5013             }
5014             final List<IntentFilter> filters = ephemeralApplication.getFilters();
5015             // No filters; this should never happen.
5016             if (filters.isEmpty()) {
5017                 continue;
5018             }
5019             // We have a domain match; resolve the filters to see if anything matches.
5020             final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
5021             for (int j = filters.size() - 1; j >= 0; --j) {
5022                 final EphemeralResolveIntentInfo intentInfo =
5023                         new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
5024                 ephemeralResolver.addFilter(intentInfo);
5025             }
5026             List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
5027                     intent, resolvedType, false /*defaultOnly*/, userId);
5028             if (!matchedResolveInfoList.isEmpty()) {
5029                 return matchedResolveInfoList.get(0);
5030             }
5031         }
5032         // Hash or filter mis-match; no ephemeral apps for this domain.
5033         return null;
5034     }
5035
5036     private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5037             int flags, List<ResolveInfo> query, int userId) {
5038         if (query != null) {
5039             final int N = query.size();
5040             if (N == 1) {
5041                 return query.get(0);
5042             } else if (N > 1) {
5043                 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5044                 // If there is more than one activity with the same priority,
5045                 // then let the user decide between them.
5046                 ResolveInfo r0 = query.get(0);
5047                 ResolveInfo r1 = query.get(1);
5048                 if (DEBUG_INTENT_MATCHING || debug) {
5049                     Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5050                             + r1.activityInfo.name + "=" + r1.priority);
5051                 }
5052                 // If the first activity has a higher priority, or a different
5053                 // default, then it is always desirable to pick it.
5054                 if (r0.priority != r1.priority
5055                         || r0.preferredOrder != r1.preferredOrder
5056                         || r0.isDefault != r1.isDefault) {
5057                     return query.get(0);
5058                 }
5059                 // If we have saved a preference for a preferred activity for
5060                 // this Intent, use that.
5061                 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5062                         flags, query, r0.priority, true, false, debug, userId);
5063                 if (ri != null) {
5064                     return ri;
5065                 }
5066                 ri = new ResolveInfo(mResolveInfo);
5067                 ri.activityInfo = new ActivityInfo(ri.activityInfo);
5068                 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5069                 // If all of the options come from the same package, show the application's
5070                 // label and icon instead of the generic resolver's.
5071                 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5072                 // and then throw away the ResolveInfo itself, meaning that the caller loses
5073                 // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5074                 // a fallback for this case; we only set the target package's resources on
5075                 // the ResolveInfo, not the ActivityInfo.
5076                 final String intentPackage = intent.getPackage();
5077                 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5078                     final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5079                     ri.resolvePackageName = intentPackage;
5080                     if (userNeedsBadging(userId)) {
5081                         ri.noResourceId = true;
5082                     } else {
5083                         ri.icon = appi.icon;
5084                     }
5085                     ri.iconResourceId = appi.icon;
5086                     ri.labelRes = appi.labelRes;
5087                 }
5088                 ri.activityInfo.applicationInfo = new ApplicationInfo(
5089                         ri.activityInfo.applicationInfo);
5090                 if (userId != 0) {
5091                     ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5092                             UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5093                 }
5094                 // Make sure that the resolver is displayable in car mode
5095                 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5096                 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5097                 return ri;
5098             }
5099         }
5100         return null;
5101     }
5102
5103     /**
5104      * Return true if the given list is not empty and all of its contents have
5105      * an activityInfo with the given package name.
5106      */
5107     private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5108         if (ArrayUtils.isEmpty(list)) {
5109             return false;
5110         }
5111         for (int i = 0, N = list.size(); i < N; i++) {
5112             final ResolveInfo ri = list.get(i);
5113             final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5114             if (ai == null || !packageName.equals(ai.packageName)) {
5115                 return false;
5116             }
5117         }
5118         return true;
5119     }
5120
5121     private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5122             int flags, List<ResolveInfo> query, boolean debug, int userId) {
5123         final int N = query.size();
5124         PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5125                 .get(userId);
5126         // Get the list of persistent preferred activities that handle the intent
5127         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5128         List<PersistentPreferredActivity> pprefs = ppir != null
5129                 ? ppir.queryIntent(intent, resolvedType,
5130                         (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5131                 : null;
5132         if (pprefs != null && pprefs.size() > 0) {
5133             final int M = pprefs.size();
5134             for (int i=0; i<M; i++) {
5135                 final PersistentPreferredActivity ppa = pprefs.get(i);
5136                 if (DEBUG_PREFERRED || debug) {
5137                     Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5138                             + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5139                             + "\n  component=" + ppa.mComponent);
5140                     ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5141                 }
5142                 final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5143                         flags | MATCH_DISABLED_COMPONENTS, userId);
5144                 if (DEBUG_PREFERRED || debug) {
5145                     Slog.v(TAG, "Found persistent preferred activity:");
5146                     if (ai != null) {
5147                         ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5148                     } else {
5149                         Slog.v(TAG, "  null");
5150                     }
5151                 }
5152                 if (ai == null) {
5153                     // This previously registered persistent preferred activity
5154                     // component is no longer known. Ignore it and do NOT remove it.
5155                     continue;
5156                 }
5157                 for (int j=0; j<N; j++) {
5158                     final ResolveInfo ri = query.get(j);
5159                     if (!ri.activityInfo.applicationInfo.packageName
5160                             .equals(ai.applicationInfo.packageName)) {
5161                         continue;
5162                     }
5163                     if (!ri.activityInfo.name.equals(ai.name)) {
5164                         continue;
5165                     }
5166                     //  Found a persistent preference that can handle the intent.
5167                     if (DEBUG_PREFERRED || debug) {
5168                         Slog.v(TAG, "Returning persistent preferred activity: " +
5169                                 ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5170                     }
5171                     return ri;
5172                 }
5173             }
5174         }
5175         return null;
5176     }
5177
5178     // TODO: handle preferred activities missing while user has amnesia
5179     ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5180             List<ResolveInfo> query, int priority, boolean always,
5181             boolean removeMatches, boolean debug, int userId) {
5182         if (!sUserManager.exists(userId)) return null;
5183         flags = updateFlagsForResolve(flags, userId, intent);
5184         // writer
5185         synchronized (mPackages) {
5186             if (intent.getSelector() != null) {
5187                 intent = intent.getSelector();
5188             }
5189             if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5190
5191             // Try to find a matching persistent preferred activity.
5192             ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5193                     debug, userId);
5194
5195             // If a persistent preferred activity matched, use it.
5196             if (pri != null) {
5197                 return pri;
5198             }
5199
5200             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5201             // Get the list of preferred activities that handle the intent
5202             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5203             List<PreferredActivity> prefs = pir != null
5204                     ? pir.queryIntent(intent, resolvedType,
5205                             (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5206                     : null;
5207             if (prefs != null && prefs.size() > 0) {
5208                 boolean changed = false;
5209                 try {
5210                     // First figure out how good the original match set is.
5211                     // We will only allow preferred activities that came
5212                     // from the same match quality.
5213                     int match = 0;
5214
5215                     if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5216
5217                     final int N = query.size();
5218                     for (int j=0; j<N; j++) {
5219                         final ResolveInfo ri = query.get(j);
5220                         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5221                                 + ": 0x" + Integer.toHexString(match));
5222                         if (ri.match > match) {
5223                             match = ri.match;
5224                         }
5225                     }
5226
5227                     if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5228                             + Integer.toHexString(match));
5229
5230                     match &= IntentFilter.MATCH_CATEGORY_MASK;
5231                     final int M = prefs.size();
5232                     for (int i=0; i<M; i++) {
5233                         final PreferredActivity pa = prefs.get(i);
5234                         if (DEBUG_PREFERRED || debug) {
5235                             Slog.v(TAG, "Checking PreferredActivity ds="
5236                                     + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5237                                     + "\n  component=" + pa.mPref.mComponent);
5238                             pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5239                         }
5240                         if (pa.mPref.mMatch != match) {
5241                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5242                                     + Integer.toHexString(pa.mPref.mMatch));
5243                             continue;
5244                         }
5245                         // If it's not an "always" type preferred activity and that's what we're
5246                         // looking for, skip it.
5247                         if (always && !pa.mPref.mAlways) {
5248                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5249                             continue;
5250                         }
5251                         final ActivityInfo ai = getActivityInfo(
5252                                 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5253                                         | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5254                                 userId);
5255                         if (DEBUG_PREFERRED || debug) {
5256                             Slog.v(TAG, "Found preferred activity:");
5257                             if (ai != null) {
5258                                 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5259                             } else {
5260                                 Slog.v(TAG, "  null");
5261                             }
5262                         }
5263                         if (ai == null) {
5264                             // This previously registered preferred activity
5265                             // component is no longer known.  Most likely an update
5266                             // to the app was installed and in the new version this
5267                             // component no longer exists.  Clean it up by removing
5268                             // it from the preferred activities list, and skip it.
5269                             Slog.w(TAG, "Removing dangling preferred activity: "
5270                                     + pa.mPref.mComponent);
5271                             pir.removeFilter(pa);
5272                             changed = true;
5273                             continue;
5274                         }
5275                         for (int j=0; j<N; j++) {
5276                             final ResolveInfo ri = query.get(j);
5277                             if (!ri.activityInfo.applicationInfo.packageName
5278                                     .equals(ai.applicationInfo.packageName)) {
5279                                 continue;
5280                             }
5281                             if (!ri.activityInfo.name.equals(ai.name)) {
5282                                 continue;
5283                             }
5284
5285                             if (removeMatches) {
5286                                 pir.removeFilter(pa);
5287                                 changed = true;
5288                                 if (DEBUG_PREFERRED) {
5289                                     Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5290                                 }
5291                                 break;
5292                             }
5293
5294                             // Okay we found a previously set preferred or last chosen app.
5295                             // If the result set is different from when this
5296                             // was created, we need to clear it and re-ask the
5297                             // user their preference, if we're looking for an "always" type entry.
5298                             if (always && !pa.mPref.sameSet(query)) {
5299                                 Slog.i(TAG, "Result set changed, dropping preferred activity for "
5300                                         + intent + " type " + resolvedType);
5301                                 if (DEBUG_PREFERRED) {
5302                                     Slog.v(TAG, "Removing preferred activity since set changed "
5303                                             + pa.mPref.mComponent);
5304                                 }
5305                                 pir.removeFilter(pa);
5306                                 // Re-add the filter as a "last chosen" entry (!always)
5307                                 PreferredActivity lastChosen = new PreferredActivity(
5308                                         pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5309                                 pir.addFilter(lastChosen);
5310                                 changed = true;
5311                                 return null;
5312                             }
5313
5314                             // Yay! Either the set matched or we're looking for the last chosen
5315                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5316                                     + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5317                             return ri;
5318                         }
5319                     }
5320                 } finally {
5321                     if (changed) {
5322                         if (DEBUG_PREFERRED) {
5323                             Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5324                         }
5325                         scheduleWritePackageRestrictionsLocked(userId);
5326                     }
5327                 }
5328             }
5329         }
5330         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5331         return null;
5332     }
5333
5334     /*
5335      * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5336      */
5337     @Override
5338     public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5339             int targetUserId) {
5340         mContext.enforceCallingOrSelfPermission(
5341                 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5342         List<CrossProfileIntentFilter> matches =
5343                 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5344         if (matches != null) {
5345             int size = matches.size();
5346             for (int i = 0; i < size; i++) {
5347                 if (matches.get(i).getTargetUserId() == targetUserId) return true;
5348             }
5349         }
5350         if (hasWebURI(intent)) {
5351             // cross-profile app linking works only towards the parent.
5352             final UserInfo parent = getProfileParent(sourceUserId);
5353             synchronized(mPackages) {
5354                 int flags = updateFlagsForResolve(0, parent.id, intent);
5355                 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5356                         intent, resolvedType, flags, sourceUserId, parent.id);
5357                 return xpDomainInfo != null;
5358             }
5359         }
5360         return false;
5361     }
5362
5363     private UserInfo getProfileParent(int userId) {
5364         final long identity = Binder.clearCallingIdentity();
5365         try {
5366             return sUserManager.getProfileParent(userId);
5367         } finally {
5368             Binder.restoreCallingIdentity(identity);
5369         }
5370     }
5371
5372     private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5373             String resolvedType, int userId) {
5374         CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5375         if (resolver != null) {
5376             return resolver.queryIntent(intent, resolvedType, false, userId);
5377         }
5378         return null;
5379     }
5380
5381     @Override
5382     public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5383             String resolvedType, int flags, int userId) {
5384         try {
5385             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5386
5387             return new ParceledListSlice<>(
5388                     queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5389         } finally {
5390             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5391         }
5392     }
5393
5394     private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5395             String resolvedType, int flags, int userId) {
5396         if (!sUserManager.exists(userId)) return Collections.emptyList();
5397         flags = updateFlagsForResolve(flags, userId, intent);
5398         enforceCrossUserPermission(Binder.getCallingUid(), userId,
5399                 false /* requireFullPermission */, false /* checkShell */,
5400                 "query intent activities");
5401         ComponentName comp = intent.getComponent();
5402         if (comp == null) {
5403             if (intent.getSelector() != null) {
5404                 intent = intent.getSelector();
5405                 comp = intent.getComponent();
5406             }
5407         }
5408
5409         if (comp != null) {
5410             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5411             final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5412             if (ai != null) {
5413                 final ResolveInfo ri = new ResolveInfo();
5414                 ri.activityInfo = ai;
5415                 list.add(ri);
5416             }
5417             return list;
5418         }
5419
5420         // reader
5421         synchronized (mPackages) {
5422             final String pkgName = intent.getPackage();
5423             if (pkgName == null) {
5424                 List<CrossProfileIntentFilter> matchingFilters =
5425                         getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5426                 // Check for results that need to skip the current profile.
5427                 ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5428                         resolvedType, flags, userId);
5429                 if (xpResolveInfo != null) {
5430                     List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5431                     result.add(xpResolveInfo);
5432                     return filterIfNotSystemUser(result, userId);
5433                 }
5434
5435                 // Check for results in the current profile.
5436                 List<ResolveInfo> result = mActivities.queryIntent(
5437                         intent, resolvedType, flags, userId);
5438                 result = filterIfNotSystemUser(result, userId);
5439
5440                 // Check for cross profile results.
5441                 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5442                 xpResolveInfo = queryCrossProfileIntents(
5443                         matchingFilters, intent, resolvedType, flags, userId,
5444                         hasNonNegativePriorityResult);
5445                 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5446                     boolean isVisibleToUser = filterIfNotSystemUser(
5447                             Collections.singletonList(xpResolveInfo), userId).size() > 0;
5448                     if (isVisibleToUser) {
5449                         result.add(xpResolveInfo);
5450                         Collections.sort(result, mResolvePrioritySorter);
5451                     }
5452                 }
5453                 if (hasWebURI(intent)) {
5454                     CrossProfileDomainInfo xpDomainInfo = null;
5455                     final UserInfo parent = getProfileParent(userId);
5456                     if (parent != null) {
5457                         xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5458                                 flags, userId, parent.id);
5459                     }
5460                     if (xpDomainInfo != null) {
5461                         if (xpResolveInfo != null) {
5462                             // If we didn't remove it, the cross-profile ResolveInfo would be twice
5463                             // in the result.
5464                             result.remove(xpResolveInfo);
5465                         }
5466                         if (result.size() == 0) {
5467                             result.add(xpDomainInfo.resolveInfo);
5468                             return result;
5469                         }
5470                     } else if (result.size() <= 1) {
5471                         return result;
5472                     }
5473                     result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5474                             xpDomainInfo, userId);
5475                     Collections.sort(result, mResolvePrioritySorter);
5476                 }
5477                 return result;
5478             }
5479             final PackageParser.Package pkg = mPackages.get(pkgName);
5480             if (pkg != null) {
5481                 return filterIfNotSystemUser(
5482                         mActivities.queryIntentForPackage(
5483                                 intent, resolvedType, flags, pkg.activities, userId),
5484                         userId);
5485             }
5486             return new ArrayList<ResolveInfo>();
5487         }
5488     }
5489
5490     private static class CrossProfileDomainInfo {
5491         /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5492         ResolveInfo resolveInfo;
5493         /* Best domain verification status of the activities found in the other profile */
5494         int bestDomainVerificationStatus;
5495     }
5496
5497     private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5498             String resolvedType, int flags, int sourceUserId, int parentUserId) {
5499         if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5500                 sourceUserId)) {
5501             return null;
5502         }
5503         List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5504                 resolvedType, flags, parentUserId);
5505
5506         if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5507             return null;
5508         }
5509         CrossProfileDomainInfo result = null;
5510         int size = resultTargetUser.size();
5511         for (int i = 0; i < size; i++) {
5512             ResolveInfo riTargetUser = resultTargetUser.get(i);
5513             // Intent filter verification is only for filters that specify a host. So don't return
5514             // those that handle all web uris.
5515             if (riTargetUser.handleAllWebDataURI) {
5516                 continue;
5517             }
5518             String packageName = riTargetUser.activityInfo.packageName;
5519             PackageSetting ps = mSettings.mPackages.get(packageName);
5520             if (ps == null) {
5521                 continue;
5522             }
5523             long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5524             int status = (int)(verificationState >> 32);
5525             if (result == null) {
5526                 result = new CrossProfileDomainInfo();
5527                 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5528                         sourceUserId, parentUserId);
5529                 result.bestDomainVerificationStatus = status;
5530             } else {
5531                 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5532                         result.bestDomainVerificationStatus);
5533             }
5534         }
5535         // Don't consider matches with status NEVER across profiles.
5536         if (result != null && result.bestDomainVerificationStatus
5537                 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5538             return null;
5539         }
5540         return result;
5541     }
5542
5543     /**
5544      * Verification statuses are ordered from the worse to the best, except for
5545      * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5546      */
5547     private int bestDomainVerificationStatus(int status1, int status2) {
5548         if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5549             return status2;
5550         }
5551         if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5552             return status1;
5553         }
5554         return (int) MathUtils.max(status1, status2);
5555     }
5556
5557     private boolean isUserEnabled(int userId) {
5558         long callingId = Binder.clearCallingIdentity();
5559         try {
5560             UserInfo userInfo = sUserManager.getUserInfo(userId);
5561             return userInfo != null && userInfo.isEnabled();
5562         } finally {
5563             Binder.restoreCallingIdentity(callingId);
5564         }
5565     }
5566
5567     /**
5568      * Filter out activities with systemUserOnly flag set, when current user is not System.
5569      *
5570      * @return filtered list
5571      */
5572     private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5573         if (userId == UserHandle.USER_SYSTEM) {
5574             return resolveInfos;
5575         }
5576         for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5577             ResolveInfo info = resolveInfos.get(i);
5578             if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5579                 resolveInfos.remove(i);
5580             }
5581         }
5582         return resolveInfos;
5583     }
5584
5585     /**
5586      * @param resolveInfos list of resolve infos in descending priority order
5587      * @return if the list contains a resolve info with non-negative priority
5588      */
5589     private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5590         return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5591     }
5592
5593     private static boolean hasWebURI(Intent intent) {
5594         if (intent.getData() == null) {
5595             return false;
5596         }
5597         final String scheme = intent.getScheme();
5598         if (TextUtils.isEmpty(scheme)) {
5599             return false;
5600         }
5601         return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5602     }
5603
5604     private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5605             int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5606             int userId) {
5607         final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5608
5609         if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5610             Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5611                     candidates.size());
5612         }
5613
5614         ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5615         ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5616         ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5617         ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5618         ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5619         ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5620
5621         synchronized (mPackages) {
5622             final int count = candidates.size();
5623             // First, try to use linked apps. Partition the candidates into four lists:
5624             // one for the final results, one for the "do not use ever", one for "undefined status"
5625             // and finally one for "browser app type".
5626             for (int n=0; n<count; n++) {
5627                 ResolveInfo info = candidates.get(n);
5628                 String packageName = info.activityInfo.packageName;
5629                 PackageSetting ps = mSettings.mPackages.get(packageName);
5630                 if (ps != null) {
5631                     // Add to the special match all list (Browser use case)
5632                     if (info.handleAllWebDataURI) {
5633                         matchAllList.add(info);
5634                         continue;
5635                     }
5636                     // Try to get the status from User settings first
5637                     long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5638                     int status = (int)(packedStatus >> 32);
5639                     int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5640                     if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5641                         if (DEBUG_DOMAIN_VERIFICATION) {
5642                             Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5643                                     + " : linkgen=" + linkGeneration);
5644                         }
5645                         // Use link-enabled generation as preferredOrder, i.e.
5646                         // prefer newly-enabled over earlier-enabled.
5647                         info.preferredOrder = linkGeneration;
5648                         alwaysList.add(info);
5649                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5650                         if (DEBUG_DOMAIN_VERIFICATION) {
5651                             Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5652                         }
5653                         neverList.add(info);
5654                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5655                         if (DEBUG_DOMAIN_VERIFICATION) {
5656                             Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5657                         }
5658                         alwaysAskList.add(info);
5659                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5660                             status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5661                         if (DEBUG_DOMAIN_VERIFICATION) {
5662                             Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5663                         }
5664                         undefinedList.add(info);
5665                     }
5666                 }
5667             }
5668
5669             // We'll want to include browser possibilities in a few cases
5670             boolean includeBrowser = false;
5671
5672             // First try to add the "always" resolution(s) for the current user, if any
5673             if (alwaysList.size() > 0) {
5674                 result.addAll(alwaysList);
5675             } else {
5676                 // Add all undefined apps as we want them to appear in the disambiguation dialog.
5677                 result.addAll(undefinedList);
5678                 // Maybe add one for the other profile.
5679                 if (xpDomainInfo != null && (
5680                         xpDomainInfo.bestDomainVerificationStatus
5681                         != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5682                     result.add(xpDomainInfo.resolveInfo);
5683                 }
5684                 includeBrowser = true;
5685             }
5686
5687             // The presence of any 'always ask' alternatives means we'll also offer browsers.
5688             // If there were 'always' entries their preferred order has been set, so we also
5689             // back that off to make the alternatives equivalent
5690             if (alwaysAskList.size() > 0) {
5691                 for (ResolveInfo i : result) {
5692                     i.preferredOrder = 0;
5693                 }
5694                 result.addAll(alwaysAskList);
5695                 includeBrowser = true;
5696             }
5697
5698             if (includeBrowser) {
5699                 // Also add browsers (all of them or only the default one)
5700                 if (DEBUG_DOMAIN_VERIFICATION) {
5701                     Slog.v(TAG, "   ...including browsers in candidate set");
5702                 }
5703                 if ((matchFlags & MATCH_ALL) != 0) {
5704                     result.addAll(matchAllList);
5705                 } else {
5706                     // Browser/generic handling case.  If there's a default browser, go straight
5707                     // to that (but only if there is no other higher-priority match).
5708                     final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5709                     int maxMatchPrio = 0;
5710                     ResolveInfo defaultBrowserMatch = null;
5711                     final int numCandidates = matchAllList.size();
5712                     for (int n = 0; n < numCandidates; n++) {
5713                         ResolveInfo info = matchAllList.get(n);
5714                         // track the highest overall match priority...
5715                         if (info.priority > maxMatchPrio) {
5716                             maxMatchPrio = info.priority;
5717                         }
5718                         // ...and the highest-priority default browser match
5719                         if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5720                             if (defaultBrowserMatch == null
5721                                     || (defaultBrowserMatch.priority < info.priority)) {
5722                                 if (debug) {
5723                                     Slog.v(TAG, "Considering default browser match " + info);
5724                                 }
5725                                 defaultBrowserMatch = info;
5726                             }
5727                         }
5728                     }
5729                     if (defaultBrowserMatch != null
5730                             && defaultBrowserMatch.priority >= maxMatchPrio
5731                             && !TextUtils.isEmpty(defaultBrowserPackageName))
5732                     {
5733                         if (debug) {
5734                             Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5735                         }
5736                         result.add(defaultBrowserMatch);
5737                     } else {
5738                         result.addAll(matchAllList);
5739                     }
5740                 }
5741
5742                 // If there is nothing selected, add all candidates and remove the ones that the user
5743                 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5744                 if (result.size() == 0) {
5745                     result.addAll(candidates);
5746                     result.removeAll(neverList);
5747                 }
5748             }
5749         }
5750         if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5751             Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5752                     result.size());
5753             for (ResolveInfo info : result) {
5754                 Slog.v(TAG, "  + " + info.activityInfo);
5755             }
5756         }
5757         return result;
5758     }
5759
5760     // Returns a packed value as a long:
5761     //
5762     // high 'int'-sized word: link status: undefined/ask/never/always.
5763     // low 'int'-sized word: relative priority among 'always' results.
5764     private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5765         long result = ps.getDomainVerificationStatusForUser(userId);
5766         // if none available, get the master status
5767         if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5768             if (ps.getIntentFilterVerificationInfo() != null) {
5769                 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5770             }
5771         }
5772         return result;
5773     }
5774
5775     private ResolveInfo querySkipCurrentProfileIntents(
5776             List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5777             int flags, int sourceUserId) {
5778         if (matchingFilters != null) {
5779             int size = matchingFilters.size();
5780             for (int i = 0; i < size; i ++) {
5781                 CrossProfileIntentFilter filter = matchingFilters.get(i);
5782                 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5783                     // Checking if there are activities in the target user that can handle the
5784                     // intent.
5785                     ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5786                             resolvedType, flags, sourceUserId);
5787                     if (resolveInfo != null) {
5788                         return resolveInfo;
5789                     }
5790                 }
5791             }
5792         }
5793         return null;
5794     }
5795
5796     // Return matching ResolveInfo in target user if any.
5797     private ResolveInfo queryCrossProfileIntents(
5798             List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5799             int flags, int sourceUserId, boolean matchInCurrentProfile) {
5800         if (matchingFilters != null) {
5801             // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5802             // match the same intent. For performance reasons, it is better not to
5803             // run queryIntent twice for the same userId
5804             SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5805             int size = matchingFilters.size();
5806             for (int i = 0; i < size; i++) {
5807                 CrossProfileIntentFilter filter = matchingFilters.get(i);
5808                 int targetUserId = filter.getTargetUserId();
5809                 boolean skipCurrentProfile =
5810                         (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5811                 boolean skipCurrentProfileIfNoMatchFound =
5812                         (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5813                 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5814                         && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5815                     // Checking if there are activities in the target user that can handle the
5816                     // intent.
5817                     ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5818                             resolvedType, flags, sourceUserId);
5819                     if (resolveInfo != null) return resolveInfo;
5820                     alreadyTriedUserIds.put(targetUserId, true);
5821                 }
5822             }
5823         }
5824         return null;
5825     }
5826
5827     /**
5828      * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5829      * will forward the intent to the filter's target user.
5830      * Otherwise, returns null.
5831      */
5832     private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5833             String resolvedType, int flags, int sourceUserId) {
5834         int targetUserId = filter.getTargetUserId();
5835         List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5836                 resolvedType, flags, targetUserId);
5837         if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5838             // If all the matches in the target profile are suspended, return null.
5839             for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5840                 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5841                         & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5842                     return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5843                             targetUserId);
5844                 }
5845             }
5846         }
5847         return null;
5848     }
5849
5850     private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5851             int sourceUserId, int targetUserId) {
5852         ResolveInfo forwardingResolveInfo = new ResolveInfo();
5853         long ident = Binder.clearCallingIdentity();
5854         boolean targetIsProfile;
5855         try {
5856             targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5857         } finally {
5858             Binder.restoreCallingIdentity(ident);
5859         }
5860         String className;
5861         if (targetIsProfile) {
5862             className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5863         } else {
5864             className = FORWARD_INTENT_TO_PARENT;
5865         }
5866         ComponentName forwardingActivityComponentName = new ComponentName(
5867                 mAndroidApplication.packageName, className);
5868         ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5869                 sourceUserId);
5870         if (!targetIsProfile) {
5871             forwardingActivityInfo.showUserIcon = targetUserId;
5872             forwardingResolveInfo.noResourceId = true;
5873         }
5874         forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5875         forwardingResolveInfo.priority = 0;
5876         forwardingResolveInfo.preferredOrder = 0;
5877         forwardingResolveInfo.match = 0;
5878         forwardingResolveInfo.isDefault = true;
5879         forwardingResolveInfo.filter = filter;
5880         forwardingResolveInfo.targetUserId = targetUserId;
5881         return forwardingResolveInfo;
5882     }
5883
5884     @Override
5885     public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5886             Intent[] specifics, String[] specificTypes, Intent intent,
5887             String resolvedType, int flags, int userId) {
5888         return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5889                 specificTypes, intent, resolvedType, flags, userId));
5890     }
5891
5892     private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5893             Intent[] specifics, String[] specificTypes, Intent intent,
5894             String resolvedType, int flags, int userId) {
5895         if (!sUserManager.exists(userId)) return Collections.emptyList();
5896         flags = updateFlagsForResolve(flags, userId, intent);
5897         enforceCrossUserPermission(Binder.getCallingUid(), userId,
5898                 false /* requireFullPermission */, false /* checkShell */,
5899                 "query intent activity options");
5900         final String resultsAction = intent.getAction();
5901
5902         final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5903                 | PackageManager.GET_RESOLVED_FILTER, userId);
5904
5905         if (DEBUG_INTENT_MATCHING) {
5906             Log.v(TAG, "Query " + intent + ": " + results);
5907         }
5908
5909         int specificsPos = 0;
5910         int N;
5911
5912         // todo: note that the algorithm used here is O(N^2).  This
5913         // isn't a problem in our current environment, but if we start running
5914         // into situations where we have more than 5 or 10 matches then this
5915         // should probably be changed to something smarter...
5916
5917         // First we go through and resolve each of the specific items
5918         // that were supplied, taking care of removing any corresponding
5919         // duplicate items in the generic resolve list.
5920         if (specifics != null) {
5921             for (int i=0; i<specifics.length; i++) {
5922                 final Intent sintent = specifics[i];
5923                 if (sintent == null) {
5924                     continue;
5925                 }
5926
5927                 if (DEBUG_INTENT_MATCHING) {
5928                     Log.v(TAG, "Specific #" + i + ": " + sintent);
5929                 }
5930
5931                 String action = sintent.getAction();
5932                 if (resultsAction != null && resultsAction.equals(action)) {
5933                     // If this action was explicitly requested, then don't
5934                     // remove things that have it.
5935                     action = null;
5936                 }
5937
5938                 ResolveInfo ri = null;
5939                 ActivityInfo ai = null;
5940
5941                 ComponentName comp = sintent.getComponent();
5942                 if (comp == null) {
5943                     ri = resolveIntent(
5944                         sintent,
5945                         specificTypes != null ? specificTypes[i] : null,
5946                             flags, userId);
5947                     if (ri == null) {
5948                         continue;
5949                     }
5950                     if (ri == mResolveInfo) {
5951                         // ACK!  Must do something better with this.
5952                     }
5953                     ai = ri.activityInfo;
5954                     comp = new ComponentName(ai.applicationInfo.packageName,
5955                             ai.name);
5956                 } else {
5957                     ai = getActivityInfo(comp, flags, userId);
5958                     if (ai == null) {
5959                         continue;
5960                     }
5961                 }
5962
5963                 // Look for any generic query activities that are duplicates
5964                 // of this specific one, and remove them from the results.
5965                 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5966                 N = results.size();
5967                 int j;
5968                 for (j=specificsPos; j<N; j++) {
5969                     ResolveInfo sri = results.get(j);
5970                     if ((sri.activityInfo.name.equals(comp.getClassName())
5971                             && sri.activityInfo.applicationInfo.packageName.equals(
5972                                     comp.getPackageName()))
5973                         || (action != null && sri.filter.matchAction(action))) {
5974                         results.remove(j);
5975                         if (DEBUG_INTENT_MATCHING) Log.v(
5976                             TAG, "Removing duplicate item from " + j
5977                             + " due to specific " + specificsPos);
5978                         if (ri == null) {
5979                             ri = sri;
5980                         }
5981                         j--;
5982                         N--;
5983                     }
5984                 }
5985
5986                 // Add this specific item to its proper place.
5987                 if (ri == null) {
5988                     ri = new ResolveInfo();
5989                     ri.activityInfo = ai;
5990                 }
5991                 results.add(specificsPos, ri);
5992                 ri.specificIndex = i;
5993                 specificsPos++;
5994             }
5995         }
5996
5997         // Now we go through the remaining generic results and remove any
5998         // duplicate actions that are found here.
5999         N = results.size();
6000         for (int i=specificsPos; i<N-1; i++) {
6001             final ResolveInfo rii = results.get(i);
6002             if (rii.filter == null) {
6003                 continue;
6004             }
6005
6006             // Iterate over all of the actions of this result's intent
6007             // filter...  typically this should be just one.
6008             final Iterator<String> it = rii.filter.actionsIterator();
6009             if (it == null) {
6010                 continue;
6011             }
6012             while (it.hasNext()) {
6013                 final String action = it.next();
6014                 if (resultsAction != null && resultsAction.equals(action)) {
6015                     // If this action was explicitly requested, then don't
6016                     // remove things that have it.
6017                     continue;
6018                 }
6019                 for (int j=i+1; j<N; j++) {
6020                     final ResolveInfo rij = results.get(j);
6021                     if (rij.filter != null && rij.filter.hasAction(action)) {
6022                         results.remove(j);
6023                         if (DEBUG_INTENT_MATCHING) Log.v(
6024                             TAG, "Removing duplicate item from " + j
6025                             + " due to action " + action + " at " + i);
6026                         j--;
6027                         N--;
6028                     }
6029                 }
6030             }
6031
6032             // If the caller didn't request filter information, drop it now
6033             // so we don't have to marshall/unmarshall it.
6034             if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6035                 rii.filter = null;
6036             }
6037         }
6038
6039         // Filter out the caller activity if so requested.
6040         if (caller != null) {
6041             N = results.size();
6042             for (int i=0; i<N; i++) {
6043                 ActivityInfo ainfo = results.get(i).activityInfo;
6044                 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6045                         && caller.getClassName().equals(ainfo.name)) {
6046                     results.remove(i);
6047                     break;
6048                 }
6049             }
6050         }
6051
6052         // If the caller didn't request filter information,
6053         // drop them now so we don't have to
6054         // marshall/unmarshall it.
6055         if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6056             N = results.size();
6057             for (int i=0; i<N; i++) {
6058                 results.get(i).filter = null;
6059             }
6060         }
6061
6062         if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6063         return results;
6064     }
6065
6066     @Override
6067     public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6068             String resolvedType, int flags, int userId) {
6069         return new ParceledListSlice<>(
6070                 queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6071     }
6072
6073     private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6074             String resolvedType, int flags, int userId) {
6075         if (!sUserManager.exists(userId)) return Collections.emptyList();
6076         flags = updateFlagsForResolve(flags, userId, intent);
6077         ComponentName comp = intent.getComponent();
6078         if (comp == null) {
6079             if (intent.getSelector() != null) {
6080                 intent = intent.getSelector();
6081                 comp = intent.getComponent();
6082             }
6083         }
6084         if (comp != null) {
6085             List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6086             ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6087             if (ai != null) {
6088                 ResolveInfo ri = new ResolveInfo();
6089                 ri.activityInfo = ai;
6090                 list.add(ri);
6091             }
6092             return list;
6093         }
6094
6095         // reader
6096         synchronized (mPackages) {
6097             String pkgName = intent.getPackage();
6098             if (pkgName == null) {
6099                 return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6100             }
6101             final PackageParser.Package pkg = mPackages.get(pkgName);
6102             if (pkg != null) {
6103                 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6104                         userId);
6105             }
6106             return Collections.emptyList();
6107         }
6108     }
6109
6110     @Override
6111     public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6112         if (!sUserManager.exists(userId)) return null;
6113         flags = updateFlagsForResolve(flags, userId, intent);
6114         List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6115         if (query != null) {
6116             if (query.size() >= 1) {
6117                 // If there is more than one service with the same priority,
6118                 // just arbitrarily pick the first one.
6119                 return query.get(0);
6120             }
6121         }
6122         return null;
6123     }
6124
6125     @Override
6126     public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6127             String resolvedType, int flags, int userId) {
6128         return new ParceledListSlice<>(
6129                 queryIntentServicesInternal(intent, resolvedType, flags, userId));
6130     }
6131
6132     private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6133             String resolvedType, int flags, int userId) {
6134         if (!sUserManager.exists(userId)) return Collections.emptyList();
6135         flags = updateFlagsForResolve(flags, userId, intent);
6136         ComponentName comp = intent.getComponent();
6137         if (comp == null) {
6138             if (intent.getSelector() != null) {
6139                 intent = intent.getSelector();
6140                 comp = intent.getComponent();
6141             }
6142         }
6143         if (comp != null) {
6144             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6145             final ServiceInfo si = getServiceInfo(comp, flags, userId);
6146             if (si != null) {
6147                 final ResolveInfo ri = new ResolveInfo();
6148                 ri.serviceInfo = si;
6149                 list.add(ri);
6150             }
6151             return list;
6152         }
6153
6154         // reader
6155         synchronized (mPackages) {
6156             String pkgName = intent.getPackage();
6157             if (pkgName == null) {
6158                 return mServices.queryIntent(intent, resolvedType, flags, userId);
6159             }
6160             final PackageParser.Package pkg = mPackages.get(pkgName);
6161             if (pkg != null) {
6162                 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6163                         userId);
6164             }
6165             return Collections.emptyList();
6166         }
6167     }
6168
6169     @Override
6170     public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6171             String resolvedType, int flags, int userId) {
6172         return new ParceledListSlice<>(
6173                 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6174     }
6175
6176     private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6177             Intent intent, String resolvedType, int flags, int userId) {
6178         if (!sUserManager.exists(userId)) return Collections.emptyList();
6179         flags = updateFlagsForResolve(flags, userId, intent);
6180         ComponentName comp = intent.getComponent();
6181         if (comp == null) {
6182             if (intent.getSelector() != null) {
6183                 intent = intent.getSelector();
6184                 comp = intent.getComponent();
6185             }
6186         }
6187         if (comp != null) {
6188             final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6189             final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6190             if (pi != null) {
6191                 final ResolveInfo ri = new ResolveInfo();
6192                 ri.providerInfo = pi;
6193                 list.add(ri);
6194             }
6195             return list;
6196         }
6197
6198         // reader
6199         synchronized (mPackages) {
6200             String pkgName = intent.getPackage();
6201             if (pkgName == null) {
6202                 return mProviders.queryIntent(intent, resolvedType, flags, userId);
6203             }
6204             final PackageParser.Package pkg = mPackages.get(pkgName);
6205             if (pkg != null) {
6206                 return mProviders.queryIntentForPackage(
6207                         intent, resolvedType, flags, pkg.providers, userId);
6208             }
6209             return Collections.emptyList();
6210         }
6211     }
6212
6213     @Override
6214     public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6215         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6216         flags = updateFlagsForPackage(flags, userId, null);
6217         final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6218         enforceCrossUserPermission(Binder.getCallingUid(), userId,
6219                 true /* requireFullPermission */, false /* checkShell */,
6220                 "get installed packages");
6221
6222         // writer
6223         synchronized (mPackages) {
6224             ArrayList<PackageInfo> list;
6225             if (listUninstalled) {
6226                 list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6227                 for (PackageSetting ps : mSettings.mPackages.values()) {
6228                     final PackageInfo pi;
6229                     if (ps.pkg != null) {
6230                         pi = generatePackageInfo(ps, flags, userId);
6231                     } else {
6232                         pi = generatePackageInfo(ps, flags, userId);
6233                     }
6234                     if (pi != null) {
6235                         list.add(pi);
6236                     }
6237                 }
6238             } else {
6239                 list = new ArrayList<PackageInfo>(mPackages.size());
6240                 for (PackageParser.Package p : mPackages.values()) {
6241                     final PackageInfo pi =
6242                             generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6243                     if (pi != null) {
6244                         list.add(pi);
6245                     }
6246                 }
6247             }
6248
6249             return new ParceledListSlice<PackageInfo>(list);
6250         }
6251     }
6252
6253     private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6254             String[] permissions, boolean[] tmp, int flags, int userId) {
6255         int numMatch = 0;
6256         final PermissionsState permissionsState = ps.getPermissionsState();
6257         for (int i=0; i<permissions.length; i++) {
6258             final String permission = permissions[i];
6259             if (permissionsState.hasPermission(permission, userId)) {
6260                 tmp[i] = true;
6261                 numMatch++;
6262             } else {
6263                 tmp[i] = false;
6264             }
6265         }
6266         if (numMatch == 0) {
6267             return;
6268         }
6269         final PackageInfo pi;
6270         if (ps.pkg != null) {
6271             pi = generatePackageInfo(ps, flags, userId);
6272         } else {
6273             pi = generatePackageInfo(ps, flags, userId);
6274         }
6275         // The above might return null in cases of uninstalled apps or install-state
6276         // skew across users/profiles.
6277         if (pi != null) {
6278             if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6279                 if (numMatch == permissions.length) {
6280                     pi.requestedPermissions = permissions;
6281                 } else {
6282                     pi.requestedPermissions = new String[numMatch];
6283                     numMatch = 0;
6284                     for (int i=0; i<permissions.length; i++) {
6285                         if (tmp[i]) {
6286                             pi.requestedPermissions[numMatch] = permissions[i];
6287                             numMatch++;
6288                         }
6289                     }
6290                 }
6291             }
6292             list.add(pi);
6293         }
6294     }
6295
6296     @Override
6297     public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6298             String[] permissions, int flags, int userId) {
6299         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6300         flags = updateFlagsForPackage(flags, userId, permissions);
6301         final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6302
6303         // writer
6304         synchronized (mPackages) {
6305             ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6306             boolean[] tmpBools = new boolean[permissions.length];
6307             if (listUninstalled) {
6308                 for (PackageSetting ps : mSettings.mPackages.values()) {
6309                     addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6310                 }
6311             } else {
6312                 for (PackageParser.Package pkg : mPackages.values()) {
6313                     PackageSetting ps = (PackageSetting)pkg.mExtras;
6314                     if (ps != null) {
6315                         addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6316                                 userId);
6317                     }
6318                 }
6319             }
6320
6321             return new ParceledListSlice<PackageInfo>(list);
6322         }
6323     }
6324
6325     @Override
6326     public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6327         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6328         flags = updateFlagsForApplication(flags, userId, null);
6329         final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6330
6331         // writer
6332         synchronized (mPackages) {
6333             ArrayList<ApplicationInfo> list;
6334             if (listUninstalled) {
6335                 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6336                 for (PackageSetting ps : mSettings.mPackages.values()) {
6337                     ApplicationInfo ai;
6338                     if (ps.pkg != null) {
6339                         ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6340                                 ps.readUserState(userId), userId);
6341                     } else {
6342                         ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6343                     }
6344                     if (ai != null) {
6345                         list.add(ai);
6346                     }
6347                 }
6348             } else {
6349                 list = new ArrayList<ApplicationInfo>(mPackages.size());
6350                 for (PackageParser.Package p : mPackages.values()) {
6351                     if (p.mExtras != null) {
6352                         ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6353                                 ((PackageSetting)p.mExtras).readUserState(userId), userId);
6354                         if (ai != null) {
6355                             list.add(ai);
6356                         }
6357                     }
6358                 }
6359             }
6360
6361             return new ParceledListSlice<ApplicationInfo>(list);
6362         }
6363     }
6364
6365     @Override
6366     public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6367         if (DISABLE_EPHEMERAL_APPS) {
6368             return null;
6369         }
6370
6371         mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6372                 "getEphemeralApplications");
6373         enforceCrossUserPermission(Binder.getCallingUid(), userId,
6374                 true /* requireFullPermission */, false /* checkShell */,
6375                 "getEphemeralApplications");
6376         synchronized (mPackages) {
6377             List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6378                     .getEphemeralApplicationsLPw(userId);
6379             if (ephemeralApps != null) {
6380                 return new ParceledListSlice<>(ephemeralApps);
6381             }
6382         }
6383         return null;
6384     }
6385
6386     @Override
6387     public boolean isEphemeralApplication(String packageName, int userId) {
6388         enforceCrossUserPermission(Binder.getCallingUid(), userId,
6389                 true /* requireFullPermission */, false /* checkShell */,
6390                 "isEphemeral");
6391         if (DISABLE_EPHEMERAL_APPS) {
6392             return false;
6393         }
6394
6395         if (!isCallerSameApp(packageName)) {
6396             return false;
6397         }
6398         synchronized (mPackages) {
6399             PackageParser.Package pkg = mPackages.get(packageName);
6400             if (pkg != null) {
6401                 return pkg.applicationInfo.isEphemeralApp();
6402             }
6403         }
6404         return false;
6405     }
6406
6407     @Override
6408     public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6409         if (DISABLE_EPHEMERAL_APPS) {
6410             return null;
6411         }
6412
6413         enforceCrossUserPermission(Binder.getCallingUid(), userId,
6414                 true /* requireFullPermission */, false /* checkShell */,
6415                 "getCookie");
6416         if (!isCallerSameApp(packageName)) {
6417             return null;
6418         }
6419         synchronized (mPackages) {
6420             return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6421                     packageName, userId);
6422         }
6423     }
6424
6425     @Override
6426     public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6427         if (DISABLE_EPHEMERAL_APPS) {
6428             return true;
6429         }
6430
6431         enforceCrossUserPermission(Binder.getCallingUid(), userId,
6432                 true /* requireFullPermission */, true /* checkShell */,
6433                 "setCookie");
6434         if (!isCallerSameApp(packageName)) {
6435             return false;
6436         }
6437         synchronized (mPackages) {
6438             return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6439                     packageName, cookie, userId);
6440         }
6441     }
6442
6443     @Override
6444     public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6445         if (DISABLE_EPHEMERAL_APPS) {
6446             return null;
6447         }
6448
6449         mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6450                 "getEphemeralApplicationIcon");
6451         enforceCrossUserPermission(Binder.getCallingUid(), userId,
6452                 true /* requireFullPermission */, false /* checkShell */,
6453                 "getEphemeralApplicationIcon");
6454         synchronized (mPackages) {
6455             return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6456                     packageName, userId);
6457         }
6458     }
6459
6460     private boolean isCallerSameApp(String packageName) {
6461         PackageParser.Package pkg = mPackages.get(packageName);
6462         return pkg != null
6463                 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6464     }
6465
6466     @Override
6467     public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6468         return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6469     }
6470
6471     private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6472         final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6473
6474         // reader
6475         synchronized (mPackages) {
6476             final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6477             final int userId = UserHandle.getCallingUserId();
6478             while (i.hasNext()) {
6479                 final PackageParser.Package p = i.next();
6480                 if (p.applicationInfo == null) continue;
6481
6482                 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6483                         && !p.applicationInfo.isDirectBootAware();
6484                 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6485                         && p.applicationInfo.isDirectBootAware();
6486
6487                 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6488                         && (!mSafeMode || isSystemApp(p))
6489                         && (matchesUnaware || matchesAware)) {
6490                     PackageSetting ps = mSettings.mPackages.get(p.packageName);
6491                     if (ps != null) {
6492                         ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6493                                 ps.readUserState(userId), userId);
6494                         if (ai != null) {
6495                             finalList.add(ai);
6496                         }
6497                     }
6498                 }
6499             }
6500         }
6501
6502         return finalList;
6503     }
6504
6505     @Override
6506     public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6507         if (!sUserManager.exists(userId)) return null;
6508         flags = updateFlagsForComponent(flags, userId, name);
6509         // reader
6510         synchronized (mPackages) {
6511             final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6512             PackageSetting ps = provider != null
6513                     ? mSettings.mPackages.get(provider.owner.packageName)
6514                     : null;
6515             return ps != null
6516                     && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6517                     ? PackageParser.generateProviderInfo(provider, flags,
6518                             ps.readUserState(userId), userId)
6519                     : null;
6520         }
6521     }
6522
6523     /**
6524      * @deprecated
6525      */
6526     @Deprecated
6527     public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6528         // reader
6529         synchronized (mPackages) {
6530             final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6531                     .entrySet().iterator();
6532             final int userId = UserHandle.getCallingUserId();
6533             while (i.hasNext()) {
6534                 Map.Entry<String, PackageParser.Provider> entry = i.next();
6535                 PackageParser.Provider p = entry.getValue();
6536                 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6537
6538                 if (ps != null && p.syncable
6539                         && (!mSafeMode || (p.info.applicationInfo.flags
6540                                 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6541                     ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6542                             ps.readUserState(userId), userId);
6543                     if (info != null) {
6544                         outNames.add(entry.getKey());
6545                         outInfo.add(info);
6546                     }
6547                 }
6548             }
6549         }
6550     }
6551
6552     @Override
6553     public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6554             int uid, int flags) {
6555         final int userId = processName != null ? UserHandle.getUserId(uid)
6556                 : UserHandle.getCallingUserId();
6557         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6558         flags = updateFlagsForComponent(flags, userId, processName);
6559
6560         ArrayList<ProviderInfo> finalList = null;
6561         // reader
6562         synchronized (mPackages) {
6563             final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6564             while (i.hasNext()) {
6565                 final PackageParser.Provider p = i.next();
6566                 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6567                 if (ps != null && p.info.authority != null
6568                         && (processName == null
6569                                 || (p.info.processName.equals(processName)
6570                                         && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6571                         && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6572                     if (finalList == null) {
6573                         finalList = new ArrayList<ProviderInfo>(3);
6574                     }
6575                     ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6576                             ps.readUserState(userId), userId);
6577                     if (info != null) {
6578                         finalList.add(info);
6579                     }
6580                 }
6581             }
6582         }
6583
6584         if (finalList != null) {
6585             Collections.sort(finalList, mProviderInitOrderSorter);
6586             return new ParceledListSlice<ProviderInfo>(finalList);
6587         }
6588
6589         return ParceledListSlice.emptyList();
6590     }
6591
6592     @Override
6593     public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6594         // reader
6595         synchronized (mPackages) {
6596             final PackageParser.Instrumentation i = mInstrumentation.get(name);
6597             return PackageParser.generateInstrumentationInfo(i, flags);
6598         }
6599     }
6600
6601     @Override
6602     public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6603             String targetPackage, int flags) {
6604         return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6605     }
6606
6607     private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6608             int flags) {
6609         ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6610
6611         // reader
6612         synchronized (mPackages) {
6613             final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6614             while (i.hasNext()) {
6615                 final PackageParser.Instrumentation p = i.next();
6616                 if (targetPackage == null
6617                         || targetPackage.equals(p.info.targetPackage)) {
6618                     InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6619                             flags);
6620                     if (ii != null) {
6621                         finalList.add(ii);
6622                     }
6623                 }
6624             }
6625         }
6626
6627         return finalList;
6628     }
6629
6630     private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6631         ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6632         if (overlays == null) {
6633             Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6634             return;
6635         }
6636         for (PackageParser.Package opkg : overlays.values()) {
6637             // Not much to do if idmap fails: we already logged the error
6638             // and we certainly don't want to abort installation of pkg simply
6639             // because an overlay didn't fit properly. For these reasons,
6640             // ignore the return value of createIdmapForPackagePairLI.
6641             createIdmapForPackagePairLI(pkg, opkg);
6642         }
6643     }
6644
6645     private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6646             PackageParser.Package opkg) {
6647         if (!opkg.mTrustedOverlay) {
6648             Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6649                     opkg.baseCodePath + ": overlay not trusted");
6650             return false;
6651         }
6652         ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6653         if (overlaySet == null) {
6654             Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6655                     opkg.baseCodePath + " but target package has no known overlays");
6656             return false;
6657         }
6658         final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6659         // TODO: generate idmap for split APKs
6660         try {
6661             mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6662         } catch (InstallerException e) {
6663             Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6664                     + opkg.baseCodePath);
6665             return false;
6666         }
6667         PackageParser.Package[] overlayArray =
6668             overlaySet.values().toArray(new PackageParser.Package[0]);
6669         Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6670             public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6671                 return p1.mOverlayPriority - p2.mOverlayPriority;
6672             }
6673         };
6674         Arrays.sort(overlayArray, cmp);
6675
6676         pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6677         int i = 0;
6678         for (PackageParser.Package p : overlayArray) {
6679             pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6680         }
6681         return true;
6682     }
6683
6684     private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6685         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6686         try {
6687             scanDirLI(dir, parseFlags, scanFlags, currentTime);
6688         } finally {
6689             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6690         }
6691     }
6692
6693     private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6694         final File[] files = dir.listFiles();
6695         if (ArrayUtils.isEmpty(files)) {
6696             Log.d(TAG, "No files in app dir " + dir);
6697             return;
6698         }
6699
6700         if (DEBUG_PACKAGE_SCANNING) {
6701             Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6702                     + " flags=0x" + Integer.toHexString(parseFlags));
6703         }
6704
6705         for (File file : files) {
6706             final boolean isPackage = (isApkFile(file) || file.isDirectory())
6707                     && !PackageInstallerService.isStageName(file.getName());
6708             if (!isPackage) {
6709                 // Ignore entries which are not packages
6710                 continue;
6711             }
6712             try {
6713                 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6714                         scanFlags, currentTime, null);
6715             } catch (PackageManagerException e) {
6716                 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6717
6718                 // Delete invalid userdata apps
6719                 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6720                         e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6721                     logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6722                     removeCodePathLI(file);
6723                 }
6724             }
6725         }
6726     }
6727
6728     private static File getSettingsProblemFile() {
6729         File dataDir = Environment.getDataDirectory();
6730         File systemDir = new File(dataDir, "system");
6731         File fname = new File(systemDir, "uiderrors.txt");
6732         return fname;
6733     }
6734
6735     static void reportSettingsProblem(int priority, String msg) {
6736         logCriticalInfo(priority, msg);
6737     }
6738
6739     static void logCriticalInfo(int priority, String msg) {
6740         Slog.println(priority, TAG, msg);
6741         EventLogTags.writePmCriticalInfo(msg);
6742         try {
6743             File fname = getSettingsProblemFile();
6744             FileOutputStream out = new FileOutputStream(fname, true);
6745             PrintWriter pw = new FastPrintWriter(out);
6746             SimpleDateFormat formatter = new SimpleDateFormat();
6747             String dateString = formatter.format(new Date(System.currentTimeMillis()));
6748             pw.println(dateString + ": " + msg);
6749             pw.close();
6750             FileUtils.setPermissions(
6751                     fname.toString(),
6752                     FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6753                     -1, -1);
6754         } catch (java.io.IOException e) {
6755         }
6756     }
6757
6758     private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6759             final int policyFlags) throws PackageManagerException {
6760         if (ps != null
6761                 && ps.codePath.equals(srcFile)
6762                 && ps.timeStamp == srcFile.lastModified()
6763                 && !isCompatSignatureUpdateNeeded(pkg)
6764                 && !isRecoverSignatureUpdateNeeded(pkg)) {
6765             long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6766             KeySetManagerService ksms = mSettings.mKeySetManagerService;
6767             ArraySet<PublicKey> signingKs;
6768             synchronized (mPackages) {
6769                 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6770             }
6771             if (ps.signatures.mSignatures != null
6772                     && ps.signatures.mSignatures.length != 0
6773                     && signingKs != null) {
6774                 // Optimization: reuse the existing cached certificates
6775                 // if the package appears to be unchanged.
6776                 pkg.mSignatures = ps.signatures.mSignatures;
6777                 pkg.mSigningKeys = signingKs;
6778                 return;
6779             }
6780
6781             Slog.w(TAG, "PackageSetting for " + ps.name
6782                     + " is missing signatures.  Collecting certs again to recover them.");
6783         } else {
6784             Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6785         }
6786
6787         try {
6788             PackageParser.collectCertificates(pkg, policyFlags);
6789         } catch (PackageParserException e) {
6790             throw PackageManagerException.from(e);
6791         }
6792     }
6793
6794     /**
6795      *  Traces a package scan.
6796      *  @see #scanPackageLI(File, int, int, long, UserHandle)
6797      */
6798     private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6799             int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6800         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6801         try {
6802             return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6803         } finally {
6804             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6805         }
6806     }
6807
6808     /**
6809      *  Scans a package and returns the newly parsed package.
6810      *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6811      */
6812     private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6813             long currentTime, UserHandle user) throws PackageManagerException {
6814         if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6815         PackageParser pp = new PackageParser();
6816         pp.setSeparateProcesses(mSeparateProcesses);
6817         pp.setOnlyCoreApps(mOnlyCore);
6818         pp.setDisplayMetrics(mMetrics);
6819
6820         if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6821             parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6822         }
6823
6824         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6825         final PackageParser.Package pkg;
6826         try {
6827             pkg = pp.parsePackage(scanFile, parseFlags);
6828         } catch (PackageParserException e) {
6829             throw PackageManagerException.from(e);
6830         } finally {
6831             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6832         }
6833
6834         return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6835     }
6836
6837     /**
6838      *  Scans a package and returns the newly parsed package.
6839      *  @throws PackageManagerException on a parse error.
6840      */
6841     private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6842             final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6843             throws PackageManagerException {
6844         // If the package has children and this is the first dive in the function
6845         // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6846         // packages (parent and children) would be successfully scanned before the
6847         // actual scan since scanning mutates internal state and we want to atomically
6848         // install the package and its children.
6849         if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6850             if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6851                 scanFlags |= SCAN_CHECK_ONLY;
6852             }
6853         } else {
6854             scanFlags &= ~SCAN_CHECK_ONLY;
6855         }
6856
6857         // Scan the parent
6858         PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6859                 scanFlags, currentTime, user);
6860
6861         // Scan the children
6862         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6863         for (int i = 0; i < childCount; i++) {
6864             PackageParser.Package childPackage = pkg.childPackages.get(i);
6865             scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6866                     currentTime, user);
6867         }
6868
6869
6870         if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6871             return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6872         }
6873
6874         return scannedPkg;
6875     }
6876
6877     /**
6878      *  Scans a package and returns the newly parsed package.
6879      *  @throws PackageManagerException on a parse error.
6880      */
6881     private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6882             int policyFlags, int scanFlags, long currentTime, UserHandle user)
6883             throws PackageManagerException {
6884         PackageSetting ps = null;
6885         PackageSetting updatedPkg;
6886         // reader
6887         synchronized (mPackages) {
6888             // Look to see if we already know about this package.
6889             String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6890             if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6891                 // This package has been renamed to its original name.  Let's
6892                 // use that.
6893                 ps = mSettings.peekPackageLPr(oldName);
6894             }
6895             // If there was no original package, see one for the real package name.
6896             if (ps == null) {
6897                 ps = mSettings.peekPackageLPr(pkg.packageName);
6898             }
6899             // Check to see if this package could be hiding/updating a system
6900             // package.  Must look for it either under the original or real
6901             // package name depending on our state.
6902             updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6903             if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6904
6905             // If this is a package we don't know about on the system partition, we
6906             // may need to remove disabled child packages on the system partition
6907             // or may need to not add child packages if the parent apk is updated
6908             // on the data partition and no longer defines this child package.
6909             if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6910                 // If this is a parent package for an updated system app and this system
6911                 // app got an OTA update which no longer defines some of the child packages
6912                 // we have to prune them from the disabled system packages.
6913                 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6914                 if (disabledPs != null) {
6915                     final int scannedChildCount = (pkg.childPackages != null)
6916                             ? pkg.childPackages.size() : 0;
6917                     final int disabledChildCount = disabledPs.childPackageNames != null
6918                             ? disabledPs.childPackageNames.size() : 0;
6919                     for (int i = 0; i < disabledChildCount; i++) {
6920                         String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6921                         boolean disabledPackageAvailable = false;
6922                         for (int j = 0; j < scannedChildCount; j++) {
6923                             PackageParser.Package childPkg = pkg.childPackages.get(j);
6924                             if (childPkg.packageName.equals(disabledChildPackageName)) {
6925                                 disabledPackageAvailable = true;
6926                                 break;
6927                             }
6928                          }
6929                          if (!disabledPackageAvailable) {
6930                              mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6931                          }
6932                     }
6933                 }
6934             }
6935         }
6936
6937         boolean updatedPkgBetter = false;
6938         // First check if this is a system package that may involve an update
6939         if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6940             // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6941             // it needs to drop FLAG_PRIVILEGED.
6942             if (locationIsPrivileged(scanFile)) {
6943                 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6944             } else {
6945                 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6946             }
6947
6948             if (ps != null && !ps.codePath.equals(scanFile)) {
6949                 // The path has changed from what was last scanned...  check the
6950                 // version of the new path against what we have stored to determine
6951                 // what to do.
6952                 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6953                 if (pkg.mVersionCode <= ps.versionCode) {
6954                     // The system package has been updated and the code path does not match
6955                     // Ignore entry. Skip it.
6956                     if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6957                             + " ignored: updated version " + ps.versionCode
6958                             + " better than this " + pkg.mVersionCode);
6959                     if (!updatedPkg.codePath.equals(scanFile)) {
6960                         Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6961                                 + ps.name + " changing from " + updatedPkg.codePathString
6962                                 + " to " + scanFile);
6963                         updatedPkg.codePath = scanFile;
6964                         updatedPkg.codePathString = scanFile.toString();
6965                         updatedPkg.resourcePath = scanFile;
6966                         updatedPkg.resourcePathString = scanFile.toString();
6967                     }
6968                     updatedPkg.pkg = pkg;
6969                     updatedPkg.versionCode = pkg.mVersionCode;
6970
6971                     // Update the disabled system child packages to point to the package too.
6972                     final int childCount = updatedPkg.childPackageNames != null
6973                             ? updatedPkg.childPackageNames.size() : 0;
6974                     for (int i = 0; i < childCount; i++) {
6975                         String childPackageName = updatedPkg.childPackageNames.get(i);
6976                         PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6977                                 childPackageName);
6978                         if (updatedChildPkg != null) {
6979                             updatedChildPkg.pkg = pkg;
6980                             updatedChildPkg.versionCode = pkg.mVersionCode;
6981                         }
6982                     }
6983
6984                     throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6985                             + scanFile + " ignored: updated version " + ps.versionCode
6986                             + " better than this " + pkg.mVersionCode);
6987                 } else {
6988                     // The current app on the system partition is better than
6989                     // what we have updated to on the data partition; switch
6990                     // back to the system partition version.
6991                     // At this point, its safely assumed that package installation for
6992                     // apps in system partition will go through. If not there won't be a working
6993                     // version of the app
6994                     // writer
6995                     synchronized (mPackages) {
6996                         // Just remove the loaded entries from package lists.
6997                         mPackages.remove(ps.name);
6998                     }
6999
7000                     logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7001                             + " reverting from " + ps.codePathString
7002                             + ": new version " + pkg.mVersionCode
7003                             + " better than installed " + ps.versionCode);
7004
7005                     InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7006                             ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7007                     synchronized (mInstallLock) {
7008                         args.cleanUpResourcesLI();
7009                     }
7010                     synchronized (mPackages) {
7011                         mSettings.enableSystemPackageLPw(ps.name);
7012                     }
7013                     updatedPkgBetter = true;
7014                 }
7015             }
7016         }
7017
7018         if (updatedPkg != null) {
7019             // An updated system app will not have the PARSE_IS_SYSTEM flag set
7020             // initially
7021             policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7022
7023             // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7024             // flag set initially
7025             if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7026                 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7027             }
7028         }
7029
7030         // Verify certificates against what was last scanned
7031         collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7032
7033         /*
7034          * A new system app appeared, but we already had a non-system one of the
7035          * same name installed earlier.
7036          */
7037         boolean shouldHideSystemApp = false;
7038         if (updatedPkg == null && ps != null
7039                 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7040             /*
7041              * Check to make sure the signatures match first. If they don't,
7042              * wipe the installed application and its data.
7043              */
7044             if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7045                     != PackageManager.SIGNATURE_MATCH) {
7046                 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7047                         + " signatures don't match existing userdata copy; removing");
7048                 try (PackageFreezer freezer = freezePackage(pkg.packageName,
7049                         "scanPackageInternalLI")) {
7050                     deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7051                 }
7052                 ps = null;
7053             } else {
7054                 /*
7055                  * If the newly-added system app is an older version than the
7056                  * already installed version, hide it. It will be scanned later
7057                  * and re-added like an update.
7058                  */
7059                 if (pkg.mVersionCode <= ps.versionCode) {
7060                     shouldHideSystemApp = true;
7061                     logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7062                             + " but new version " + pkg.mVersionCode + " better than installed "
7063                             + ps.versionCode + "; hiding system");
7064                 } else {
7065                     /*
7066                      * The newly found system app is a newer version that the
7067                      * one previously installed. Simply remove the
7068                      * already-installed application and replace it with our own
7069                      * while keeping the application data.
7070                      */
7071                     logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7072                             + " reverting from " + ps.codePathString + ": new version "
7073                             + pkg.mVersionCode + " better than installed " + ps.versionCode);
7074                     InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7075                             ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7076                     synchronized (mInstallLock) {
7077                         args.cleanUpResourcesLI();
7078                     }
7079                 }
7080             }
7081         }
7082
7083         // The apk is forward locked (not public) if its code and resources
7084         // are kept in different files. (except for app in either system or
7085         // vendor path).
7086         // TODO grab this value from PackageSettings
7087         if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7088             if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7089                 policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7090             }
7091         }
7092
7093         // TODO: extend to support forward-locked splits
7094         String resourcePath = null;
7095         String baseResourcePath = null;
7096         if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7097             if (ps != null && ps.resourcePathString != null) {
7098                 resourcePath = ps.resourcePathString;
7099                 baseResourcePath = ps.resourcePathString;
7100             } else {
7101                 // Should not happen at all. Just log an error.
7102                 Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7103             }
7104         } else {
7105             resourcePath = pkg.codePath;
7106             baseResourcePath = pkg.baseCodePath;
7107         }
7108
7109         // Set application objects path explicitly.
7110         pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7111         pkg.setApplicationInfoCodePath(pkg.codePath);
7112         pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7113         pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7114         pkg.setApplicationInfoResourcePath(resourcePath);
7115         pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7116         pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7117
7118         // Note that we invoke the following method only if we are about to unpack an application
7119         PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7120                 | SCAN_UPDATE_SIGNATURE, currentTime, user);
7121
7122         /*
7123          * If the system app should be overridden by a previously installed
7124          * data, hide the system app now and let the /data/app scan pick it up
7125          * again.
7126          */
7127         if (shouldHideSystemApp) {
7128             synchronized (mPackages) {
7129                 mSettings.disableSystemPackageLPw(pkg.packageName, true);
7130             }
7131         }
7132
7133         return scannedPkg;
7134     }
7135
7136     private static String fixProcessName(String defProcessName,
7137             String processName, int uid) {
7138         if (processName == null) {
7139             return defProcessName;
7140         }
7141         return processName;
7142     }
7143
7144     private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7145             throws PackageManagerException {
7146         if (pkgSetting.signatures.mSignatures != null) {
7147             // Already existing package. Make sure signatures match
7148             boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7149                     == PackageManager.SIGNATURE_MATCH;
7150             if (!match) {
7151                 match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7152                         == PackageManager.SIGNATURE_MATCH;
7153             }
7154             if (!match) {
7155                 match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7156                         == PackageManager.SIGNATURE_MATCH;
7157             }
7158             if (!match) {
7159                 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7160                         + pkg.packageName + " signatures do not match the "
7161                         + "previously installed version; ignoring!");
7162             }
7163         }
7164
7165         // Check for shared user signatures
7166         if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7167             // Already existing package. Make sure signatures match
7168             boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7169                     pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7170             if (!match) {
7171                 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7172                         == PackageManager.SIGNATURE_MATCH;
7173             }
7174             if (!match) {
7175                 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7176                         == PackageManager.SIGNATURE_MATCH;
7177             }
7178             if (!match) {
7179                 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7180                         "Package " + pkg.packageName
7181                         + " has no signatures that match those in shared user "
7182                         + pkgSetting.sharedUser.name + "; ignoring!");
7183             }
7184         }
7185     }
7186
7187     /**
7188      * Enforces that only the system UID or root's UID can call a method exposed
7189      * via Binder.
7190      *
7191      * @param message used as message if SecurityException is thrown
7192      * @throws SecurityException if the caller is not system or root
7193      */
7194     private static final void enforceSystemOrRoot(String message) {
7195         final int uid = Binder.getCallingUid();
7196         if (uid != Process.SYSTEM_UID && uid != 0) {
7197             throw new SecurityException(message);
7198         }
7199     }
7200
7201     @Override
7202     public void performFstrimIfNeeded() {
7203         enforceSystemOrRoot("Only the system can request fstrim");
7204
7205         // Before everything else, see whether we need to fstrim.
7206         try {
7207             IMountService ms = PackageHelper.getMountService();
7208             if (ms != null) {
7209                 final boolean isUpgrade = isUpgrade();
7210                 boolean doTrim = isUpgrade;
7211                 if (doTrim) {
7212                     Slog.w(TAG, "Running disk maintenance immediately due to system update");
7213                 } else {
7214                     final long interval = android.provider.Settings.Global.getLong(
7215                             mContext.getContentResolver(),
7216                             android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7217                             DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7218                     if (interval > 0) {
7219                         final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7220                         if (timeSinceLast > interval) {
7221                             doTrim = true;
7222                             Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7223                                     + "; running immediately");
7224                         }
7225                     }
7226                 }
7227                 if (doTrim) {
7228                     if (!isFirstBoot()) {
7229                         try {
7230                             ActivityManagerNative.getDefault().showBootMessage(
7231                                     mContext.getResources().getString(
7232                                             R.string.android_upgrading_fstrim), true);
7233                         } catch (RemoteException e) {
7234                         }
7235                     }
7236                     ms.runMaintenance();
7237                 }
7238             } else {
7239                 Slog.e(TAG, "Mount service unavailable!");
7240             }
7241         } catch (RemoteException e) {
7242             // Can't happen; MountService is local
7243         }
7244     }
7245
7246     @Override
7247     public void updatePackagesIfNeeded() {
7248         enforceSystemOrRoot("Only the system can request package update");
7249
7250         // We need to re-extract after an OTA.
7251         boolean causeUpgrade = isUpgrade();
7252
7253         // First boot or factory reset.
7254         // Note: we also handle devices that are upgrading to N right now as if it is their
7255         //       first boot, as they do not have profile data.
7256         boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7257
7258         // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7259         boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7260
7261         if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7262             return;
7263         }
7264
7265         List<PackageParser.Package> pkgs;
7266         synchronized (mPackages) {
7267             pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7268         }
7269
7270         final long startTime = System.nanoTime();
7271         final int[] stats = performDexOpt(pkgs, mIsPreNUpgrade /* showDialog */,
7272                     getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7273
7274         final int elapsedTimeSeconds =
7275                 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7276
7277         MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7278         MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7279         MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7280         MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7281         MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7282     }
7283
7284     /**
7285      * Performs dexopt on the set of packages in {@code packages} and returns an int array
7286      * containing statistics about the invocation. The array consists of three elements,
7287      * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7288      * and {@code numberOfPackagesFailed}.
7289      */
7290     private int[] performDexOpt(List<PackageParser.Package> pkgs, boolean showDialog,
7291             String compilerFilter) {
7292
7293         int numberOfPackagesVisited = 0;
7294         int numberOfPackagesOptimized = 0;
7295         int numberOfPackagesSkipped = 0;
7296         int numberOfPackagesFailed = 0;
7297         final int numberOfPackagesToDexopt = pkgs.size();
7298
7299         for (PackageParser.Package pkg : pkgs) {
7300             numberOfPackagesVisited++;
7301
7302             if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7303                 if (DEBUG_DEXOPT) {
7304                     Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7305                 }
7306                 numberOfPackagesSkipped++;
7307                 continue;
7308             }
7309
7310             if (DEBUG_DEXOPT) {
7311                 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7312                         numberOfPackagesToDexopt + ": " + pkg.packageName);
7313             }
7314
7315             if (showDialog) {
7316                 try {
7317                     ActivityManagerNative.getDefault().showBootMessage(
7318                             mContext.getResources().getString(R.string.android_upgrading_apk,
7319                                     numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7320                 } catch (RemoteException e) {
7321                 }
7322             }
7323
7324             // checkProfiles is false to avoid merging profiles during boot which
7325             // might interfere with background compilation (b/28612421).
7326             // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7327             // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7328             // trade-off worth doing to save boot time work.
7329             int dexOptStatus = performDexOptTraced(pkg.packageName,
7330                     false /* checkProfiles */,
7331                     compilerFilter,
7332                     false /* force */);
7333             switch (dexOptStatus) {
7334                 case PackageDexOptimizer.DEX_OPT_PERFORMED:
7335                     numberOfPackagesOptimized++;
7336                     break;
7337                 case PackageDexOptimizer.DEX_OPT_SKIPPED:
7338                     numberOfPackagesSkipped++;
7339                     break;
7340                 case PackageDexOptimizer.DEX_OPT_FAILED:
7341                     numberOfPackagesFailed++;
7342                     break;
7343                 default:
7344                     Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7345                     break;
7346             }
7347         }
7348
7349         return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7350                 numberOfPackagesFailed };
7351     }
7352
7353     @Override
7354     public void notifyPackageUse(String packageName, int reason) {
7355         synchronized (mPackages) {
7356             PackageParser.Package p = mPackages.get(packageName);
7357             if (p == null) {
7358                 return;
7359             }
7360             p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7361         }
7362     }
7363
7364     // TODO: this is not used nor needed. Delete it.
7365     @Override
7366     public boolean performDexOptIfNeeded(String packageName) {
7367         int dexOptStatus = performDexOptTraced(packageName,
7368                 false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7369         return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7370     }
7371
7372     @Override
7373     public boolean performDexOpt(String packageName,
7374             boolean checkProfiles, int compileReason, boolean force) {
7375         int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7376                 getCompilerFilterForReason(compileReason), force);
7377         return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7378     }
7379
7380     @Override
7381     public boolean performDexOptMode(String packageName,
7382             boolean checkProfiles, String targetCompilerFilter, boolean force) {
7383         int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7384                 targetCompilerFilter, force);
7385         return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7386     }
7387
7388     private int performDexOptTraced(String packageName,
7389                 boolean checkProfiles, String targetCompilerFilter, boolean force) {
7390         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7391         try {
7392             return performDexOptInternal(packageName, checkProfiles,
7393                     targetCompilerFilter, force);
7394         } finally {
7395             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7396         }
7397     }
7398
7399     // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7400     // if the package can now be considered up to date for the given filter.
7401     private int performDexOptInternal(String packageName,
7402                 boolean checkProfiles, String targetCompilerFilter, boolean force) {
7403         PackageParser.Package p;
7404         synchronized (mPackages) {
7405             p = mPackages.get(packageName);
7406             if (p == null) {
7407                 // Package could not be found. Report failure.
7408                 return PackageDexOptimizer.DEX_OPT_FAILED;
7409             }
7410             mPackageUsage.write(false);
7411         }
7412         long callingId = Binder.clearCallingIdentity();
7413         try {
7414             synchronized (mInstallLock) {
7415                 return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7416                         targetCompilerFilter, force);
7417             }
7418         } finally {
7419             Binder.restoreCallingIdentity(callingId);
7420         }
7421     }
7422
7423     public ArraySet<String> getOptimizablePackages() {
7424         ArraySet<String> pkgs = new ArraySet<String>();
7425         synchronized (mPackages) {
7426             for (PackageParser.Package p : mPackages.values()) {
7427                 if (PackageDexOptimizer.canOptimizePackage(p)) {
7428                     pkgs.add(p.packageName);
7429                 }
7430             }
7431         }
7432         return pkgs;
7433     }
7434
7435     private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7436             boolean checkProfiles, String targetCompilerFilter,
7437             boolean force) {
7438         // Select the dex optimizer based on the force parameter.
7439         // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7440         //       allocate an object here.
7441         PackageDexOptimizer pdo = force
7442                 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7443                 : mPackageDexOptimizer;
7444
7445         // Optimize all dependencies first. Note: we ignore the return value and march on
7446         // on errors.
7447         Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7448         final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7449         if (!deps.isEmpty()) {
7450             for (PackageParser.Package depPackage : deps) {
7451                 // TODO: Analyze and investigate if we (should) profile libraries.
7452                 // Currently this will do a full compilation of the library by default.
7453                 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7454                         false /* checkProfiles */,
7455                         getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7456             }
7457         }
7458         return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7459                 targetCompilerFilter);
7460     }
7461
7462     Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7463         if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7464             ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7465             Set<String> collectedNames = new HashSet<>();
7466             findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7467
7468             retValue.remove(p);
7469
7470             return retValue;
7471         } else {
7472             return Collections.emptyList();
7473         }
7474     }
7475
7476     private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7477             Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7478         if (!collectedNames.contains(p.packageName)) {
7479             collectedNames.add(p.packageName);
7480             collected.add(p);
7481
7482             if (p.usesLibraries != null) {
7483                 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7484             }
7485             if (p.usesOptionalLibraries != null) {
7486                 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7487                         collectedNames);
7488             }
7489         }
7490     }
7491
7492     private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7493             Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7494         for (String libName : libs) {
7495             PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7496             if (libPkg != null) {
7497                 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7498             }
7499         }
7500     }
7501
7502     private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7503         synchronized (mPackages) {
7504             PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7505             if (lib != null && lib.apk != null) {
7506                 return mPackages.get(lib.apk);
7507             }
7508         }
7509         return null;
7510     }
7511
7512     public void shutdown() {
7513         mPackageUsage.write(true);
7514     }
7515
7516     @Override
7517     public void dumpProfiles(String packageName) {
7518         PackageParser.Package pkg;
7519         synchronized (mPackages) {
7520             pkg = mPackages.get(packageName);
7521             if (pkg == null) {
7522                 throw new IllegalArgumentException("Unknown package: " + packageName);
7523             }
7524         }
7525         /* Only the shell, root, or the app user should be able to dump profiles. */
7526         int callingUid = Binder.getCallingUid();
7527         if (callingUid != Process.SHELL_UID &&
7528             callingUid != Process.ROOT_UID &&
7529             callingUid != pkg.applicationInfo.uid) {
7530             throw new SecurityException("dumpProfiles");
7531         }
7532
7533         synchronized (mInstallLock) {
7534             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7535             final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7536             try {
7537                 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7538                 String gid = Integer.toString(sharedGid);
7539                 String codePaths = TextUtils.join(";", allCodePaths);
7540                 mInstaller.dumpProfiles(gid, packageName, codePaths);
7541             } catch (InstallerException e) {
7542                 Slog.w(TAG, "Failed to dump profiles", e);
7543             }
7544             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7545         }
7546     }
7547
7548     @Override
7549     public void forceDexOpt(String packageName) {
7550         enforceSystemOrRoot("forceDexOpt");
7551
7552         PackageParser.Package pkg;
7553         synchronized (mPackages) {
7554             pkg = mPackages.get(packageName);
7555             if (pkg == null) {
7556                 throw new IllegalArgumentException("Unknown package: " + packageName);
7557             }
7558         }
7559
7560         synchronized (mInstallLock) {
7561             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7562
7563             // Whoever is calling forceDexOpt wants a fully compiled package.
7564             // Don't use profiles since that may cause compilation to be skipped.
7565             final int res = performDexOptInternalWithDependenciesLI(pkg,
7566                     false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7567                     true /* force */);
7568
7569             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7570             if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7571                 throw new IllegalStateException("Failed to dexopt: " + res);
7572             }
7573         }
7574     }
7575
7576     private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7577         if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7578             Slog.w(TAG, "Unable to update from " + oldPkg.name
7579                     + " to " + newPkg.packageName
7580                     + ": old package not in system partition");
7581             return false;
7582         } else if (mPackages.get(oldPkg.name) != null) {
7583             Slog.w(TAG, "Unable to update from " + oldPkg.name
7584                     + " to " + newPkg.packageName
7585                     + ": old package still exists");
7586             return false;
7587         }
7588         return true;
7589     }
7590
7591     void removeCodePathLI(File codePath) {
7592         if (codePath.isDirectory()) {
7593             try {
7594                 mInstaller.rmPackageDir(codePath.getAbsolutePath());
7595             } catch (InstallerException e) {
7596                 Slog.w(TAG, "Failed to remove code path", e);
7597             }
7598         } else {
7599             codePath.delete();
7600         }
7601     }
7602
7603     private int[] resolveUserIds(int userId) {
7604         return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7605     }
7606
7607     private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7608         if (pkg == null) {
7609             Slog.wtf(TAG, "Package was null!", new Throwable());
7610             return;
7611         }
7612         clearAppDataLeafLIF(pkg, userId, flags);
7613         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7614         for (int i = 0; i < childCount; i++) {
7615             clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7616         }
7617     }
7618
7619     private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7620         final PackageSetting ps;
7621         synchronized (mPackages) {
7622             ps = mSettings.mPackages.get(pkg.packageName);
7623         }
7624         for (int realUserId : resolveUserIds(userId)) {
7625             final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7626             try {
7627                 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7628                         ceDataInode);
7629             } catch (InstallerException e) {
7630                 Slog.w(TAG, String.valueOf(e));
7631             }
7632         }
7633     }
7634
7635     private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7636         if (pkg == null) {
7637             Slog.wtf(TAG, "Package was null!", new Throwable());
7638             return;
7639         }
7640         destroyAppDataLeafLIF(pkg, userId, flags);
7641         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7642         for (int i = 0; i < childCount; i++) {
7643             destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7644         }
7645     }
7646
7647     private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7648         final PackageSetting ps;
7649         synchronized (mPackages) {
7650             ps = mSettings.mPackages.get(pkg.packageName);
7651         }
7652         for (int realUserId : resolveUserIds(userId)) {
7653             final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7654             try {
7655                 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7656                         ceDataInode);
7657             } catch (InstallerException e) {
7658                 Slog.w(TAG, String.valueOf(e));
7659             }
7660         }
7661     }
7662
7663     private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7664         if (pkg == null) {
7665             Slog.wtf(TAG, "Package was null!", new Throwable());
7666             return;
7667         }
7668         destroyAppProfilesLeafLIF(pkg);
7669         destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7670         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7671         for (int i = 0; i < childCount; i++) {
7672             destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7673             destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7674                     true /* removeBaseMarker */);
7675         }
7676     }
7677
7678     private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7679             boolean removeBaseMarker) {
7680         if (pkg.isForwardLocked()) {
7681             return;
7682         }
7683
7684         for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7685             try {
7686                 path = PackageManagerServiceUtils.realpath(new File(path));
7687             } catch (IOException e) {
7688                 // TODO: Should we return early here ?
7689                 Slog.w(TAG, "Failed to get canonical path", e);
7690                 continue;
7691             }
7692
7693             final String useMarker = path.replace('/', '@');
7694             for (int realUserId : resolveUserIds(userId)) {
7695                 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7696                 if (removeBaseMarker) {
7697                     File foreignUseMark = new File(profileDir, useMarker);
7698                     if (foreignUseMark.exists()) {
7699                         if (!foreignUseMark.delete()) {
7700                             Slog.w(TAG, "Unable to delete foreign user mark for package: "
7701                                     + pkg.packageName);
7702                         }
7703                     }
7704                 }
7705
7706                 File[] markers = profileDir.listFiles();
7707                 if (markers != null) {
7708                     final String searchString = "@" + pkg.packageName + "@";
7709                     // We also delete all markers that contain the package name we're
7710                     // uninstalling. These are associated with secondary dex-files belonging
7711                     // to the package. Reconstructing the path of these dex files is messy
7712                     // in general.
7713                     for (File marker : markers) {
7714                         if (marker.getName().indexOf(searchString) > 0) {
7715                             if (!marker.delete()) {
7716                                 Slog.w(TAG, "Unable to delete foreign user mark for package: "
7717                                     + pkg.packageName);
7718                             }
7719                         }
7720                     }
7721                 }
7722             }
7723         }
7724     }
7725
7726     private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7727         try {
7728             mInstaller.destroyAppProfiles(pkg.packageName);
7729         } catch (InstallerException e) {
7730             Slog.w(TAG, String.valueOf(e));
7731         }
7732     }
7733
7734     private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7735         if (pkg == null) {
7736             Slog.wtf(TAG, "Package was null!", new Throwable());
7737             return;
7738         }
7739         clearAppProfilesLeafLIF(pkg);
7740         // We don't remove the base foreign use marker when clearing profiles because
7741         // we will rename it when the app is updated. Unlike the actual profile contents,
7742         // the foreign use marker is good across installs.
7743         destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7744         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7745         for (int i = 0; i < childCount; i++) {
7746             clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7747         }
7748     }
7749
7750     private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7751         try {
7752             mInstaller.clearAppProfiles(pkg.packageName);
7753         } catch (InstallerException e) {
7754             Slog.w(TAG, String.valueOf(e));
7755         }
7756     }
7757
7758     private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7759             long lastUpdateTime) {
7760         // Set parent install/update time
7761         PackageSetting ps = (PackageSetting) pkg.mExtras;
7762         if (ps != null) {
7763             ps.firstInstallTime = firstInstallTime;
7764             ps.lastUpdateTime = lastUpdateTime;
7765         }
7766         // Set children install/update time
7767         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7768         for (int i = 0; i < childCount; i++) {
7769             PackageParser.Package childPkg = pkg.childPackages.get(i);
7770             ps = (PackageSetting) childPkg.mExtras;
7771             if (ps != null) {
7772                 ps.firstInstallTime = firstInstallTime;
7773                 ps.lastUpdateTime = lastUpdateTime;
7774             }
7775         }
7776     }
7777
7778     private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7779             PackageParser.Package changingLib) {
7780         if (file.path != null) {
7781             usesLibraryFiles.add(file.path);
7782             return;
7783         }
7784         PackageParser.Package p = mPackages.get(file.apk);
7785         if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7786             // If we are doing this while in the middle of updating a library apk,
7787             // then we need to make sure to use that new apk for determining the
7788             // dependencies here.  (We haven't yet finished committing the new apk
7789             // to the package manager state.)
7790             if (p == null || p.packageName.equals(changingLib.packageName)) {
7791                 p = changingLib;
7792             }
7793         }
7794         if (p != null) {
7795             usesLibraryFiles.addAll(p.getAllCodePaths());
7796         }
7797     }
7798
7799     private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7800             PackageParser.Package changingLib) throws PackageManagerException {
7801         if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7802             final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7803             int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7804             for (int i=0; i<N; i++) {
7805                 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7806                 if (file == null) {
7807                     throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7808                             "Package " + pkg.packageName + " requires unavailable shared library "
7809                             + pkg.usesLibraries.get(i) + "; failing!");
7810                 }
7811                 addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7812             }
7813             N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7814             for (int i=0; i<N; i++) {
7815                 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7816                 if (file == null) {
7817                     Slog.w(TAG, "Package " + pkg.packageName
7818                             + " desires unavailable shared library "
7819                             + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7820                 } else {
7821                     addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7822                 }
7823             }
7824             N = usesLibraryFiles.size();
7825             if (N > 0) {
7826                 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7827             } else {
7828                 pkg.usesLibraryFiles = null;
7829             }
7830         }
7831     }
7832
7833     private static boolean hasString(List<String> list, List<String> which) {
7834         if (list == null) {
7835             return false;
7836         }
7837         for (int i=list.size()-1; i>=0; i--) {
7838             for (int j=which.size()-1; j>=0; j--) {
7839                 if (which.get(j).equals(list.get(i))) {
7840                     return true;
7841                 }
7842             }
7843         }
7844         return false;
7845     }
7846
7847     private void updateAllSharedLibrariesLPw() {
7848         for (PackageParser.Package pkg : mPackages.values()) {
7849             try {
7850                 updateSharedLibrariesLPw(pkg, null);
7851             } catch (PackageManagerException e) {
7852                 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7853             }
7854         }
7855     }
7856
7857     private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7858             PackageParser.Package changingPkg) {
7859         ArrayList<PackageParser.Package> res = null;
7860         for (PackageParser.Package pkg : mPackages.values()) {
7861             if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7862                     || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7863                 if (res == null) {
7864                     res = new ArrayList<PackageParser.Package>();
7865                 }
7866                 res.add(pkg);
7867                 try {
7868                     updateSharedLibrariesLPw(pkg, changingPkg);
7869                 } catch (PackageManagerException e) {
7870                     Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7871                 }
7872             }
7873         }
7874         return res;
7875     }
7876
7877     /**
7878      * Derive the value of the {@code cpuAbiOverride} based on the provided
7879      * value and an optional stored value from the package settings.
7880      */
7881     private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7882         String cpuAbiOverride = null;
7883
7884         if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7885             cpuAbiOverride = null;
7886         } else if (abiOverride != null) {
7887             cpuAbiOverride = abiOverride;
7888         } else if (settings != null) {
7889             cpuAbiOverride = settings.cpuAbiOverrideString;
7890         }
7891
7892         return cpuAbiOverride;
7893     }
7894
7895     private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7896             final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7897                     throws PackageManagerException {
7898         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7899         // If the package has children and this is the first dive in the function
7900         // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7901         // whether all packages (parent and children) would be successfully scanned
7902         // before the actual scan since scanning mutates internal state and we want
7903         // to atomically install the package and its children.
7904         if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7905             if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7906                 scanFlags |= SCAN_CHECK_ONLY;
7907             }
7908         } else {
7909             scanFlags &= ~SCAN_CHECK_ONLY;
7910         }
7911
7912         final PackageParser.Package scannedPkg;
7913         try {
7914             // Scan the parent
7915             scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7916             // Scan the children
7917             final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7918             for (int i = 0; i < childCount; i++) {
7919                 PackageParser.Package childPkg = pkg.childPackages.get(i);
7920                 scanPackageLI(childPkg, policyFlags,
7921                         scanFlags, currentTime, user);
7922             }
7923         } finally {
7924             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7925         }
7926
7927         if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7928             return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7929         }
7930
7931         return scannedPkg;
7932     }
7933
7934     private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7935             int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7936         boolean success = false;
7937         try {
7938             final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7939                     currentTime, user);
7940             success = true;
7941             return res;
7942         } finally {
7943             if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7944                 // DELETE_DATA_ON_FAILURES is only used by frozen paths
7945                 destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7946                         StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7947                 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7948             }
7949         }
7950     }
7951
7952     /**
7953      * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7954      */
7955     private static boolean apkHasCode(String fileName) {
7956         StrictJarFile jarFile = null;
7957         try {
7958             jarFile = new StrictJarFile(fileName,
7959                     false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7960             return jarFile.findEntry("classes.dex") != null;
7961         } catch (IOException ignore) {
7962         } finally {
7963             try {
7964                 jarFile.close();
7965             } catch (IOException ignore) {}
7966         }
7967         return false;
7968     }
7969
7970     /**
7971      * Enforces code policy for the package. This ensures that if an APK has
7972      * declared hasCode="true" in its manifest that the APK actually contains
7973      * code.
7974      *
7975      * @throws PackageManagerException If bytecode could not be found when it should exist
7976      */
7977     private static void enforceCodePolicy(PackageParser.Package pkg)
7978             throws PackageManagerException {
7979         final boolean shouldHaveCode =
7980                 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7981         if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7982             throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7983                     "Package " + pkg.baseCodePath + " code is missing");
7984         }
7985
7986         if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7987             for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7988                 final boolean splitShouldHaveCode =
7989                         (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7990                 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7991                     throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7992                             "Package " + pkg.splitCodePaths[i] + " code is missing");
7993                 }
7994             }
7995         }
7996     }
7997
7998     private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7999             final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8000             throws PackageManagerException {
8001         final File scanFile = new File(pkg.codePath);
8002         if (pkg.applicationInfo.getCodePath() == null ||
8003                 pkg.applicationInfo.getResourcePath() == null) {
8004             // Bail out. The resource and code paths haven't been set.
8005             throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8006                     "Code and resource paths haven't been set correctly");
8007         }
8008
8009         // Apply policy
8010         if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8011             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8012             if (pkg.applicationInfo.isDirectBootAware()) {
8013                 // we're direct boot aware; set for all components
8014                 for (PackageParser.Service s : pkg.services) {
8015                     s.info.encryptionAware = s.info.directBootAware = true;
8016                 }
8017                 for (PackageParser.Provider p : pkg.providers) {
8018                     p.info.encryptionAware = p.info.directBootAware = true;
8019                 }
8020                 for (PackageParser.Activity a : pkg.activities) {
8021                     a.info.encryptionAware = a.info.directBootAware = true;
8022                 }
8023                 for (PackageParser.Activity r : pkg.receivers) {
8024                     r.info.encryptionAware = r.info.directBootAware = true;
8025                 }
8026             }
8027         } else {
8028             // Only allow system apps to be flagged as core apps.
8029             pkg.coreApp = false;
8030             // clear flags not applicable to regular apps
8031             pkg.applicationInfo.privateFlags &=
8032                     ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8033             pkg.applicationInfo.privateFlags &=
8034                     ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8035         }
8036         pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8037
8038         if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8039             pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8040         }
8041
8042         if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8043             enforceCodePolicy(pkg);
8044         }
8045
8046         if (mCustomResolverComponentName != null &&
8047                 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8048             setUpCustomResolverActivity(pkg);
8049         }
8050
8051         if (pkg.packageName.equals("android")) {
8052             synchronized (mPackages) {
8053                 if (mAndroidApplication != null) {
8054                     Slog.w(TAG, "*************************************************");
8055                     Slog.w(TAG, "Core android package being redefined.  Skipping.");
8056                     Slog.w(TAG, " file=" + scanFile);
8057                     Slog.w(TAG, "*************************************************");
8058                     throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8059                             "Core android package being redefined.  Skipping.");
8060                 }
8061
8062                 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8063                     // Set up information for our fall-back user intent resolution activity.
8064                     mPlatformPackage = pkg;
8065                     pkg.mVersionCode = mSdkVersion;
8066                     mAndroidApplication = pkg.applicationInfo;
8067
8068                     if (!mResolverReplaced) {
8069                         mResolveActivity.applicationInfo = mAndroidApplication;
8070                         mResolveActivity.name = ResolverActivity.class.getName();
8071                         mResolveActivity.packageName = mAndroidApplication.packageName;
8072                         mResolveActivity.processName = "system:ui";
8073                         mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8074                         mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8075                         mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8076                         mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8077                         mResolveActivity.exported = true;
8078                         mResolveActivity.enabled = true;
8079                         mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8080                         mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8081                                 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8082                                 | ActivityInfo.CONFIG_SCREEN_LAYOUT
8083                                 | ActivityInfo.CONFIG_ORIENTATION
8084                                 | ActivityInfo.CONFIG_KEYBOARD
8085                                 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8086                         mResolveInfo.activityInfo = mResolveActivity;
8087                         mResolveInfo.priority = 0;
8088                         mResolveInfo.preferredOrder = 0;
8089                         mResolveInfo.match = 0;
8090                         mResolveComponentName = new ComponentName(
8091                                 mAndroidApplication.packageName, mResolveActivity.name);
8092                     }
8093                 }
8094             }
8095         }
8096
8097         if (DEBUG_PACKAGE_SCANNING) {
8098             if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8099                 Log.d(TAG, "Scanning package " + pkg.packageName);
8100         }
8101
8102         synchronized (mPackages) {
8103             if (mPackages.containsKey(pkg.packageName)
8104                     || mSharedLibraries.containsKey(pkg.packageName)) {
8105                 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8106                         "Application package " + pkg.packageName
8107                                 + " already installed.  Skipping duplicate.");
8108             }
8109
8110             // If we're only installing presumed-existing packages, require that the
8111             // scanned APK is both already known and at the path previously established
8112             // for it.  Previously unknown packages we pick up normally, but if we have an
8113             // a priori expectation about this package's install presence, enforce it.
8114             // With a singular exception for new system packages. When an OTA contains
8115             // a new system package, we allow the codepath to change from a system location
8116             // to the user-installed location. If we don't allow this change, any newer,
8117             // user-installed version of the application will be ignored.
8118             if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8119                 if (mExpectingBetter.containsKey(pkg.packageName)) {
8120                     logCriticalInfo(Log.WARN,
8121                             "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8122                 } else {
8123                     PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8124                     if (known != null) {
8125                         if (DEBUG_PACKAGE_SCANNING) {
8126                             Log.d(TAG, "Examining " + pkg.codePath
8127                                     + " and requiring known paths " + known.codePathString
8128                                     + " & " + known.resourcePathString);
8129                         }
8130                         if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8131                                 || !pkg.applicationInfo.getResourcePath().equals(
8132                                 known.resourcePathString)) {
8133                             throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8134                                     "Application package " + pkg.packageName
8135                                             + " found at " + pkg.applicationInfo.getCodePath()
8136                                             + " but expected at " + known.codePathString
8137                                             + "; ignoring.");
8138                         }
8139                     }
8140                 }
8141             }
8142         }
8143
8144         // Initialize package source and resource directories
8145         File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8146         File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8147
8148         SharedUserSetting suid = null;
8149         PackageSetting pkgSetting = null;
8150
8151         if (!isSystemApp(pkg)) {
8152             // Only system apps can use these features.
8153             pkg.mOriginalPackages = null;
8154             pkg.mRealPackage = null;
8155             pkg.mAdoptPermissions = null;
8156         }
8157
8158         // Getting the package setting may have a side-effect, so if we
8159         // are only checking if scan would succeed, stash a copy of the
8160         // old setting to restore at the end.
8161         PackageSetting nonMutatedPs = null;
8162
8163         // writer
8164         synchronized (mPackages) {
8165             if (pkg.mSharedUserId != null) {
8166                 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8167                 if (suid == null) {
8168                     throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8169                             "Creating application package " + pkg.packageName
8170                             + " for shared user failed");
8171                 }
8172                 if (DEBUG_PACKAGE_SCANNING) {
8173                     if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8174                         Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8175                                 + "): packages=" + suid.packages);
8176                 }
8177             }
8178
8179             // Check if we are renaming from an original package name.
8180             PackageSetting origPackage = null;
8181             String realName = null;
8182             if (pkg.mOriginalPackages != null) {
8183                 // This package may need to be renamed to a previously
8184                 // installed name.  Let's check on that...
8185                 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8186                 if (pkg.mOriginalPackages.contains(renamed)) {
8187                     // This package had originally been installed as the
8188                     // original name, and we have already taken care of
8189                     // transitioning to the new one.  Just update the new
8190                     // one to continue using the old name.
8191                     realName = pkg.mRealPackage;
8192                     if (!pkg.packageName.equals(renamed)) {
8193                         // Callers into this function may have already taken
8194                         // care of renaming the package; only do it here if
8195                         // it is not already done.
8196                         pkg.setPackageName(renamed);
8197                     }
8198
8199                 } else {
8200                     for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8201                         if ((origPackage = mSettings.peekPackageLPr(
8202                                 pkg.mOriginalPackages.get(i))) != null) {
8203                             // We do have the package already installed under its
8204                             // original name...  should we use it?
8205                             if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8206                                 // New package is not compatible with original.
8207                                 origPackage = null;
8208                                 continue;
8209                             } else if (origPackage.sharedUser != null) {
8210                                 // Make sure uid is compatible between packages.
8211                                 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8212                                     Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8213                                             + " to " + pkg.packageName + ": old uid "
8214                                             + origPackage.sharedUser.name
8215                                             + " differs from " + pkg.mSharedUserId);
8216                                     origPackage = null;
8217                                     continue;
8218                                 }
8219                                 // TODO: Add case when shared user id is added [b/28144775]
8220                             } else {
8221                                 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8222                                         + pkg.packageName + " to old name " + origPackage.name);
8223                             }
8224                             break;
8225                         }
8226                     }
8227                 }
8228             }
8229
8230             if (mTransferedPackages.contains(pkg.packageName)) {
8231                 Slog.w(TAG, "Package " + pkg.packageName
8232                         + " was transferred to another, but its .apk remains");
8233             }
8234
8235             // See comments in nonMutatedPs declaration
8236             if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8237                 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8238                 if (foundPs != null) {
8239                     nonMutatedPs = new PackageSetting(foundPs);
8240                 }
8241             }
8242
8243             // Just create the setting, don't add it yet. For already existing packages
8244             // the PkgSetting exists already and doesn't have to be created.
8245             pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8246                     destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8247                     pkg.applicationInfo.primaryCpuAbi,
8248                     pkg.applicationInfo.secondaryCpuAbi,
8249                     pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8250                     user, false);
8251             if (pkgSetting == null) {
8252                 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8253                         "Creating application package " + pkg.packageName + " failed");
8254             }
8255
8256             if (pkgSetting.origPackage != null) {
8257                 // If we are first transitioning from an original package,
8258                 // fix up the new package's name now.  We need to do this after
8259                 // looking up the package under its new name, so getPackageLP
8260                 // can take care of fiddling things correctly.
8261                 pkg.setPackageName(origPackage.name);
8262
8263                 // File a report about this.
8264                 String msg = "New package " + pkgSetting.realName
8265                         + " renamed to replace old package " + pkgSetting.name;
8266                 reportSettingsProblem(Log.WARN, msg);
8267
8268                 // Make a note of it.
8269                 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8270                     mTransferedPackages.add(origPackage.name);
8271                 }
8272
8273                 // No longer need to retain this.
8274                 pkgSetting.origPackage = null;
8275             }
8276
8277             if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8278                 // Make a note of it.
8279                 mTransferedPackages.add(pkg.packageName);
8280             }
8281
8282             if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8283                 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8284             }
8285
8286             if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8287                 // Check all shared libraries and map to their actual file path.
8288                 // We only do this here for apps not on a system dir, because those
8289                 // are the only ones that can fail an install due to this.  We
8290                 // will take care of the system apps by updating all of their
8291                 // library paths after the scan is done.
8292                 updateSharedLibrariesLPw(pkg, null);
8293             }
8294
8295             if (mFoundPolicyFile) {
8296                 SELinuxMMAC.assignSeinfoValue(pkg);
8297             }
8298
8299             pkg.applicationInfo.uid = pkgSetting.appId;
8300             pkg.mExtras = pkgSetting;
8301             if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8302                 if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8303                     // We just determined the app is signed correctly, so bring
8304                     // over the latest parsed certs.
8305                     pkgSetting.signatures.mSignatures = pkg.mSignatures;
8306                 } else {
8307                     if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8308                         throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8309                                 "Package " + pkg.packageName + " upgrade keys do not match the "
8310                                 + "previously installed version");
8311                     } else {
8312                         pkgSetting.signatures.mSignatures = pkg.mSignatures;
8313                         String msg = "System package " + pkg.packageName
8314                             + " signature changed; retaining data.";
8315                         reportSettingsProblem(Log.WARN, msg);
8316                     }
8317                 }
8318             } else {
8319                 try {
8320                     verifySignaturesLP(pkgSetting, pkg);
8321                     // We just determined the app is signed correctly, so bring
8322                     // over the latest parsed certs.
8323                     pkgSetting.signatures.mSignatures = pkg.mSignatures;
8324                 } catch (PackageManagerException e) {
8325                     if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8326                         throw e;
8327                     }
8328                     // The signature has changed, but this package is in the system
8329                     // image...  let's recover!
8330                     pkgSetting.signatures.mSignatures = pkg.mSignatures;
8331                     // However...  if this package is part of a shared user, but it
8332                     // doesn't match the signature of the shared user, let's fail.
8333                     // What this means is that you can't change the signatures
8334                     // associated with an overall shared user, which doesn't seem all
8335                     // that unreasonable.
8336                     if (pkgSetting.sharedUser != null) {
8337                         if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8338                                               pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8339                             throw new PackageManagerException(
8340                                     INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8341                                             "Signature mismatch for shared user: "
8342                                             + pkgSetting.sharedUser);
8343                         }
8344                     }
8345                     // File a report about this.
8346                     String msg = "System package " + pkg.packageName
8347                         + " signature changed; retaining data.";
8348                     reportSettingsProblem(Log.WARN, msg);
8349                 }
8350             }
8351             // Verify that this new package doesn't have any content providers
8352             // that conflict with existing packages.  Only do this if the
8353             // package isn't already installed, since we don't want to break
8354             // things that are installed.
8355             if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8356                 final int N = pkg.providers.size();
8357                 int i;
8358                 for (i=0; i<N; i++) {
8359                     PackageParser.Provider p = pkg.providers.get(i);
8360                     if (p.info.authority != null) {
8361                         String names[] = p.info.authority.split(";");
8362                         for (int j = 0; j < names.length; j++) {
8363                             if (mProvidersByAuthority.containsKey(names[j])) {
8364                                 PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8365                                 final String otherPackageName =
8366                                         ((other != null && other.getComponentName() != null) ?
8367                                                 other.getComponentName().getPackageName() : "?");
8368                                 throw new PackageManagerException(
8369                                         INSTALL_FAILED_CONFLICTING_PROVIDER,
8370                                                 "Can't install because provider name " + names[j]
8371                                                 + " (in package " + pkg.applicationInfo.packageName
8372                                                 + ") is already used by " + otherPackageName);
8373                             }
8374                         }
8375                     }
8376                 }
8377             }
8378
8379             if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8380                 // This package wants to adopt ownership of permissions from
8381                 // another package.
8382                 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8383                     final String origName = pkg.mAdoptPermissions.get(i);
8384                     final PackageSetting orig = mSettings.peekPackageLPr(origName);
8385                     if (orig != null) {
8386                         if (verifyPackageUpdateLPr(orig, pkg)) {
8387                             Slog.i(TAG, "Adopting permissions from " + origName + " to "
8388                                     + pkg.packageName);
8389                             mSettings.transferPermissionsLPw(origName, pkg.packageName);
8390                         }
8391                     }
8392                 }
8393             }
8394         }
8395
8396         final String pkgName = pkg.packageName;
8397
8398         final long scanFileTime = scanFile.lastModified();
8399         final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8400         pkg.applicationInfo.processName = fixProcessName(
8401                 pkg.applicationInfo.packageName,
8402                 pkg.applicationInfo.processName,
8403                 pkg.applicationInfo.uid);
8404
8405         if (pkg != mPlatformPackage) {
8406             // Get all of our default paths setup
8407             pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8408         }
8409
8410         final String path = scanFile.getPath();
8411         final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8412
8413         if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8414             derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8415
8416             // Some system apps still use directory structure for native libraries
8417             // in which case we might end up not detecting abi solely based on apk
8418             // structure. Try to detect abi based on directory structure.
8419             if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8420                     pkg.applicationInfo.primaryCpuAbi == null) {
8421                 setBundledAppAbisAndRoots(pkg, pkgSetting);
8422                 setNativeLibraryPaths(pkg);
8423             }
8424
8425         } else {
8426             if ((scanFlags & SCAN_MOVE) != 0) {
8427                 // We haven't run dex-opt for this move (since we've moved the compiled output too)
8428                 // but we already have this packages package info in the PackageSetting. We just
8429                 // use that and derive the native library path based on the new codepath.
8430                 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8431                 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8432             }
8433
8434             // Set native library paths again. For moves, the path will be updated based on the
8435             // ABIs we've determined above. For non-moves, the path will be updated based on the
8436             // ABIs we determined during compilation, but the path will depend on the final
8437             // package path (after the rename away from the stage path).
8438             setNativeLibraryPaths(pkg);
8439         }
8440
8441         // This is a special case for the "system" package, where the ABI is
8442         // dictated by the zygote configuration (and init.rc). We should keep track
8443         // of this ABI so that we can deal with "normal" applications that run under
8444         // the same UID correctly.
8445         if (mPlatformPackage == pkg) {
8446             pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8447                     Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8448         }
8449
8450         // If there's a mismatch between the abi-override in the package setting
8451         // and the abiOverride specified for the install. Warn about this because we
8452         // would've already compiled the app without taking the package setting into
8453         // account.
8454         if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8455             if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8456                 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8457                         " for package " + pkg.packageName);
8458             }
8459         }
8460
8461         pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8462         pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8463         pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8464
8465         // Copy the derived override back to the parsed package, so that we can
8466         // update the package settings accordingly.
8467         pkg.cpuAbiOverride = cpuAbiOverride;
8468
8469         if (DEBUG_ABI_SELECTION) {
8470             Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8471                     + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8472                     + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8473         }
8474
8475         // Push the derived path down into PackageSettings so we know what to
8476         // clean up at uninstall time.
8477         pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8478
8479         if (DEBUG_ABI_SELECTION) {
8480             Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8481                     " primary=" + pkg.applicationInfo.primaryCpuAbi +
8482                     " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8483         }
8484
8485         if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8486             // We don't do this here during boot because we can do it all
8487             // at once after scanning all existing packages.
8488             //
8489             // We also do this *before* we perform dexopt on this package, so that
8490             // we can avoid redundant dexopts, and also to make sure we've got the
8491             // code and package path correct.
8492             adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8493                     pkg, true /* boot complete */);
8494         }
8495
8496         if (mFactoryTest && pkg.requestedPermissions.contains(
8497                 android.Manifest.permission.FACTORY_TEST)) {
8498             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8499         }
8500
8501         ArrayList<PackageParser.Package> clientLibPkgs = null;
8502
8503         if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8504             if (nonMutatedPs != null) {
8505                 synchronized (mPackages) {
8506                     mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8507                 }
8508             }
8509             return pkg;
8510         }
8511
8512         // Only privileged apps and updated privileged apps can add child packages.
8513         if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8514             if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8515                 throw new PackageManagerException("Only privileged apps and updated "
8516                         + "privileged apps can add child packages. Ignoring package "
8517                         + pkg.packageName);
8518             }
8519             final int childCount = pkg.childPackages.size();
8520             for (int i = 0; i < childCount; i++) {
8521                 PackageParser.Package childPkg = pkg.childPackages.get(i);
8522                 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8523                         childPkg.packageName)) {
8524                     throw new PackageManagerException("Cannot override a child package of "
8525                             + "another disabled system app. Ignoring package " + pkg.packageName);
8526                 }
8527             }
8528         }
8529
8530         // writer
8531         synchronized (mPackages) {
8532             if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8533                 // Only system apps can add new shared libraries.
8534                 if (pkg.libraryNames != null) {
8535                     for (int i=0; i<pkg.libraryNames.size(); i++) {
8536                         String name = pkg.libraryNames.get(i);
8537                         boolean allowed = false;
8538                         if (pkg.isUpdatedSystemApp()) {
8539                             // New library entries can only be added through the
8540                             // system image.  This is important to get rid of a lot
8541                             // of nasty edge cases: for example if we allowed a non-
8542                             // system update of the app to add a library, then uninstalling
8543                             // the update would make the library go away, and assumptions
8544                             // we made such as through app install filtering would now
8545                             // have allowed apps on the device which aren't compatible
8546                             // with it.  Better to just have the restriction here, be
8547                             // conservative, and create many fewer cases that can negatively
8548                             // impact the user experience.
8549                             final PackageSetting sysPs = mSettings
8550                                     .getDisabledSystemPkgLPr(pkg.packageName);
8551                             if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8552                                 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8553                                     if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8554                                         allowed = true;
8555                                         break;
8556                                     }
8557                                 }
8558                             }
8559                         } else {
8560                             allowed = true;
8561                         }
8562                         if (allowed) {
8563                             if (!mSharedLibraries.containsKey(name)) {
8564                                 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8565                             } else if (!name.equals(pkg.packageName)) {
8566                                 Slog.w(TAG, "Package " + pkg.packageName + " library "
8567                                         + name + " already exists; skipping");
8568                             }
8569                         } else {
8570                             Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8571                                     + name + " that is not declared on system image; skipping");
8572                         }
8573                     }
8574                     if ((scanFlags & SCAN_BOOTING) == 0) {
8575                         // If we are not booting, we need to update any applications
8576                         // that are clients of our shared library.  If we are booting,
8577                         // this will all be done once the scan is complete.
8578                         clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8579                     }
8580                 }
8581             }
8582         }
8583
8584         if ((scanFlags & SCAN_BOOTING) != 0) {
8585             // No apps can run during boot scan, so they don't need to be frozen
8586         } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8587             // Caller asked to not kill app, so it's probably not frozen
8588         } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8589             // Caller asked us to ignore frozen check for some reason; they
8590             // probably didn't know the package name
8591         } else {
8592             // We're doing major surgery on this package, so it better be frozen
8593             // right now to keep it from launching
8594             checkPackageFrozen(pkgName);
8595         }
8596
8597         // Also need to kill any apps that are dependent on the library.
8598         if (clientLibPkgs != null) {
8599             for (int i=0; i<clientLibPkgs.size(); i++) {
8600                 PackageParser.Package clientPkg = clientLibPkgs.get(i);
8601                 killApplication(clientPkg.applicationInfo.packageName,
8602                         clientPkg.applicationInfo.uid, "update lib");
8603             }
8604         }
8605
8606         // Make sure we're not adding any bogus keyset info
8607         KeySetManagerService ksms = mSettings.mKeySetManagerService;
8608         ksms.assertScannedPackageValid(pkg);
8609
8610         // writer
8611         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8612
8613         boolean createIdmapFailed = false;
8614         synchronized (mPackages) {
8615             // We don't expect installation to fail beyond this point
8616
8617             if (pkgSetting.pkg != null) {
8618                 // Note that |user| might be null during the initial boot scan. If a codePath
8619                 // for an app has changed during a boot scan, it's due to an app update that's
8620                 // part of the system partition and marker changes must be applied to all users.
8621                 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8622                     (user != null) ? user : UserHandle.ALL);
8623             }
8624
8625             // Add the new setting to mSettings
8626             mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8627             // Add the new setting to mPackages
8628             mPackages.put(pkg.applicationInfo.packageName, pkg);
8629             // Make sure we don't accidentally delete its data.
8630             final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8631             while (iter.hasNext()) {
8632                 PackageCleanItem item = iter.next();
8633                 if (pkgName.equals(item.packageName)) {
8634                     iter.remove();
8635                 }
8636             }
8637
8638             // Take care of first install / last update times.
8639             if (currentTime != 0) {
8640                 if (pkgSetting.firstInstallTime == 0) {
8641                     pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8642                 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8643                     pkgSetting.lastUpdateTime = currentTime;
8644                 }
8645             } else if (pkgSetting.firstInstallTime == 0) {
8646                 // We need *something*.  Take time time stamp of the file.
8647                 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8648             } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8649                 if (scanFileTime != pkgSetting.timeStamp) {
8650                     // A package on the system image has changed; consider this
8651                     // to be an update.
8652                     pkgSetting.lastUpdateTime = scanFileTime;
8653                 }
8654             }
8655
8656             // Add the package's KeySets to the global KeySetManagerService
8657             ksms.addScannedPackageLPw(pkg);
8658
8659             int N = pkg.providers.size();
8660             StringBuilder r = null;
8661             int i;
8662             for (i=0; i<N; i++) {
8663                 PackageParser.Provider p = pkg.providers.get(i);
8664                 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8665                         p.info.processName, pkg.applicationInfo.uid);
8666                 mProviders.addProvider(p);
8667                 p.syncable = p.info.isSyncable;
8668                 if (p.info.authority != null) {
8669                     String names[] = p.info.authority.split(";");
8670                     p.info.authority = null;
8671                     for (int j = 0; j < names.length; j++) {
8672                         if (j == 1 && p.syncable) {
8673                             // We only want the first authority for a provider to possibly be
8674                             // syncable, so if we already added this provider using a different
8675                             // authority clear the syncable flag. We copy the provider before
8676                             // changing it because the mProviders object contains a reference
8677                             // to a provider that we don't want to change.
8678                             // Only do this for the second authority since the resulting provider
8679                             // object can be the same for all future authorities for this provider.
8680                             p = new PackageParser.Provider(p);
8681                             p.syncable = false;
8682                         }
8683                         if (!mProvidersByAuthority.containsKey(names[j])) {
8684                             mProvidersByAuthority.put(names[j], p);
8685                             if (p.info.authority == null) {
8686                                 p.info.authority = names[j];
8687                             } else {
8688                                 p.info.authority = p.info.authority + ";" + names[j];
8689                             }
8690                             if (DEBUG_PACKAGE_SCANNING) {
8691                                 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8692                                     Log.d(TAG, "Registered content provider: " + names[j]
8693                                             + ", className = " + p.info.name + ", isSyncable = "
8694                                             + p.info.isSyncable);
8695                             }
8696                         } else {
8697                             PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8698                             Slog.w(TAG, "Skipping provider name " + names[j] +
8699                                     " (in package " + pkg.applicationInfo.packageName +
8700                                     "): name already used by "
8701                                     + ((other != null && other.getComponentName() != null)
8702                                             ? other.getComponentName().getPackageName() : "?"));
8703                         }
8704                     }
8705                 }
8706                 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8707                     if (r == null) {
8708                         r = new StringBuilder(256);
8709                     } else {
8710                         r.append(' ');
8711                     }
8712                     r.append(p.info.name);
8713                 }
8714             }
8715             if (r != null) {
8716                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8717             }
8718
8719             N = pkg.services.size();
8720             r = null;
8721             for (i=0; i<N; i++) {
8722                 PackageParser.Service s = pkg.services.get(i);
8723                 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8724                         s.info.processName, pkg.applicationInfo.uid);
8725                 mServices.addService(s);
8726                 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8727                     if (r == null) {
8728                         r = new StringBuilder(256);
8729                     } else {
8730                         r.append(' ');
8731                     }
8732                     r.append(s.info.name);
8733                 }
8734             }
8735             if (r != null) {
8736                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8737             }
8738
8739             N = pkg.receivers.size();
8740             r = null;
8741             for (i=0; i<N; i++) {
8742                 PackageParser.Activity a = pkg.receivers.get(i);
8743                 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8744                         a.info.processName, pkg.applicationInfo.uid);
8745                 mReceivers.addActivity(a, "receiver");
8746                 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8747                     if (r == null) {
8748                         r = new StringBuilder(256);
8749                     } else {
8750                         r.append(' ');
8751                     }
8752                     r.append(a.info.name);
8753                 }
8754             }
8755             if (r != null) {
8756                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8757             }
8758
8759             N = pkg.activities.size();
8760             r = null;
8761             for (i=0; i<N; i++) {
8762                 PackageParser.Activity a = pkg.activities.get(i);
8763                 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8764                         a.info.processName, pkg.applicationInfo.uid);
8765                 mActivities.addActivity(a, "activity");
8766                 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8767                     if (r == null) {
8768                         r = new StringBuilder(256);
8769                     } else {
8770                         r.append(' ');
8771                     }
8772                     r.append(a.info.name);
8773                 }
8774             }
8775             if (r != null) {
8776                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8777             }
8778
8779             N = pkg.permissionGroups.size();
8780             r = null;
8781             for (i=0; i<N; i++) {
8782                 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8783                 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8784                 if (cur == null) {
8785                     mPermissionGroups.put(pg.info.name, pg);
8786                     if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8787                         if (r == null) {
8788                             r = new StringBuilder(256);
8789                         } else {
8790                             r.append(' ');
8791                         }
8792                         r.append(pg.info.name);
8793                     }
8794                 } else {
8795                     Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8796                             + pg.info.packageName + " ignored: original from "
8797                             + cur.info.packageName);
8798                     if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8799                         if (r == null) {
8800                             r = new StringBuilder(256);
8801                         } else {
8802                             r.append(' ');
8803                         }
8804                         r.append("DUP:");
8805                         r.append(pg.info.name);
8806                     }
8807                 }
8808             }
8809             if (r != null) {
8810                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8811             }
8812
8813             N = pkg.permissions.size();
8814             r = null;
8815             for (i=0; i<N; i++) {
8816                 PackageParser.Permission p = pkg.permissions.get(i);
8817
8818                 // Assume by default that we did not install this permission into the system.
8819                 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8820
8821                 // Now that permission groups have a special meaning, we ignore permission
8822                 // groups for legacy apps to prevent unexpected behavior. In particular,
8823                 // permissions for one app being granted to someone just becase they happen
8824                 // to be in a group defined by another app (before this had no implications).
8825                 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8826                     p.group = mPermissionGroups.get(p.info.group);
8827                     // Warn for a permission in an unknown group.
8828                     if (p.info.group != null && p.group == null) {
8829                         Slog.w(TAG, "Permission " + p.info.name + " from package "
8830                                 + p.info.packageName + " in an unknown group " + p.info.group);
8831                     }
8832                 }
8833
8834                 ArrayMap<String, BasePermission> permissionMap =
8835                         p.tree ? mSettings.mPermissionTrees
8836                                 : mSettings.mPermissions;
8837                 BasePermission bp = permissionMap.get(p.info.name);
8838
8839                 // Allow system apps to redefine non-system permissions
8840                 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8841                     final boolean currentOwnerIsSystem = (bp.perm != null
8842                             && isSystemApp(bp.perm.owner));
8843                     if (isSystemApp(p.owner)) {
8844                         if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8845                             // It's a built-in permission and no owner, take ownership now
8846                             bp.packageSetting = pkgSetting;
8847                             bp.perm = p;
8848                             bp.uid = pkg.applicationInfo.uid;
8849                             bp.sourcePackage = p.info.packageName;
8850                             p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8851                         } else if (!currentOwnerIsSystem) {
8852                             String msg = "New decl " + p.owner + " of permission  "
8853                                     + p.info.name + " is system; overriding " + bp.sourcePackage;
8854                             reportSettingsProblem(Log.WARN, msg);
8855                             bp = null;
8856                         }
8857                     }
8858                 }
8859
8860                 if (bp == null) {
8861                     bp = new BasePermission(p.info.name, p.info.packageName,
8862                             BasePermission.TYPE_NORMAL);
8863                     permissionMap.put(p.info.name, bp);
8864                 }
8865
8866                 if (bp.perm == null) {
8867                     if (bp.sourcePackage == null
8868                             || bp.sourcePackage.equals(p.info.packageName)) {
8869                         BasePermission tree = findPermissionTreeLP(p.info.name);
8870                         if (tree == null
8871                                 || tree.sourcePackage.equals(p.info.packageName)) {
8872                             bp.packageSetting = pkgSetting;
8873                             bp.perm = p;
8874                             bp.uid = pkg.applicationInfo.uid;
8875                             bp.sourcePackage = p.info.packageName;
8876                             p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8877                             if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8878                                 if (r == null) {
8879                                     r = new StringBuilder(256);
8880                                 } else {
8881                                     r.append(' ');
8882                                 }
8883                                 r.append(p.info.name);
8884                             }
8885                         } else {
8886                             Slog.w(TAG, "Permission " + p.info.name + " from package "
8887                                     + p.info.packageName + " ignored: base tree "
8888                                     + tree.name + " is from package "
8889                                     + tree.sourcePackage);
8890                         }
8891                     } else {
8892                         Slog.w(TAG, "Permission " + p.info.name + " from package "
8893                                 + p.info.packageName + " ignored: original from "
8894                                 + bp.sourcePackage);
8895                     }
8896                 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8897                     if (r == null) {
8898                         r = new StringBuilder(256);
8899                     } else {
8900                         r.append(' ');
8901                     }
8902                     r.append("DUP:");
8903                     r.append(p.info.name);
8904                 }
8905                 if (bp.perm == p) {
8906                     bp.protectionLevel = p.info.protectionLevel;
8907                 }
8908             }
8909
8910             if (r != null) {
8911                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8912             }
8913
8914             N = pkg.instrumentation.size();
8915             r = null;
8916             for (i=0; i<N; i++) {
8917                 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8918                 a.info.packageName = pkg.applicationInfo.packageName;
8919                 a.info.sourceDir = pkg.applicationInfo.sourceDir;
8920                 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8921                 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8922                 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8923                 a.info.dataDir = pkg.applicationInfo.dataDir;
8924                 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8925                 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8926
8927                 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8928                 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8929                 mInstrumentation.put(a.getComponentName(), a);
8930                 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8931                     if (r == null) {
8932                         r = new StringBuilder(256);
8933                     } else {
8934                         r.append(' ');
8935                     }
8936                     r.append(a.info.name);
8937                 }
8938             }
8939             if (r != null) {
8940                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8941             }
8942
8943             if (pkg.protectedBroadcasts != null) {
8944                 N = pkg.protectedBroadcasts.size();
8945                 for (i=0; i<N; i++) {
8946                     mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8947                 }
8948             }
8949
8950             pkgSetting.setTimeStamp(scanFileTime);
8951
8952             // Create idmap files for pairs of (packages, overlay packages).
8953             // Note: "android", ie framework-res.apk, is handled by native layers.
8954             if (pkg.mOverlayTarget != null) {
8955                 // This is an overlay package.
8956                 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8957                     if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8958                         mOverlays.put(pkg.mOverlayTarget,
8959                                 new ArrayMap<String, PackageParser.Package>());
8960                     }
8961                     ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8962                     map.put(pkg.packageName, pkg);
8963                     PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8964                     if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8965                         createIdmapFailed = true;
8966                     }
8967                 }
8968             } else if (mOverlays.containsKey(pkg.packageName) &&
8969                     !pkg.packageName.equals("android")) {
8970                 // This is a regular package, with one or more known overlay packages.
8971                 createIdmapsForPackageLI(pkg);
8972             }
8973         }
8974
8975         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8976
8977         if (createIdmapFailed) {
8978             throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8979                     "scanPackageLI failed to createIdmap");
8980         }
8981         return pkg;
8982     }
8983
8984     private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
8985             PackageParser.Package update, UserHandle user) {
8986         if (existing.applicationInfo == null || update.applicationInfo == null) {
8987             // This isn't due to an app installation.
8988             return;
8989         }
8990
8991         final File oldCodePath = new File(existing.applicationInfo.getCodePath());
8992         final File newCodePath = new File(update.applicationInfo.getCodePath());
8993
8994         // The codePath hasn't changed, so there's nothing for us to do.
8995         if (Objects.equals(oldCodePath, newCodePath)) {
8996             return;
8997         }
8998
8999         File canonicalNewCodePath;
9000         try {
9001             canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9002         } catch (IOException e) {
9003             Slog.w(TAG, "Failed to get canonical path.", e);
9004             return;
9005         }
9006
9007         // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9008         // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9009         // that the last component of the path (i.e, the name) doesn't need canonicalization
9010         // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9011         // but may change in the future. Hopefully this function won't exist at that point.
9012         final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9013                 oldCodePath.getName());
9014
9015         // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9016         // with "@".
9017         String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9018         if (!oldMarkerPrefix.endsWith("@")) {
9019             oldMarkerPrefix += "@";
9020         }
9021         String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9022         if (!newMarkerPrefix.endsWith("@")) {
9023             newMarkerPrefix += "@";
9024         }
9025
9026         List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9027         List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9028         for (String updatedPath : updatedPaths) {
9029             String updatedPathName = new File(updatedPath).getName();
9030             markerSuffixes.add(updatedPathName.replace('/', '@'));
9031         }
9032
9033         for (int userId : resolveUserIds(user.getIdentifier())) {
9034             File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9035
9036             for (String markerSuffix : markerSuffixes) {
9037                 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9038                 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9039                 if (oldForeignUseMark.exists()) {
9040                     try {
9041                         Os.rename(oldForeignUseMark.getAbsolutePath(),
9042                                 newForeignUseMark.getAbsolutePath());
9043                     } catch (ErrnoException e) {
9044                         Slog.w(TAG, "Failed to rename foreign use marker", e);
9045                         oldForeignUseMark.delete();
9046                     }
9047                 }
9048             }
9049         }
9050     }
9051
9052     /**
9053      * Derive the ABI of a non-system package located at {@code scanFile}. This information
9054      * is derived purely on the basis of the contents of {@code scanFile} and
9055      * {@code cpuAbiOverride}.
9056      *
9057      * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9058      */
9059     private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9060                                  String cpuAbiOverride, boolean extractLibs)
9061             throws PackageManagerException {
9062         // TODO: We can probably be smarter about this stuff. For installed apps,
9063         // we can calculate this information at install time once and for all. For
9064         // system apps, we can probably assume that this information doesn't change
9065         // after the first boot scan. As things stand, we do lots of unnecessary work.
9066
9067         // Give ourselves some initial paths; we'll come back for another
9068         // pass once we've determined ABI below.
9069         setNativeLibraryPaths(pkg);
9070
9071         // We would never need to extract libs for forward-locked and external packages,
9072         // since the container service will do it for us. We shouldn't attempt to
9073         // extract libs from system app when it was not updated.
9074         if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9075                 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9076             extractLibs = false;
9077         }
9078
9079         final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9080         final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9081
9082         NativeLibraryHelper.Handle handle = null;
9083         try {
9084             handle = NativeLibraryHelper.Handle.create(pkg);
9085             // TODO(multiArch): This can be null for apps that didn't go through the
9086             // usual installation process. We can calculate it again, like we
9087             // do during install time.
9088             //
9089             // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9090             // unnecessary.
9091             final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9092
9093             // Null out the abis so that they can be recalculated.
9094             pkg.applicationInfo.primaryCpuAbi = null;
9095             pkg.applicationInfo.secondaryCpuAbi = null;
9096             if (isMultiArch(pkg.applicationInfo)) {
9097                 // Warn if we've set an abiOverride for multi-lib packages..
9098                 // By definition, we need to copy both 32 and 64 bit libraries for
9099                 // such packages.
9100                 if (pkg.cpuAbiOverride != null
9101                         && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9102                     Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9103                 }
9104
9105                 int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9106                 int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9107                 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9108                     if (extractLibs) {
9109                         abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9110                                 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9111                                 useIsaSpecificSubdirs);
9112                     } else {
9113                         abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9114                     }
9115                 }
9116
9117                 maybeThrowExceptionForMultiArchCopy(
9118                         "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9119
9120                 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9121                     if (extractLibs) {
9122                         abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9123                                 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9124                                 useIsaSpecificSubdirs);
9125                     } else {
9126                         abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9127                     }
9128                 }
9129
9130                 maybeThrowExceptionForMultiArchCopy(
9131                         "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9132
9133                 if (abi64 >= 0) {
9134                     pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9135                 }
9136
9137                 if (abi32 >= 0) {
9138                     final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9139                     if (abi64 >= 0) {
9140                         if (pkg.use32bitAbi) {
9141                             pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9142                             pkg.applicationInfo.primaryCpuAbi = abi;
9143                         } else {
9144                             pkg.applicationInfo.secondaryCpuAbi = abi;
9145                         }
9146                     } else {
9147                         pkg.applicationInfo.primaryCpuAbi = abi;
9148                     }
9149                 }
9150
9151             } else {
9152                 String[] abiList = (cpuAbiOverride != null) ?
9153                         new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9154
9155                 // Enable gross and lame hacks for apps that are built with old
9156                 // SDK tools. We must scan their APKs for renderscript bitcode and
9157                 // not launch them if it's present. Don't bother checking on devices
9158                 // that don't have 64 bit support.
9159                 boolean needsRenderScriptOverride = false;
9160                 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9161                         NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9162                     abiList = Build.SUPPORTED_32_BIT_ABIS;
9163                     needsRenderScriptOverride = true;
9164                 }
9165
9166                 final int copyRet;
9167                 if (extractLibs) {
9168                     copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9169                             nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9170                 } else {
9171                     copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9172                 }
9173
9174                 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9175                     throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9176                             "Error unpackaging native libs for app, errorCode=" + copyRet);
9177                 }
9178
9179                 if (copyRet >= 0) {
9180                     pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9181                 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9182                     pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9183                 } else if (needsRenderScriptOverride) {
9184                     pkg.applicationInfo.primaryCpuAbi = abiList[0];
9185                 }
9186             }
9187         } catch (IOException ioe) {
9188             Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9189         } finally {
9190             IoUtils.closeQuietly(handle);
9191         }
9192
9193         // Now that we've calculated the ABIs and determined if it's an internal app,
9194         // we will go ahead and populate the nativeLibraryPath.
9195         setNativeLibraryPaths(pkg);
9196     }
9197
9198     /**
9199      * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9200      * i.e, so that all packages can be run inside a single process if required.
9201      *
9202      * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9203      * this function will either try and make the ABI for all packages in {@code packagesForUser}
9204      * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9205      * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9206      * updating a package that belongs to a shared user.
9207      *
9208      * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9209      * adds unnecessary complexity.
9210      */
9211     private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9212             PackageParser.Package scannedPackage, boolean bootComplete) {
9213         String requiredInstructionSet = null;
9214         if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9215             requiredInstructionSet = VMRuntime.getInstructionSet(
9216                      scannedPackage.applicationInfo.primaryCpuAbi);
9217         }
9218
9219         PackageSetting requirer = null;
9220         for (PackageSetting ps : packagesForUser) {
9221             // If packagesForUser contains scannedPackage, we skip it. This will happen
9222             // when scannedPackage is an update of an existing package. Without this check,
9223             // we will never be able to change the ABI of any package belonging to a shared
9224             // user, even if it's compatible with other packages.
9225             if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9226                 if (ps.primaryCpuAbiString == null) {
9227                     continue;
9228                 }
9229
9230                 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9231                 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9232                     // We have a mismatch between instruction sets (say arm vs arm64) warn about
9233                     // this but there's not much we can do.
9234                     String errorMessage = "Instruction set mismatch, "
9235                             + ((requirer == null) ? "[caller]" : requirer)
9236                             + " requires " + requiredInstructionSet + " whereas " + ps
9237                             + " requires " + instructionSet;
9238                     Slog.w(TAG, errorMessage);
9239                 }
9240
9241                 if (requiredInstructionSet == null) {
9242                     requiredInstructionSet = instructionSet;
9243                     requirer = ps;
9244                 }
9245             }
9246         }
9247
9248         if (requiredInstructionSet != null) {
9249             String adjustedAbi;
9250             if (requirer != null) {
9251                 // requirer != null implies that either scannedPackage was null or that scannedPackage
9252                 // did not require an ABI, in which case we have to adjust scannedPackage to match
9253                 // the ABI of the set (which is the same as requirer's ABI)
9254                 adjustedAbi = requirer.primaryCpuAbiString;
9255                 if (scannedPackage != null) {
9256                     scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9257                 }
9258             } else {
9259                 // requirer == null implies that we're updating all ABIs in the set to
9260                 // match scannedPackage.
9261                 adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9262             }
9263
9264             for (PackageSetting ps : packagesForUser) {
9265                 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9266                     if (ps.primaryCpuAbiString != null) {
9267                         continue;
9268                     }
9269
9270                     ps.primaryCpuAbiString = adjustedAbi;
9271                     if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9272                             !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9273                         ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9274                         Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9275                                 + " (requirer="
9276                                 + (requirer == null ? "null" : requirer.pkg.packageName)
9277                                 + ", scannedPackage="
9278                                 + (scannedPackage != null ? scannedPackage.packageName : "null")
9279                                 + ")");
9280                         try {
9281                             mInstaller.rmdex(ps.codePathString,
9282                                     getDexCodeInstructionSet(getPreferredInstructionSet()));
9283                         } catch (InstallerException ignored) {
9284                         }
9285                     }
9286                 }
9287             }
9288         }
9289     }
9290
9291     private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9292         synchronized (mPackages) {
9293             mResolverReplaced = true;
9294             // Set up information for custom user intent resolution activity.
9295             mResolveActivity.applicationInfo = pkg.applicationInfo;
9296             mResolveActivity.name = mCustomResolverComponentName.getClassName();
9297             mResolveActivity.packageName = pkg.applicationInfo.packageName;
9298             mResolveActivity.processName = pkg.applicationInfo.packageName;
9299             mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9300             mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9301                     ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9302             mResolveActivity.theme = 0;
9303             mResolveActivity.exported = true;
9304             mResolveActivity.enabled = true;
9305             mResolveInfo.activityInfo = mResolveActivity;
9306             mResolveInfo.priority = 0;
9307             mResolveInfo.preferredOrder = 0;
9308             mResolveInfo.match = 0;
9309             mResolveComponentName = mCustomResolverComponentName;
9310             Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9311                     mResolveComponentName);
9312         }
9313     }
9314
9315     private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9316         final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9317
9318         // Set up information for ephemeral installer activity
9319         mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9320         mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9321         mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9322         mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9323         mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9324         mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9325                 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9326         mEphemeralInstallerActivity.theme = 0;
9327         mEphemeralInstallerActivity.exported = true;
9328         mEphemeralInstallerActivity.enabled = true;
9329         mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9330         mEphemeralInstallerInfo.priority = 0;
9331         mEphemeralInstallerInfo.preferredOrder = 0;
9332         mEphemeralInstallerInfo.match = 0;
9333
9334         if (DEBUG_EPHEMERAL) {
9335             Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9336         }
9337     }
9338
9339     private static String calculateBundledApkRoot(final String codePathString) {
9340         final File codePath = new File(codePathString);
9341         final File codeRoot;
9342         if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9343             codeRoot = Environment.getRootDirectory();
9344         } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9345             codeRoot = Environment.getOemDirectory();
9346         } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9347             codeRoot = Environment.getVendorDirectory();
9348         } else {
9349             // Unrecognized code path; take its top real segment as the apk root:
9350             // e.g. /something/app/blah.apk => /something
9351             try {
9352                 File f = codePath.getCanonicalFile();
9353                 File parent = f.getParentFile();    // non-null because codePath is a file
9354                 File tmp;
9355                 while ((tmp = parent.getParentFile()) != null) {
9356                     f = parent;
9357                     parent = tmp;
9358                 }
9359                 codeRoot = f;
9360                 Slog.w(TAG, "Unrecognized code path "
9361                         + codePath + " - using " + codeRoot);
9362             } catch (IOException e) {
9363                 // Can't canonicalize the code path -- shenanigans?
9364                 Slog.w(TAG, "Can't canonicalize code path " + codePath);
9365                 return Environment.getRootDirectory().getPath();
9366             }
9367         }
9368         return codeRoot.getPath();
9369     }
9370
9371     /**
9372      * Derive and set the location of native libraries for the given package,
9373      * which varies depending on where and how the package was installed.
9374      */
9375     private void setNativeLibraryPaths(PackageParser.Package pkg) {
9376         final ApplicationInfo info = pkg.applicationInfo;
9377         final String codePath = pkg.codePath;
9378         final File codeFile = new File(codePath);
9379         final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9380         final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9381
9382         info.nativeLibraryRootDir = null;
9383         info.nativeLibraryRootRequiresIsa = false;
9384         info.nativeLibraryDir = null;
9385         info.secondaryNativeLibraryDir = null;
9386
9387         if (isApkFile(codeFile)) {
9388             // Monolithic install
9389             if (bundledApp) {
9390                 // If "/system/lib64/apkname" exists, assume that is the per-package
9391                 // native library directory to use; otherwise use "/system/lib/apkname".
9392                 final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9393                 final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9394                         getPrimaryInstructionSet(info));
9395
9396                 // This is a bundled system app so choose the path based on the ABI.
9397                 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9398                 // is just the default path.
9399                 final String apkName = deriveCodePathName(codePath);
9400                 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9401                 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9402                         apkName).getAbsolutePath();
9403
9404                 if (info.secondaryCpuAbi != null) {
9405                     final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9406                     info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9407                             secondaryLibDir, apkName).getAbsolutePath();
9408                 }
9409             } else if (asecApp) {
9410                 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9411                         .getAbsolutePath();
9412             } else {
9413                 final String apkName = deriveCodePathName(codePath);
9414                 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9415                         .getAbsolutePath();
9416             }
9417
9418             info.nativeLibraryRootRequiresIsa = false;
9419             info.nativeLibraryDir = info.nativeLibraryRootDir;
9420         } else {
9421             // Cluster install
9422             info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9423             info.nativeLibraryRootRequiresIsa = true;
9424
9425             info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9426                     getPrimaryInstructionSet(info)).getAbsolutePath();
9427
9428             if (info.secondaryCpuAbi != null) {
9429                 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9430                         VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9431             }
9432         }
9433     }
9434
9435     /**
9436      * Calculate the abis and roots for a bundled app. These can uniquely
9437      * be determined from the contents of the system partition, i.e whether
9438      * it contains 64 or 32 bit shared libraries etc. We do not validate any
9439      * of this information, and instead assume that the system was built
9440      * sensibly.
9441      */
9442     private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9443                                            PackageSetting pkgSetting) {
9444         final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9445
9446         // If "/system/lib64/apkname" exists, assume that is the per-package
9447         // native library directory to use; otherwise use "/system/lib/apkname".
9448         final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9449         setBundledAppAbi(pkg, apkRoot, apkName);
9450         // pkgSetting might be null during rescan following uninstall of updates
9451         // to a bundled app, so accommodate that possibility.  The settings in
9452         // that case will be established later from the parsed package.
9453         //
9454         // If the settings aren't null, sync them up with what we've just derived.
9455         // note that apkRoot isn't stored in the package settings.
9456         if (pkgSetting != null) {
9457             pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9458             pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9459         }
9460     }
9461
9462     /**
9463      * Deduces the ABI of a bundled app and sets the relevant fields on the
9464      * parsed pkg object.
9465      *
9466      * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9467      *        under which system libraries are installed.
9468      * @param apkName the name of the installed package.
9469      */
9470     private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9471         final File codeFile = new File(pkg.codePath);
9472
9473         final boolean has64BitLibs;
9474         final boolean has32BitLibs;
9475         if (isApkFile(codeFile)) {
9476             // Monolithic install
9477             has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9478             has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9479         } else {
9480             // Cluster install
9481             final File rootDir = new File(codeFile, LIB_DIR_NAME);
9482             if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9483                     && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9484                 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9485                 has64BitLibs = (new File(rootDir, isa)).exists();
9486             } else {
9487                 has64BitLibs = false;
9488             }
9489             if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9490                     && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9491                 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9492                 has32BitLibs = (new File(rootDir, isa)).exists();
9493             } else {
9494                 has32BitLibs = false;
9495             }
9496         }
9497
9498         if (has64BitLibs && !has32BitLibs) {
9499             // The package has 64 bit libs, but not 32 bit libs. Its primary
9500             // ABI should be 64 bit. We can safely assume here that the bundled
9501             // native libraries correspond to the most preferred ABI in the list.
9502
9503             pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9504             pkg.applicationInfo.secondaryCpuAbi = null;
9505         } else if (has32BitLibs && !has64BitLibs) {
9506             // The package has 32 bit libs but not 64 bit libs. Its primary
9507             // ABI should be 32 bit.
9508
9509             pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9510             pkg.applicationInfo.secondaryCpuAbi = null;
9511         } else if (has32BitLibs && has64BitLibs) {
9512             // The application has both 64 and 32 bit bundled libraries. We check
9513             // here that the app declares multiArch support, and warn if it doesn't.
9514             //
9515             // We will be lenient here and record both ABIs. The primary will be the
9516             // ABI that's higher on the list, i.e, a device that's configured to prefer
9517             // 64 bit apps will see a 64 bit primary ABI,
9518
9519             if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9520                 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9521             }
9522
9523             if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9524                 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9525                 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9526             } else {
9527                 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9528                 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9529             }
9530         } else {
9531             pkg.applicationInfo.primaryCpuAbi = null;
9532             pkg.applicationInfo.secondaryCpuAbi = null;
9533         }
9534     }
9535
9536     private void killApplication(String pkgName, int appId, String reason) {
9537         killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9538     }
9539
9540     private void killApplication(String pkgName, int appId, int userId, String reason) {
9541         // Request the ActivityManager to kill the process(only for existing packages)
9542         // so that we do not end up in a confused state while the user is still using the older
9543         // version of the application while the new one gets installed.
9544         final long token = Binder.clearCallingIdentity();
9545         try {
9546             IActivityManager am = ActivityManagerNative.getDefault();
9547             if (am != null) {
9548                 try {
9549                     am.killApplication(pkgName, appId, userId, reason);
9550                 } catch (RemoteException e) {
9551                 }
9552             }
9553         } finally {
9554             Binder.restoreCallingIdentity(token);
9555         }
9556     }
9557
9558     private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9559         // Remove the parent package setting
9560         PackageSetting ps = (PackageSetting) pkg.mExtras;
9561         if (ps != null) {
9562             removePackageLI(ps, chatty);
9563         }
9564         // Remove the child package setting
9565         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9566         for (int i = 0; i < childCount; i++) {
9567             PackageParser.Package childPkg = pkg.childPackages.get(i);
9568             ps = (PackageSetting) childPkg.mExtras;
9569             if (ps != null) {
9570                 removePackageLI(ps, chatty);
9571             }
9572         }
9573     }
9574
9575     void removePackageLI(PackageSetting ps, boolean chatty) {
9576         if (DEBUG_INSTALL) {
9577             if (chatty)
9578                 Log.d(TAG, "Removing package " + ps.name);
9579         }
9580
9581         // writer
9582         synchronized (mPackages) {
9583             mPackages.remove(ps.name);
9584             final PackageParser.Package pkg = ps.pkg;
9585             if (pkg != null) {
9586                 cleanPackageDataStructuresLILPw(pkg, chatty);
9587             }
9588         }
9589     }
9590
9591     void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9592         if (DEBUG_INSTALL) {
9593             if (chatty)
9594                 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9595         }
9596
9597         // writer
9598         synchronized (mPackages) {
9599             // Remove the parent package
9600             mPackages.remove(pkg.applicationInfo.packageName);
9601             cleanPackageDataStructuresLILPw(pkg, chatty);
9602
9603             // Remove the child packages
9604             final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9605             for (int i = 0; i < childCount; i++) {
9606                 PackageParser.Package childPkg = pkg.childPackages.get(i);
9607                 mPackages.remove(childPkg.applicationInfo.packageName);
9608                 cleanPackageDataStructuresLILPw(childPkg, chatty);
9609             }
9610         }
9611     }
9612
9613     void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9614         int N = pkg.providers.size();
9615         StringBuilder r = null;
9616         int i;
9617         for (i=0; i<N; i++) {
9618             PackageParser.Provider p = pkg.providers.get(i);
9619             mProviders.removeProvider(p);
9620             if (p.info.authority == null) {
9621
9622                 /* There was another ContentProvider with this authority when
9623                  * this app was installed so this authority is null,
9624                  * Ignore it as we don't have to unregister the provider.
9625                  */
9626                 continue;
9627             }
9628             String names[] = p.info.authority.split(";");
9629             for (int j = 0; j < names.length; j++) {
9630                 if (mProvidersByAuthority.get(names[j]) == p) {
9631                     mProvidersByAuthority.remove(names[j]);
9632                     if (DEBUG_REMOVE) {
9633                         if (chatty)
9634                             Log.d(TAG, "Unregistered content provider: " + names[j]
9635                                     + ", className = " + p.info.name + ", isSyncable = "
9636                                     + p.info.isSyncable);
9637                     }
9638                 }
9639             }
9640             if (DEBUG_REMOVE && chatty) {
9641                 if (r == null) {
9642                     r = new StringBuilder(256);
9643                 } else {
9644                     r.append(' ');
9645                 }
9646                 r.append(p.info.name);
9647             }
9648         }
9649         if (r != null) {
9650             if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9651         }
9652
9653         N = pkg.services.size();
9654         r = null;
9655         for (i=0; i<N; i++) {
9656             PackageParser.Service s = pkg.services.get(i);
9657             mServices.removeService(s);
9658             if (chatty) {
9659                 if (r == null) {
9660                     r = new StringBuilder(256);
9661                 } else {
9662                     r.append(' ');
9663                 }
9664                 r.append(s.info.name);
9665             }
9666         }
9667         if (r != null) {
9668             if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9669         }
9670
9671         N = pkg.receivers.size();
9672         r = null;
9673         for (i=0; i<N; i++) {
9674             PackageParser.Activity a = pkg.receivers.get(i);
9675             mReceivers.removeActivity(a, "receiver");
9676             if (DEBUG_REMOVE && chatty) {
9677                 if (r == null) {
9678                     r = new StringBuilder(256);
9679                 } else {
9680                     r.append(' ');
9681                 }
9682                 r.append(a.info.name);
9683             }
9684         }
9685         if (r != null) {
9686             if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9687         }
9688
9689         N = pkg.activities.size();
9690         r = null;
9691         for (i=0; i<N; i++) {
9692             PackageParser.Activity a = pkg.activities.get(i);
9693             mActivities.removeActivity(a, "activity");
9694             if (DEBUG_REMOVE && chatty) {
9695                 if (r == null) {
9696                     r = new StringBuilder(256);
9697                 } else {
9698                     r.append(' ');
9699                 }
9700                 r.append(a.info.name);
9701             }
9702         }
9703         if (r != null) {
9704             if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9705         }
9706
9707         N = pkg.permissions.size();
9708         r = null;
9709         for (i=0; i<N; i++) {
9710             PackageParser.Permission p = pkg.permissions.get(i);
9711             BasePermission bp = mSettings.mPermissions.get(p.info.name);
9712             if (bp == null) {
9713                 bp = mSettings.mPermissionTrees.get(p.info.name);
9714             }
9715             if (bp != null && bp.perm == p) {
9716                 bp.perm = null;
9717                 if (DEBUG_REMOVE && chatty) {
9718                     if (r == null) {
9719                         r = new StringBuilder(256);
9720                     } else {
9721                         r.append(' ');
9722                     }
9723                     r.append(p.info.name);
9724                 }
9725             }
9726             if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9727                 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9728                 if (appOpPkgs != null) {
9729                     appOpPkgs.remove(pkg.packageName);
9730                 }
9731             }
9732         }
9733         if (r != null) {
9734             if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9735         }
9736
9737         N = pkg.requestedPermissions.size();
9738         r = null;
9739         for (i=0; i<N; i++) {
9740             String perm = pkg.requestedPermissions.get(i);
9741             BasePermission bp = mSettings.mPermissions.get(perm);
9742             if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9743                 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9744                 if (appOpPkgs != null) {
9745                     appOpPkgs.remove(pkg.packageName);
9746                     if (appOpPkgs.isEmpty()) {
9747                         mAppOpPermissionPackages.remove(perm);
9748                     }
9749                 }
9750             }
9751         }
9752         if (r != null) {
9753             if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9754         }
9755
9756         N = pkg.instrumentation.size();
9757         r = null;
9758         for (i=0; i<N; i++) {
9759             PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9760             mInstrumentation.remove(a.getComponentName());
9761             if (DEBUG_REMOVE && chatty) {
9762                 if (r == null) {
9763                     r = new StringBuilder(256);
9764                 } else {
9765                     r.append(' ');
9766                 }
9767                 r.append(a.info.name);
9768             }
9769         }
9770         if (r != null) {
9771             if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9772         }
9773
9774         r = null;
9775         if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9776             // Only system apps can hold shared libraries.
9777             if (pkg.libraryNames != null) {
9778                 for (i=0; i<pkg.libraryNames.size(); i++) {
9779                     String name = pkg.libraryNames.get(i);
9780                     SharedLibraryEntry cur = mSharedLibraries.get(name);
9781                     if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9782                         mSharedLibraries.remove(name);
9783                         if (DEBUG_REMOVE && chatty) {
9784                             if (r == null) {
9785                                 r = new StringBuilder(256);
9786                             } else {
9787                                 r.append(' ');
9788                             }
9789                             r.append(name);
9790                         }
9791                     }
9792                 }
9793             }
9794         }
9795         if (r != null) {
9796             if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9797         }
9798     }
9799
9800     private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9801         for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9802             if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9803                 return true;
9804             }
9805         }
9806         return false;
9807     }
9808
9809     static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9810     static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9811     static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9812
9813     private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9814         // Update the parent permissions
9815         updatePermissionsLPw(pkg.packageName, pkg, flags);
9816         // Update the child permissions
9817         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9818         for (int i = 0; i < childCount; i++) {
9819             PackageParser.Package childPkg = pkg.childPackages.get(i);
9820             updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9821         }
9822     }
9823
9824     private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9825             int flags) {
9826         final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9827         updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9828     }
9829
9830     private void updatePermissionsLPw(String changingPkg,
9831             PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9832         // Make sure there are no dangling permission trees.
9833         Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9834         while (it.hasNext()) {
9835             final BasePermission bp = it.next();
9836             if (bp.packageSetting == null) {
9837                 // We may not yet have parsed the package, so just see if
9838                 // we still know about its settings.
9839                 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9840             }
9841             if (bp.packageSetting == null) {
9842                 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9843                         + " from package " + bp.sourcePackage);
9844                 it.remove();
9845             } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9846                 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9847                     Slog.i(TAG, "Removing old permission tree: " + bp.name
9848                             + " from package " + bp.sourcePackage);
9849                     flags |= UPDATE_PERMISSIONS_ALL;
9850                     it.remove();
9851                 }
9852             }
9853         }
9854
9855         // Make sure all dynamic permissions have been assigned to a package,
9856         // and make sure there are no dangling permissions.
9857         it = mSettings.mPermissions.values().iterator();
9858         while (it.hasNext()) {
9859             final BasePermission bp = it.next();
9860             if (bp.type == BasePermission.TYPE_DYNAMIC) {
9861                 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9862                         + bp.name + " pkg=" + bp.sourcePackage
9863                         + " info=" + bp.pendingInfo);
9864                 if (bp.packageSetting == null && bp.pendingInfo != null) {
9865                     final BasePermission tree = findPermissionTreeLP(bp.name);
9866                     if (tree != null && tree.perm != null) {
9867                         bp.packageSetting = tree.packageSetting;
9868                         bp.perm = new PackageParser.Permission(tree.perm.owner,
9869                                 new PermissionInfo(bp.pendingInfo));
9870                         bp.perm.info.packageName = tree.perm.info.packageName;
9871                         bp.perm.info.name = bp.name;
9872                         bp.uid = tree.uid;
9873                     }
9874                 }
9875             }
9876             if (bp.packageSetting == null) {
9877                 // We may not yet have parsed the package, so just see if
9878                 // we still know about its settings.
9879                 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9880             }
9881             if (bp.packageSetting == null) {
9882                 Slog.w(TAG, "Removing dangling permission: " + bp.name
9883                         + " from package " + bp.sourcePackage);
9884                 it.remove();
9885             } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9886                 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9887                     Slog.i(TAG, "Removing old permission: " + bp.name
9888                             + " from package " + bp.sourcePackage);
9889                     flags |= UPDATE_PERMISSIONS_ALL;
9890                     it.remove();
9891                 }
9892             }
9893         }
9894
9895         // Now update the permissions for all packages, in particular
9896         // replace the granted permissions of the system packages.
9897         if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9898             for (PackageParser.Package pkg : mPackages.values()) {
9899                 if (pkg != pkgInfo) {
9900                     // Only replace for packages on requested volume
9901                     final String volumeUuid = getVolumeUuidForPackage(pkg);
9902                     final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9903                             && Objects.equals(replaceVolumeUuid, volumeUuid);
9904                     grantPermissionsLPw(pkg, replace, changingPkg);
9905                 }
9906             }
9907         }
9908
9909         if (pkgInfo != null) {
9910             // Only replace for packages on requested volume
9911             final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9912             final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9913                     && Objects.equals(replaceVolumeUuid, volumeUuid);
9914             grantPermissionsLPw(pkgInfo, replace, changingPkg);
9915         }
9916     }
9917
9918     private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9919             String packageOfInterest) {
9920         // IMPORTANT: There are two types of permissions: install and runtime.
9921         // Install time permissions are granted when the app is installed to
9922         // all device users and users added in the future. Runtime permissions
9923         // are granted at runtime explicitly to specific users. Normal and signature
9924         // protected permissions are install time permissions. Dangerous permissions
9925         // are install permissions if the app's target SDK is Lollipop MR1 or older,
9926         // otherwise they are runtime permissions. This function does not manage
9927         // runtime permissions except for the case an app targeting Lollipop MR1
9928         // being upgraded to target a newer SDK, in which case dangerous permissions
9929         // are transformed from install time to runtime ones.
9930
9931         final PackageSetting ps = (PackageSetting) pkg.mExtras;
9932         if (ps == null) {
9933             return;
9934         }
9935
9936         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9937
9938         PermissionsState permissionsState = ps.getPermissionsState();
9939         PermissionsState origPermissions = permissionsState;
9940
9941         final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9942
9943         boolean runtimePermissionsRevoked = false;
9944         int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9945
9946         boolean changedInstallPermission = false;
9947
9948         if (replace) {
9949             ps.installPermissionsFixed = false;
9950             if (!ps.isSharedUser()) {
9951                 origPermissions = new PermissionsState(permissionsState);
9952                 permissionsState.reset();
9953             } else {
9954                 // We need to know only about runtime permission changes since the
9955                 // calling code always writes the install permissions state but
9956                 // the runtime ones are written only if changed. The only cases of
9957                 // changed runtime permissions here are promotion of an install to
9958                 // runtime and revocation of a runtime from a shared user.
9959                 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9960                         ps.sharedUser, UserManagerService.getInstance().getUserIds());
9961                 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9962                     runtimePermissionsRevoked = true;
9963                 }
9964             }
9965         }
9966
9967         permissionsState.setGlobalGids(mGlobalGids);
9968
9969         final int N = pkg.requestedPermissions.size();
9970         for (int i=0; i<N; i++) {
9971             final String name = pkg.requestedPermissions.get(i);
9972             final BasePermission bp = mSettings.mPermissions.get(name);
9973
9974             if (DEBUG_INSTALL) {
9975                 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9976             }
9977
9978             if (bp == null || bp.packageSetting == null) {
9979                 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9980                     Slog.w(TAG, "Unknown permission " + name
9981                             + " in package " + pkg.packageName);
9982                 }
9983                 continue;
9984             }
9985
9986             final String perm = bp.name;
9987             boolean allowedSig = false;
9988             int grant = GRANT_DENIED;
9989
9990             // Keep track of app op permissions.
9991             if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9992                 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9993                 if (pkgs == null) {
9994                     pkgs = new ArraySet<>();
9995                     mAppOpPermissionPackages.put(bp.name, pkgs);
9996                 }
9997                 pkgs.add(pkg.packageName);
9998             }
9999
10000             final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
10001             final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10002                     >= Build.VERSION_CODES.M;
10003             switch (level) {
10004                 case PermissionInfo.PROTECTION_NORMAL: {
10005                     // For all apps normal permissions are install time ones.
10006                     grant = GRANT_INSTALL;
10007                 } break;
10008
10009                 case PermissionInfo.PROTECTION_DANGEROUS: {
10010                     // If a permission review is required for legacy apps we represent
10011                     // their permissions as always granted runtime ones since we need
10012                     // to keep the review required permission flag per user while an
10013                     // install permission's state is shared across all users.
10014                     if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
10015                         // For legacy apps dangerous permissions are install time ones.
10016                         grant = GRANT_INSTALL;
10017                     } else if (origPermissions.hasInstallPermission(bp.name)) {
10018                         // For legacy apps that became modern, install becomes runtime.
10019                         grant = GRANT_UPGRADE;
10020                     } else if (mPromoteSystemApps
10021                             && isSystemApp(ps)
10022                             && mExistingSystemPackages.contains(ps.name)) {
10023                         // For legacy system apps, install becomes runtime.
10024                         // We cannot check hasInstallPermission() for system apps since those
10025                         // permissions were granted implicitly and not persisted pre-M.
10026                         grant = GRANT_UPGRADE;
10027                     } else {
10028                         // For modern apps keep runtime permissions unchanged.
10029                         grant = GRANT_RUNTIME;
10030                     }
10031                 } break;
10032
10033                 case PermissionInfo.PROTECTION_SIGNATURE: {
10034                     // For all apps signature permissions are install time ones.
10035                     allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10036                     if (allowedSig) {
10037                         grant = GRANT_INSTALL;
10038                     }
10039                 } break;
10040             }
10041
10042             if (DEBUG_INSTALL) {
10043                 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10044             }
10045
10046             if (grant != GRANT_DENIED) {
10047                 if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10048                     // If this is an existing, non-system package, then
10049                     // we can't add any new permissions to it.
10050                     if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10051                         // Except...  if this is a permission that was added
10052                         // to the platform (note: need to only do this when
10053                         // updating the platform).
10054                         if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10055                             grant = GRANT_DENIED;
10056                         }
10057                     }
10058                 }
10059
10060                 switch (grant) {
10061                     case GRANT_INSTALL: {
10062                         // Revoke this as runtime permission to handle the case of
10063                         // a runtime permission being downgraded to an install one.
10064                         // Also in permission review mode we keep dangerous permissions
10065                         // for legacy apps
10066                         for (int userId : UserManagerService.getInstance().getUserIds()) {
10067                             if (origPermissions.getRuntimePermissionState(
10068                                     bp.name, userId) != null) {
10069                                 // Revoke the runtime permission and clear the flags.
10070                                 origPermissions.revokeRuntimePermission(bp, userId);
10071                                 origPermissions.updatePermissionFlags(bp, userId,
10072                                       PackageManager.MASK_PERMISSION_FLAGS, 0);
10073                                 // If we revoked a permission permission, we have to write.
10074                                 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10075                                         changedRuntimePermissionUserIds, userId);
10076                             }
10077                         }
10078                         // Grant an install permission.
10079                         if (permissionsState.grantInstallPermission(bp) !=
10080                                 PermissionsState.PERMISSION_OPERATION_FAILURE) {
10081                             changedInstallPermission = true;
10082                         }
10083                     } break;
10084
10085                     case GRANT_RUNTIME: {
10086                         // Grant previously granted runtime permissions.
10087                         for (int userId : UserManagerService.getInstance().getUserIds()) {
10088                             PermissionState permissionState = origPermissions
10089                                     .getRuntimePermissionState(bp.name, userId);
10090                             int flags = permissionState != null
10091                                     ? permissionState.getFlags() : 0;
10092                             if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10093                                 if (permissionsState.grantRuntimePermission(bp, userId) ==
10094                                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
10095                                     // If we cannot put the permission as it was, we have to write.
10096                                     changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10097                                             changedRuntimePermissionUserIds, userId);
10098                                 }
10099                                 // If the app supports runtime permissions no need for a review.
10100                                 if (Build.PERMISSIONS_REVIEW_REQUIRED
10101                                         && appSupportsRuntimePermissions
10102                                         && (flags & PackageManager
10103                                                 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10104                                     flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10105                                     // Since we changed the flags, we have to write.
10106                                     changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10107                                             changedRuntimePermissionUserIds, userId);
10108                                 }
10109                             } else if (Build.PERMISSIONS_REVIEW_REQUIRED
10110                                     && !appSupportsRuntimePermissions) {
10111                                 // For legacy apps that need a permission review, every new
10112                                 // runtime permission is granted but it is pending a review.
10113                                 // We also need to review only platform defined runtime
10114                                 // permissions as these are the only ones the platform knows
10115                                 // how to disable the API to simulate revocation as legacy
10116                                 // apps don't expect to run with revoked permissions.
10117                                 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10118                                     if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10119                                         flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10120                                         // We changed the flags, hence have to write.
10121                                         changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10122                                                 changedRuntimePermissionUserIds, userId);
10123                                     }
10124                                 }
10125                                 if (permissionsState.grantRuntimePermission(bp, userId)
10126                                         != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10127                                     // We changed the permission, hence have to write.
10128                                     changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10129                                             changedRuntimePermissionUserIds, userId);
10130                                 }
10131                             }
10132                             // Propagate the permission flags.
10133                             permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10134                         }
10135                     } break;
10136
10137                     case GRANT_UPGRADE: {
10138                         // Grant runtime permissions for a previously held install permission.
10139                         PermissionState permissionState = origPermissions
10140                                 .getInstallPermissionState(bp.name);
10141                         final int flags = permissionState != null ? permissionState.getFlags() : 0;
10142
10143                         if (origPermissions.revokeInstallPermission(bp)
10144                                 != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10145                             // We will be transferring the permission flags, so clear them.
10146                             origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10147                                     PackageManager.MASK_PERMISSION_FLAGS, 0);
10148                             changedInstallPermission = true;
10149                         }
10150
10151                         // If the permission is not to be promoted to runtime we ignore it and
10152                         // also its other flags as they are not applicable to install permissions.
10153                         if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10154                             for (int userId : currentUserIds) {
10155                                 if (permissionsState.grantRuntimePermission(bp, userId) !=
10156                                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
10157                                     // Transfer the permission flags.
10158                                     permissionsState.updatePermissionFlags(bp, userId,
10159                                             flags, flags);
10160                                     // If we granted the permission, we have to write.
10161                                     changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10162                                             changedRuntimePermissionUserIds, userId);
10163                                 }
10164                             }
10165                         }
10166                     } break;
10167
10168                     default: {
10169                         if (packageOfInterest == null
10170                                 || packageOfInterest.equals(pkg.packageName)) {
10171                             Slog.w(TAG, "Not granting permission " + perm
10172                                     + " to package " + pkg.packageName
10173                                     + " because it was previously installed without");
10174                         }
10175                     } break;
10176                 }
10177             } else {
10178                 if (permissionsState.revokeInstallPermission(bp) !=
10179                         PermissionsState.PERMISSION_OPERATION_FAILURE) {
10180                     // Also drop the permission flags.
10181                     permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10182                             PackageManager.MASK_PERMISSION_FLAGS, 0);
10183                     changedInstallPermission = true;
10184                     Slog.i(TAG, "Un-granting permission " + perm
10185                             + " from package " + pkg.packageName
10186                             + " (protectionLevel=" + bp.protectionLevel
10187                             + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10188                             + ")");
10189                 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10190                     // Don't print warning for app op permissions, since it is fine for them
10191                     // not to be granted, there is a UI for the user to decide.
10192                     if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10193                         Slog.w(TAG, "Not granting permission " + perm
10194                                 + " to package " + pkg.packageName
10195                                 + " (protectionLevel=" + bp.protectionLevel
10196                                 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10197                                 + ")");
10198                     }
10199                 }
10200             }
10201         }
10202
10203         if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10204                 !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10205             // This is the first that we have heard about this package, so the
10206             // permissions we have now selected are fixed until explicitly
10207             // changed.
10208             ps.installPermissionsFixed = true;
10209         }
10210
10211         // Persist the runtime permissions state for users with changes. If permissions
10212         // were revoked because no app in the shared user declares them we have to
10213         // write synchronously to avoid losing runtime permissions state.
10214         for (int userId : changedRuntimePermissionUserIds) {
10215             mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10216         }
10217
10218         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10219     }
10220
10221     private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10222         boolean allowed = false;
10223         final int NP = PackageParser.NEW_PERMISSIONS.length;
10224         for (int ip=0; ip<NP; ip++) {
10225             final PackageParser.NewPermissionInfo npi
10226                     = PackageParser.NEW_PERMISSIONS[ip];
10227             if (npi.name.equals(perm)
10228                     && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10229                 allowed = true;
10230                 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10231                         + pkg.packageName);
10232                 break;
10233             }
10234         }
10235         return allowed;
10236     }
10237
10238     private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10239             BasePermission bp, PermissionsState origPermissions) {
10240         boolean allowed;
10241         allowed = (compareSignatures(
10242                 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10243                         == PackageManager.SIGNATURE_MATCH)
10244                 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10245                         == PackageManager.SIGNATURE_MATCH);
10246         if (!allowed && (bp.protectionLevel
10247                 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10248             if (isSystemApp(pkg)) {
10249                 // For updated system applications, a system permission
10250                 // is granted only if it had been defined by the original application.
10251                 if (pkg.isUpdatedSystemApp()) {
10252                     final PackageSetting sysPs = mSettings
10253                             .getDisabledSystemPkgLPr(pkg.packageName);
10254                     if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10255                         // If the original was granted this permission, we take
10256                         // that grant decision as read and propagate it to the
10257                         // update.
10258                         if (sysPs.isPrivileged()) {
10259                             allowed = true;
10260                         }
10261                     } else {
10262                         // The system apk may have been updated with an older
10263                         // version of the one on the data partition, but which
10264                         // granted a new system permission that it didn't have
10265                         // before.  In this case we do want to allow the app to
10266                         // now get the new permission if the ancestral apk is
10267                         // privileged to get it.
10268                         if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10269                             for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10270                                 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10271                                     allowed = true;
10272                                     break;
10273                                 }
10274                             }
10275                         }
10276                         // Also if a privileged parent package on the system image or any of
10277                         // its children requested a privileged permission, the updated child
10278                         // packages can also get the permission.
10279                         if (pkg.parentPackage != null) {
10280                             final PackageSetting disabledSysParentPs = mSettings
10281                                     .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10282                             if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10283                                     && disabledSysParentPs.isPrivileged()) {
10284                                 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10285                                     allowed = true;
10286                                 } else if (disabledSysParentPs.pkg.childPackages != null) {
10287                                     final int count = disabledSysParentPs.pkg.childPackages.size();
10288                                     for (int i = 0; i < count; i++) {
10289                                         PackageParser.Package disabledSysChildPkg =
10290                                                 disabledSysParentPs.pkg.childPackages.get(i);
10291                                         if (isPackageRequestingPermission(disabledSysChildPkg,
10292                                                 perm)) {
10293                                             allowed = true;
10294                                             break;
10295                                         }
10296                                     }
10297                                 }
10298                             }
10299                         }
10300                     }
10301                 } else {
10302                     allowed = isPrivilegedApp(pkg);
10303                 }
10304             }
10305         }
10306         if (!allowed) {
10307             if (!allowed && (bp.protectionLevel
10308                     & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10309                     && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10310                 // If this was a previously normal/dangerous permission that got moved
10311                 // to a system permission as part of the runtime permission redesign, then
10312                 // we still want to blindly grant it to old apps.
10313                 allowed = true;
10314             }
10315             if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10316                     && pkg.packageName.equals(mRequiredInstallerPackage)) {
10317                 // If this permission is to be granted to the system installer and
10318                 // this app is an installer, then it gets the permission.
10319                 allowed = true;
10320             }
10321             if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10322                     && pkg.packageName.equals(mRequiredVerifierPackage)) {
10323                 // If this permission is to be granted to the system verifier and
10324                 // this app is a verifier, then it gets the permission.
10325                 allowed = true;
10326             }
10327             if (!allowed && (bp.protectionLevel
10328                     & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10329                     && isSystemApp(pkg)) {
10330                 // Any pre-installed system app is allowed to get this permission.
10331                 allowed = true;
10332             }
10333             if (!allowed && (bp.protectionLevel
10334                     & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10335                 // For development permissions, a development permission
10336                 // is granted only if it was already granted.
10337                 allowed = origPermissions.hasInstallPermission(perm);
10338             }
10339             if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10340                     && pkg.packageName.equals(mSetupWizardPackage)) {
10341                 // If this permission is to be granted to the system setup wizard and
10342                 // this app is a setup wizard, then it gets the permission.
10343                 allowed = true;
10344             }
10345         }
10346         return allowed;
10347     }
10348
10349     private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10350         final int permCount = pkg.requestedPermissions.size();
10351         for (int j = 0; j < permCount; j++) {
10352             String requestedPermission = pkg.requestedPermissions.get(j);
10353             if (permission.equals(requestedPermission)) {
10354                 return true;
10355             }
10356         }
10357         return false;
10358     }
10359
10360     final class ActivityIntentResolver
10361             extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10362         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10363                 boolean defaultOnly, int userId) {
10364             if (!sUserManager.exists(userId)) return null;
10365             mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10366             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10367         }
10368
10369         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10370                 int userId) {
10371             if (!sUserManager.exists(userId)) return null;
10372             mFlags = flags;
10373             return super.queryIntent(intent, resolvedType,
10374                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10375         }
10376
10377         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10378                 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10379             if (!sUserManager.exists(userId)) return null;
10380             if (packageActivities == null) {
10381                 return null;
10382             }
10383             mFlags = flags;
10384             final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10385             final int N = packageActivities.size();
10386             ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10387                 new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10388
10389             ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10390             for (int i = 0; i < N; ++i) {
10391                 intentFilters = packageActivities.get(i).intents;
10392                 if (intentFilters != null && intentFilters.size() > 0) {
10393                     PackageParser.ActivityIntentInfo[] array =
10394                             new PackageParser.ActivityIntentInfo[intentFilters.size()];
10395                     intentFilters.toArray(array);
10396                     listCut.add(array);
10397                 }
10398             }
10399             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10400         }
10401
10402         /**
10403          * Finds a privileged activity that matches the specified activity names.
10404          */
10405         private PackageParser.Activity findMatchingActivity(
10406                 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10407             for (PackageParser.Activity sysActivity : activityList) {
10408                 if (sysActivity.info.name.equals(activityInfo.name)) {
10409                     return sysActivity;
10410                 }
10411                 if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10412                     return sysActivity;
10413                 }
10414                 if (sysActivity.info.targetActivity != null) {
10415                     if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10416                         return sysActivity;
10417                     }
10418                     if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10419                         return sysActivity;
10420                     }
10421                 }
10422             }
10423             return null;
10424         }
10425
10426         public class IterGenerator<E> {
10427             public Iterator<E> generate(ActivityIntentInfo info) {
10428                 return null;
10429             }
10430         }
10431
10432         public class ActionIterGenerator extends IterGenerator<String> {
10433             @Override
10434             public Iterator<String> generate(ActivityIntentInfo info) {
10435                 return info.actionsIterator();
10436             }
10437         }
10438
10439         public class CategoriesIterGenerator extends IterGenerator<String> {
10440             @Override
10441             public Iterator<String> generate(ActivityIntentInfo info) {
10442                 return info.categoriesIterator();
10443             }
10444         }
10445
10446         public class SchemesIterGenerator extends IterGenerator<String> {
10447             @Override
10448             public Iterator<String> generate(ActivityIntentInfo info) {
10449                 return info.schemesIterator();
10450             }
10451         }
10452
10453         public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10454             @Override
10455             public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10456                 return info.authoritiesIterator();
10457             }
10458         }
10459
10460         /**
10461          * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10462          * MODIFIED. Do not pass in a list that should not be changed.
10463          */
10464         private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10465                 IterGenerator<T> generator, Iterator<T> searchIterator) {
10466             // loop through the set of actions; every one must be found in the intent filter
10467             while (searchIterator.hasNext()) {
10468                 // we must have at least one filter in the list to consider a match
10469                 if (intentList.size() == 0) {
10470                     break;
10471                 }
10472
10473                 final T searchAction = searchIterator.next();
10474
10475                 // loop through the set of intent filters
10476                 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10477                 while (intentIter.hasNext()) {
10478                     final ActivityIntentInfo intentInfo = intentIter.next();
10479                     boolean selectionFound = false;
10480
10481                     // loop through the intent filter's selection criteria; at least one
10482                     // of them must match the searched criteria
10483                     final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10484                     while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10485                         final T intentSelection = intentSelectionIter.next();
10486                         if (intentSelection != null && intentSelection.equals(searchAction)) {
10487                             selectionFound = true;
10488                             break;
10489                         }
10490                     }
10491
10492                     // the selection criteria wasn't found in this filter's set; this filter
10493                     // is not a potential match
10494                     if (!selectionFound) {
10495                         intentIter.remove();
10496                     }
10497                 }
10498             }
10499         }
10500
10501         private boolean isProtectedAction(ActivityIntentInfo filter) {
10502             final Iterator<String> actionsIter = filter.actionsIterator();
10503             while (actionsIter != null && actionsIter.hasNext()) {
10504                 final String filterAction = actionsIter.next();
10505                 if (PROTECTED_ACTIONS.contains(filterAction)) {
10506                     return true;
10507                 }
10508             }
10509             return false;
10510         }
10511
10512         /**
10513          * Adjusts the priority of the given intent filter according to policy.
10514          * <p>
10515          * <ul>
10516          * <li>The priority for non privileged applications is capped to '0'</li>
10517          * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10518          * <li>The priority for unbundled updates to privileged applications is capped to the
10519          *      priority defined on the system partition</li>
10520          * </ul>
10521          * <p>
10522          * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10523          * allowed to obtain any priority on any action.
10524          */
10525         private void adjustPriority(
10526                 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10527             // nothing to do; priority is fine as-is
10528             if (intent.getPriority() <= 0) {
10529                 return;
10530             }
10531
10532             final ActivityInfo activityInfo = intent.activity.info;
10533             final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10534
10535             final boolean privilegedApp =
10536                     ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10537             if (!privilegedApp) {
10538                 // non-privileged applications can never define a priority >0
10539                 Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10540                         + " package: " + applicationInfo.packageName
10541                         + " activity: " + intent.activity.className
10542                         + " origPrio: " + intent.getPriority());
10543                 intent.setPriority(0);
10544                 return;
10545             }
10546
10547             if (systemActivities == null) {
10548                 // the system package is not disabled; we're parsing the system partition
10549                 if (isProtectedAction(intent)) {
10550                     if (mDeferProtectedFilters) {
10551                         // We can't deal with these just yet. No component should ever obtain a
10552                         // >0 priority for a protected actions, with ONE exception -- the setup
10553                         // wizard. The setup wizard, however, cannot be known until we're able to
10554                         // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10555                         // until all intent filters have been processed. Chicken, meet egg.
10556                         // Let the filter temporarily have a high priority and rectify the
10557                         // priorities after all system packages have been scanned.
10558                         mProtectedFilters.add(intent);
10559                         if (DEBUG_FILTERS) {
10560                             Slog.i(TAG, "Protected action; save for later;"
10561                                     + " package: " + applicationInfo.packageName
10562                                     + " activity: " + intent.activity.className
10563                                     + " origPrio: " + intent.getPriority());
10564                         }
10565                         return;
10566                     } else {
10567                         if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10568                             Slog.i(TAG, "No setup wizard;"
10569                                 + " All protected intents capped to priority 0");
10570                         }
10571                         if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10572                             if (DEBUG_FILTERS) {
10573                                 Slog.i(TAG, "Found setup wizard;"
10574                                     + " allow priority " + intent.getPriority() + ";"
10575                                     + " package: " + intent.activity.info.packageName
10576                                     + " activity: " + intent.activity.className
10577                                     + " priority: " + intent.getPriority());
10578                             }
10579                             // setup wizard gets whatever it wants
10580                             return;
10581                         }
10582                         Slog.w(TAG, "Protected action; cap priority to 0;"
10583                                 + " package: " + intent.activity.info.packageName
10584                                 + " activity: " + intent.activity.className
10585                                 + " origPrio: " + intent.getPriority());
10586                         intent.setPriority(0);
10587                         return;
10588                     }
10589                 }
10590                 // privileged apps on the system image get whatever priority they request
10591                 return;
10592             }
10593
10594             // privileged app unbundled update ... try to find the same activity
10595             final PackageParser.Activity foundActivity =
10596                     findMatchingActivity(systemActivities, activityInfo);
10597             if (foundActivity == null) {
10598                 // this is a new activity; it cannot obtain >0 priority
10599                 if (DEBUG_FILTERS) {
10600                     Slog.i(TAG, "New activity; cap priority to 0;"
10601                             + " package: " + applicationInfo.packageName
10602                             + " activity: " + intent.activity.className
10603                             + " origPrio: " + intent.getPriority());
10604                 }
10605                 intent.setPriority(0);
10606                 return;
10607             }
10608
10609             // found activity, now check for filter equivalence
10610
10611             // a shallow copy is enough; we modify the list, not its contents
10612             final List<ActivityIntentInfo> intentListCopy =
10613                     new ArrayList<>(foundActivity.intents);
10614             final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10615
10616             // find matching action subsets
10617             final Iterator<String> actionsIterator = intent.actionsIterator();
10618             if (actionsIterator != null) {
10619                 getIntentListSubset(
10620                         intentListCopy, new ActionIterGenerator(), actionsIterator);
10621                 if (intentListCopy.size() == 0) {
10622                     // no more intents to match; we're not equivalent
10623                     if (DEBUG_FILTERS) {
10624                         Slog.i(TAG, "Mismatched action; cap priority to 0;"
10625                                 + " package: " + applicationInfo.packageName
10626                                 + " activity: " + intent.activity.className
10627                                 + " origPrio: " + intent.getPriority());
10628                     }
10629                     intent.setPriority(0);
10630                     return;
10631                 }
10632             }
10633
10634             // find matching category subsets
10635             final Iterator<String> categoriesIterator = intent.categoriesIterator();
10636             if (categoriesIterator != null) {
10637                 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10638                         categoriesIterator);
10639                 if (intentListCopy.size() == 0) {
10640                     // no more intents to match; we're not equivalent
10641                     if (DEBUG_FILTERS) {
10642                         Slog.i(TAG, "Mismatched category; cap priority to 0;"
10643                                 + " package: " + applicationInfo.packageName
10644                                 + " activity: " + intent.activity.className
10645                                 + " origPrio: " + intent.getPriority());
10646                     }
10647                     intent.setPriority(0);
10648                     return;
10649                 }
10650             }
10651
10652             // find matching schemes subsets
10653             final Iterator<String> schemesIterator = intent.schemesIterator();
10654             if (schemesIterator != null) {
10655                 getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10656                         schemesIterator);
10657                 if (intentListCopy.size() == 0) {
10658                     // no more intents to match; we're not equivalent
10659                     if (DEBUG_FILTERS) {
10660                         Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10661                                 + " package: " + applicationInfo.packageName
10662                                 + " activity: " + intent.activity.className
10663                                 + " origPrio: " + intent.getPriority());
10664                     }
10665                     intent.setPriority(0);
10666                     return;
10667                 }
10668             }
10669
10670             // find matching authorities subsets
10671             final Iterator<IntentFilter.AuthorityEntry>
10672                     authoritiesIterator = intent.authoritiesIterator();
10673             if (authoritiesIterator != null) {
10674                 getIntentListSubset(intentListCopy,
10675                         new AuthoritiesIterGenerator(),
10676                         authoritiesIterator);
10677                 if (intentListCopy.size() == 0) {
10678                     // no more intents to match; we're not equivalent
10679                     if (DEBUG_FILTERS) {
10680                         Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10681                                 + " package: " + applicationInfo.packageName
10682                                 + " activity: " + intent.activity.className
10683                                 + " origPrio: " + intent.getPriority());
10684                     }
10685                     intent.setPriority(0);
10686                     return;
10687                 }
10688             }
10689
10690             // we found matching filter(s); app gets the max priority of all intents
10691             int cappedPriority = 0;
10692             for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10693                 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10694             }
10695             if (intent.getPriority() > cappedPriority) {
10696                 if (DEBUG_FILTERS) {
10697                     Slog.i(TAG, "Found matching filter(s);"
10698                             + " cap priority to " + cappedPriority + ";"
10699                             + " package: " + applicationInfo.packageName
10700                             + " activity: " + intent.activity.className
10701                             + " origPrio: " + intent.getPriority());
10702                 }
10703                 intent.setPriority(cappedPriority);
10704                 return;
10705             }
10706             // all this for nothing; the requested priority was <= what was on the system
10707         }
10708
10709         public final void addActivity(PackageParser.Activity a, String type) {
10710             mActivities.put(a.getComponentName(), a);
10711             if (DEBUG_SHOW_INFO)
10712                 Log.v(
10713                 TAG, "  " + type + " " +
10714                 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10715             if (DEBUG_SHOW_INFO)
10716                 Log.v(TAG, "    Class=" + a.info.name);
10717             final int NI = a.intents.size();
10718             for (int j=0; j<NI; j++) {
10719                 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10720                 if ("activity".equals(type)) {
10721                     final PackageSetting ps =
10722                             mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10723                     final List<PackageParser.Activity> systemActivities =
10724                             ps != null && ps.pkg != null ? ps.pkg.activities : null;
10725                     adjustPriority(systemActivities, intent);
10726                 }
10727                 if (DEBUG_SHOW_INFO) {
10728                     Log.v(TAG, "    IntentFilter:");
10729                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10730                 }
10731                 if (!intent.debugCheck()) {
10732                     Log.w(TAG, "==> For Activity " + a.info.name);
10733                 }
10734                 addFilter(intent);
10735             }
10736         }
10737
10738         public final void removeActivity(PackageParser.Activity a, String type) {
10739             mActivities.remove(a.getComponentName());
10740             if (DEBUG_SHOW_INFO) {
10741                 Log.v(TAG, "  " + type + " "
10742                         + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10743                                 : a.info.name) + ":");
10744                 Log.v(TAG, "    Class=" + a.info.name);
10745             }
10746             final int NI = a.intents.size();
10747             for (int j=0; j<NI; j++) {
10748                 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10749                 if (DEBUG_SHOW_INFO) {
10750                     Log.v(TAG, "    IntentFilter:");
10751                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10752                 }
10753                 removeFilter(intent);
10754             }
10755         }
10756
10757         @Override
10758         protected boolean allowFilterResult(
10759                 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10760             ActivityInfo filterAi = filter.activity.info;
10761             for (int i=dest.size()-1; i>=0; i--) {
10762                 ActivityInfo destAi = dest.get(i).activityInfo;
10763                 if (destAi.name == filterAi.name
10764                         && destAi.packageName == filterAi.packageName) {
10765                     return false;
10766                 }
10767             }
10768             return true;
10769         }
10770
10771         @Override
10772         protected ActivityIntentInfo[] newArray(int size) {
10773             return new ActivityIntentInfo[size];
10774         }
10775
10776         @Override
10777         protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10778             if (!sUserManager.exists(userId)) return true;
10779             PackageParser.Package p = filter.activity.owner;
10780             if (p != null) {
10781                 PackageSetting ps = (PackageSetting)p.mExtras;
10782                 if (ps != null) {
10783                     // System apps are never considered stopped for purposes of
10784                     // filtering, because there may be no way for the user to
10785                     // actually re-launch them.
10786                     return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10787                             && ps.getStopped(userId);
10788                 }
10789             }
10790             return false;
10791         }
10792
10793         @Override
10794         protected boolean isPackageForFilter(String packageName,
10795                 PackageParser.ActivityIntentInfo info) {
10796             return packageName.equals(info.activity.owner.packageName);
10797         }
10798
10799         @Override
10800         protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10801                 int match, int userId) {
10802             if (!sUserManager.exists(userId)) return null;
10803             if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10804                 return null;
10805             }
10806             final PackageParser.Activity activity = info.activity;
10807             PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10808             if (ps == null) {
10809                 return null;
10810             }
10811             ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10812                     ps.readUserState(userId), userId);
10813             if (ai == null) {
10814                 return null;
10815             }
10816             final ResolveInfo res = new ResolveInfo();
10817             res.activityInfo = ai;
10818             if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10819                 res.filter = info;
10820             }
10821             if (info != null) {
10822                 res.handleAllWebDataURI = info.handleAllWebDataURI();
10823             }
10824             res.priority = info.getPriority();
10825             res.preferredOrder = activity.owner.mPreferredOrder;
10826             //System.out.println("Result: " + res.activityInfo.className +
10827             //                   " = " + res.priority);
10828             res.match = match;
10829             res.isDefault = info.hasDefault;
10830             res.labelRes = info.labelRes;
10831             res.nonLocalizedLabel = info.nonLocalizedLabel;
10832             if (userNeedsBadging(userId)) {
10833                 res.noResourceId = true;
10834             } else {
10835                 res.icon = info.icon;
10836             }
10837             res.iconResourceId = info.icon;
10838             res.system = res.activityInfo.applicationInfo.isSystemApp();
10839             return res;
10840         }
10841
10842         @Override
10843         protected void sortResults(List<ResolveInfo> results) {
10844             Collections.sort(results, mResolvePrioritySorter);
10845         }
10846
10847         @Override
10848         protected void dumpFilter(PrintWriter out, String prefix,
10849                 PackageParser.ActivityIntentInfo filter) {
10850             out.print(prefix); out.print(
10851                     Integer.toHexString(System.identityHashCode(filter.activity)));
10852                     out.print(' ');
10853                     filter.activity.printComponentShortName(out);
10854                     out.print(" filter ");
10855                     out.println(Integer.toHexString(System.identityHashCode(filter)));
10856         }
10857
10858         @Override
10859         protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10860             return filter.activity;
10861         }
10862
10863         protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10864             PackageParser.Activity activity = (PackageParser.Activity)label;
10865             out.print(prefix); out.print(
10866                     Integer.toHexString(System.identityHashCode(activity)));
10867                     out.print(' ');
10868                     activity.printComponentShortName(out);
10869             if (count > 1) {
10870                 out.print(" ("); out.print(count); out.print(" filters)");
10871             }
10872             out.println();
10873         }
10874
10875         // Keys are String (activity class name), values are Activity.
10876         private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10877                 = new ArrayMap<ComponentName, PackageParser.Activity>();
10878         private int mFlags;
10879     }
10880
10881     private final class ServiceIntentResolver
10882             extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10883         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10884                 boolean defaultOnly, int userId) {
10885             mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10886             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10887         }
10888
10889         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10890                 int userId) {
10891             if (!sUserManager.exists(userId)) return null;
10892             mFlags = flags;
10893             return super.queryIntent(intent, resolvedType,
10894                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10895         }
10896
10897         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10898                 int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10899             if (!sUserManager.exists(userId)) return null;
10900             if (packageServices == null) {
10901                 return null;
10902             }
10903             mFlags = flags;
10904             final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10905             final int N = packageServices.size();
10906             ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10907                 new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10908
10909             ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10910             for (int i = 0; i < N; ++i) {
10911                 intentFilters = packageServices.get(i).intents;
10912                 if (intentFilters != null && intentFilters.size() > 0) {
10913                     PackageParser.ServiceIntentInfo[] array =
10914                             new PackageParser.ServiceIntentInfo[intentFilters.size()];
10915                     intentFilters.toArray(array);
10916                     listCut.add(array);
10917                 }
10918             }
10919             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10920         }
10921
10922         public final void addService(PackageParser.Service s) {
10923             mServices.put(s.getComponentName(), s);
10924             if (DEBUG_SHOW_INFO) {
10925                 Log.v(TAG, "  "
10926                         + (s.info.nonLocalizedLabel != null
10927                         ? s.info.nonLocalizedLabel : s.info.name) + ":");
10928                 Log.v(TAG, "    Class=" + s.info.name);
10929             }
10930             final int NI = s.intents.size();
10931             int j;
10932             for (j=0; j<NI; j++) {
10933                 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10934                 if (DEBUG_SHOW_INFO) {
10935                     Log.v(TAG, "    IntentFilter:");
10936                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10937                 }
10938                 if (!intent.debugCheck()) {
10939                     Log.w(TAG, "==> For Service " + s.info.name);
10940                 }
10941                 addFilter(intent);
10942             }
10943         }
10944
10945         public final void removeService(PackageParser.Service s) {
10946             mServices.remove(s.getComponentName());
10947             if (DEBUG_SHOW_INFO) {
10948                 Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10949                         ? s.info.nonLocalizedLabel : s.info.name) + ":");
10950                 Log.v(TAG, "    Class=" + s.info.name);
10951             }
10952             final int NI = s.intents.size();
10953             int j;
10954             for (j=0; j<NI; j++) {
10955                 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10956                 if (DEBUG_SHOW_INFO) {
10957                     Log.v(TAG, "    IntentFilter:");
10958                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10959                 }
10960                 removeFilter(intent);
10961             }
10962         }
10963
10964         @Override
10965         protected boolean allowFilterResult(
10966                 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10967             ServiceInfo filterSi = filter.service.info;
10968             for (int i=dest.size()-1; i>=0; i--) {
10969                 ServiceInfo destAi = dest.get(i).serviceInfo;
10970                 if (destAi.name == filterSi.name
10971                         && destAi.packageName == filterSi.packageName) {
10972                     return false;
10973                 }
10974             }
10975             return true;
10976         }
10977
10978         @Override
10979         protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10980             return new PackageParser.ServiceIntentInfo[size];
10981         }
10982
10983         @Override
10984         protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10985             if (!sUserManager.exists(userId)) return true;
10986             PackageParser.Package p = filter.service.owner;
10987             if (p != null) {
10988                 PackageSetting ps = (PackageSetting)p.mExtras;
10989                 if (ps != null) {
10990                     // System apps are never considered stopped for purposes of
10991                     // filtering, because there may be no way for the user to
10992                     // actually re-launch them.
10993                     return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10994                             && ps.getStopped(userId);
10995                 }
10996             }
10997             return false;
10998         }
10999
11000         @Override
11001         protected boolean isPackageForFilter(String packageName,
11002                 PackageParser.ServiceIntentInfo info) {
11003             return packageName.equals(info.service.owner.packageName);
11004         }
11005
11006         @Override
11007         protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11008                 int match, int userId) {
11009             if (!sUserManager.exists(userId)) return null;
11010             final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11011             if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11012                 return null;
11013             }
11014             final PackageParser.Service service = info.service;
11015             PackageSetting ps = (PackageSetting) service.owner.mExtras;
11016             if (ps == null) {
11017                 return null;
11018             }
11019             ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11020                     ps.readUserState(userId), userId);
11021             if (si == null) {
11022                 return null;
11023             }
11024             final ResolveInfo res = new ResolveInfo();
11025             res.serviceInfo = si;
11026             if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11027                 res.filter = filter;
11028             }
11029             res.priority = info.getPriority();
11030             res.preferredOrder = service.owner.mPreferredOrder;
11031             res.match = match;
11032             res.isDefault = info.hasDefault;
11033             res.labelRes = info.labelRes;
11034             res.nonLocalizedLabel = info.nonLocalizedLabel;
11035             res.icon = info.icon;
11036             res.system = res.serviceInfo.applicationInfo.isSystemApp();
11037             return res;
11038         }
11039
11040         @Override
11041         protected void sortResults(List<ResolveInfo> results) {
11042             Collections.sort(results, mResolvePrioritySorter);
11043         }
11044
11045         @Override
11046         protected void dumpFilter(PrintWriter out, String prefix,
11047                 PackageParser.ServiceIntentInfo filter) {
11048             out.print(prefix); out.print(
11049                     Integer.toHexString(System.identityHashCode(filter.service)));
11050                     out.print(' ');
11051                     filter.service.printComponentShortName(out);
11052                     out.print(" filter ");
11053                     out.println(Integer.toHexString(System.identityHashCode(filter)));
11054         }
11055
11056         @Override
11057         protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11058             return filter.service;
11059         }
11060
11061         protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11062             PackageParser.Service service = (PackageParser.Service)label;
11063             out.print(prefix); out.print(
11064                     Integer.toHexString(System.identityHashCode(service)));
11065                     out.print(' ');
11066                     service.printComponentShortName(out);
11067             if (count > 1) {
11068                 out.print(" ("); out.print(count); out.print(" filters)");
11069             }
11070             out.println();
11071         }
11072
11073 //        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11074 //            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11075 //            final List<ResolveInfo> retList = Lists.newArrayList();
11076 //            while (i.hasNext()) {
11077 //                final ResolveInfo resolveInfo = (ResolveInfo) i;
11078 //                if (isEnabledLP(resolveInfo.serviceInfo)) {
11079 //                    retList.add(resolveInfo);
11080 //                }
11081 //            }
11082 //            return retList;
11083 //        }
11084
11085         // Keys are String (activity class name), values are Activity.
11086         private final ArrayMap<ComponentName, PackageParser.Service> mServices
11087                 = new ArrayMap<ComponentName, PackageParser.Service>();
11088         private int mFlags;
11089     };
11090
11091     private final class ProviderIntentResolver
11092             extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11093         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11094                 boolean defaultOnly, int userId) {
11095             mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11096             return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11097         }
11098
11099         public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11100                 int userId) {
11101             if (!sUserManager.exists(userId))
11102                 return null;
11103             mFlags = flags;
11104             return super.queryIntent(intent, resolvedType,
11105                     (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11106         }
11107
11108         public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11109                 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11110             if (!sUserManager.exists(userId))
11111                 return null;
11112             if (packageProviders == null) {
11113                 return null;
11114             }
11115             mFlags = flags;
11116             final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11117             final int N = packageProviders.size();
11118             ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11119                     new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11120
11121             ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11122             for (int i = 0; i < N; ++i) {
11123                 intentFilters = packageProviders.get(i).intents;
11124                 if (intentFilters != null && intentFilters.size() > 0) {
11125                     PackageParser.ProviderIntentInfo[] array =
11126                             new PackageParser.ProviderIntentInfo[intentFilters.size()];
11127                     intentFilters.toArray(array);
11128                     listCut.add(array);
11129                 }
11130             }
11131             return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11132         }
11133
11134         public final void addProvider(PackageParser.Provider p) {
11135             if (mProviders.containsKey(p.getComponentName())) {
11136                 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11137                 return;
11138             }
11139
11140             mProviders.put(p.getComponentName(), p);
11141             if (DEBUG_SHOW_INFO) {
11142                 Log.v(TAG, "  "
11143                         + (p.info.nonLocalizedLabel != null
11144                                 ? p.info.nonLocalizedLabel : p.info.name) + ":");
11145                 Log.v(TAG, "    Class=" + p.info.name);
11146             }
11147             final int NI = p.intents.size();
11148             int j;
11149             for (j = 0; j < NI; j++) {
11150                 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11151                 if (DEBUG_SHOW_INFO) {
11152                     Log.v(TAG, "    IntentFilter:");
11153                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11154                 }
11155                 if (!intent.debugCheck()) {
11156                     Log.w(TAG, "==> For Provider " + p.info.name);
11157                 }
11158                 addFilter(intent);
11159             }
11160         }
11161
11162         public final void removeProvider(PackageParser.Provider p) {
11163             mProviders.remove(p.getComponentName());
11164             if (DEBUG_SHOW_INFO) {
11165                 Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11166                         ? p.info.nonLocalizedLabel : p.info.name) + ":");
11167                 Log.v(TAG, "    Class=" + p.info.name);
11168             }
11169             final int NI = p.intents.size();
11170             int j;
11171             for (j = 0; j < NI; j++) {
11172                 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11173                 if (DEBUG_SHOW_INFO) {
11174                     Log.v(TAG, "    IntentFilter:");
11175                     intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11176                 }
11177                 removeFilter(intent);
11178             }
11179         }
11180
11181         @Override
11182         protected boolean allowFilterResult(
11183                 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11184             ProviderInfo filterPi = filter.provider.info;
11185             for (int i = dest.size() - 1; i >= 0; i--) {
11186                 ProviderInfo destPi = dest.get(i).providerInfo;
11187                 if (destPi.name == filterPi.name
11188                         && destPi.packageName == filterPi.packageName) {
11189                     return false;
11190                 }
11191             }
11192             return true;
11193         }
11194
11195         @Override
11196         protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11197             return new PackageParser.ProviderIntentInfo[size];
11198         }
11199
11200         @Override
11201         protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11202             if (!sUserManager.exists(userId))
11203                 return true;
11204             PackageParser.Package p = filter.provider.owner;
11205             if (p != null) {
11206                 PackageSetting ps = (PackageSetting) p.mExtras;
11207                 if (ps != null) {
11208                     // System apps are never considered stopped for purposes of
11209                     // filtering, because there may be no way for the user to
11210                     // actually re-launch them.
11211                     return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11212                             && ps.getStopped(userId);
11213                 }
11214             }
11215             return false;
11216         }
11217
11218         @Override
11219         protected boolean isPackageForFilter(String packageName,
11220                 PackageParser.ProviderIntentInfo info) {
11221             return packageName.equals(info.provider.owner.packageName);
11222         }
11223
11224         @Override
11225         protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11226                 int match, int userId) {
11227             if (!sUserManager.exists(userId))
11228                 return null;
11229             final PackageParser.ProviderIntentInfo info = filter;
11230             if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11231                 return null;
11232             }
11233             final PackageParser.Provider provider = info.provider;
11234             PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11235             if (ps == null) {
11236                 return null;
11237             }
11238             ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11239                     ps.readUserState(userId), userId);
11240             if (pi == null) {
11241                 return null;
11242             }
11243             final ResolveInfo res = new ResolveInfo();
11244             res.providerInfo = pi;
11245             if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11246                 res.filter = filter;
11247             }
11248             res.priority = info.getPriority();
11249             res.preferredOrder = provider.owner.mPreferredOrder;
11250             res.match = match;
11251             res.isDefault = info.hasDefault;
11252             res.labelRes = info.labelRes;
11253             res.nonLocalizedLabel = info.nonLocalizedLabel;
11254             res.icon = info.icon;
11255             res.system = res.providerInfo.applicationInfo.isSystemApp();
11256             return res;
11257         }
11258
11259         @Override
11260         protected void sortResults(List<ResolveInfo> results) {
11261             Collections.sort(results, mResolvePrioritySorter);
11262         }
11263
11264         @Override
11265         protected void dumpFilter(PrintWriter out, String prefix,
11266                 PackageParser.ProviderIntentInfo filter) {
11267             out.print(prefix);
11268             out.print(
11269                     Integer.toHexString(System.identityHashCode(filter.provider)));
11270             out.print(' ');
11271             filter.provider.printComponentShortName(out);
11272             out.print(" filter ");
11273             out.println(Integer.toHexString(System.identityHashCode(filter)));
11274         }
11275
11276         @Override
11277         protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11278             return filter.provider;
11279         }
11280
11281         protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11282             PackageParser.Provider provider = (PackageParser.Provider)label;
11283             out.print(prefix); out.print(
11284                     Integer.toHexString(System.identityHashCode(provider)));
11285                     out.print(' ');
11286                     provider.printComponentShortName(out);
11287             if (count > 1) {
11288                 out.print(" ("); out.print(count); out.print(" filters)");
11289             }
11290             out.println();
11291         }
11292
11293         private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11294                 = new ArrayMap<ComponentName, PackageParser.Provider>();
11295         private int mFlags;
11296     }
11297
11298     private static final class EphemeralIntentResolver
11299             extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11300         @Override
11301         protected EphemeralResolveIntentInfo[] newArray(int size) {
11302             return new EphemeralResolveIntentInfo[size];
11303         }
11304
11305         @Override
11306         protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11307             return true;
11308         }
11309
11310         @Override
11311         protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11312                 int userId) {
11313             if (!sUserManager.exists(userId)) {
11314                 return null;
11315             }
11316             return info.getEphemeralResolveInfo();
11317         }
11318     }
11319
11320     private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11321             new Comparator<ResolveInfo>() {
11322         public int compare(ResolveInfo r1, ResolveInfo r2) {
11323             int v1 = r1.priority;
11324             int v2 = r2.priority;
11325             //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11326             if (v1 != v2) {
11327                 return (v1 > v2) ? -1 : 1;
11328             }
11329             v1 = r1.preferredOrder;
11330             v2 = r2.preferredOrder;
11331             if (v1 != v2) {
11332                 return (v1 > v2) ? -1 : 1;
11333             }
11334             if (r1.isDefault != r2.isDefault) {
11335                 return r1.isDefault ? -1 : 1;
11336             }
11337             v1 = r1.match;
11338             v2 = r2.match;
11339             //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11340             if (v1 != v2) {
11341                 return (v1 > v2) ? -1 : 1;
11342             }
11343             if (r1.system != r2.system) {
11344                 return r1.system ? -1 : 1;
11345             }
11346             if (r1.activityInfo != null) {
11347                 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11348             }
11349             if (r1.serviceInfo != null) {
11350                 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11351             }
11352             if (r1.providerInfo != null) {
11353                 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11354             }
11355             return 0;
11356         }
11357     };
11358
11359     private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11360             new Comparator<ProviderInfo>() {
11361         public int compare(ProviderInfo p1, ProviderInfo p2) {
11362             final int v1 = p1.initOrder;
11363             final int v2 = p2.initOrder;
11364             return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11365         }
11366     };
11367
11368     final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11369             final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11370             final int[] userIds) {
11371         mHandler.post(new Runnable() {
11372             @Override
11373             public void run() {
11374                 try {
11375                     final IActivityManager am = ActivityManagerNative.getDefault();
11376                     if (am == null) return;
11377                     final int[] resolvedUserIds;
11378                     if (userIds == null) {
11379                         resolvedUserIds = am.getRunningUserIds();
11380                     } else {
11381                         resolvedUserIds = userIds;
11382                     }
11383                     for (int id : resolvedUserIds) {
11384                         final Intent intent = new Intent(action,
11385                                 pkg != null ? Uri.fromParts("package", pkg, null) : null);
11386                         if (extras != null) {
11387                             intent.putExtras(extras);
11388                         }
11389                         if (targetPkg != null) {
11390                             intent.setPackage(targetPkg);
11391                         }
11392                         // Modify the UID when posting to other users
11393                         int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11394                         if (uid > 0 && UserHandle.getUserId(uid) != id) {
11395                             uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11396                             intent.putExtra(Intent.EXTRA_UID, uid);
11397                         }
11398                         intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11399                         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11400                         if (DEBUG_BROADCASTS) {
11401                             RuntimeException here = new RuntimeException("here");
11402                             here.fillInStackTrace();
11403                             Slog.d(TAG, "Sending to user " + id + ": "
11404                                     + intent.toShortString(false, true, false, false)
11405                                     + " " + intent.getExtras(), here);
11406                         }
11407                         am.broadcastIntent(null, intent, null, finishedReceiver,
11408                                 0, null, null, null, android.app.AppOpsManager.OP_NONE,
11409                                 null, finishedReceiver != null, false, id);
11410                     }
11411                 } catch (RemoteException ex) {
11412                 }
11413             }
11414         });
11415     }
11416
11417     /**
11418      * Check if the external storage media is available. This is true if there
11419      * is a mounted external storage medium or if the external storage is
11420      * emulated.
11421      */
11422     private boolean isExternalMediaAvailable() {
11423         return mMediaMounted || Environment.isExternalStorageEmulated();
11424     }
11425
11426     @Override
11427     public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11428         // writer
11429         synchronized (mPackages) {
11430             if (!isExternalMediaAvailable()) {
11431                 // If the external storage is no longer mounted at this point,
11432                 // the caller may not have been able to delete all of this
11433                 // packages files and can not delete any more.  Bail.
11434                 return null;
11435             }
11436             final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11437             if (lastPackage != null) {
11438                 pkgs.remove(lastPackage);
11439             }
11440             if (pkgs.size() > 0) {
11441                 return pkgs.get(0);
11442             }
11443         }
11444         return null;
11445     }
11446
11447     void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11448         final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11449                 userId, andCode ? 1 : 0, packageName);
11450         if (mSystemReady) {
11451             msg.sendToTarget();
11452         } else {
11453             if (mPostSystemReadyMessages == null) {
11454                 mPostSystemReadyMessages = new ArrayList<>();
11455             }
11456             mPostSystemReadyMessages.add(msg);
11457         }
11458     }
11459
11460     void startCleaningPackages() {
11461         // reader
11462         if (!isExternalMediaAvailable()) {
11463             return;
11464         }
11465         synchronized (mPackages) {
11466             if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11467                 return;
11468             }
11469         }
11470         Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11471         intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11472         IActivityManager am = ActivityManagerNative.getDefault();
11473         if (am != null) {
11474             try {
11475                 am.startService(null, intent, null, mContext.getOpPackageName(),
11476                         UserHandle.USER_SYSTEM);
11477             } catch (RemoteException e) {
11478             }
11479         }
11480     }
11481
11482     @Override
11483     public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11484             int installFlags, String installerPackageName, int userId) {
11485         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11486
11487         final int callingUid = Binder.getCallingUid();
11488         enforceCrossUserPermission(callingUid, userId,
11489                 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11490
11491         if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11492             try {
11493                 if (observer != null) {
11494                     observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11495                 }
11496             } catch (RemoteException re) {
11497             }
11498             return;
11499         }
11500
11501         if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11502             installFlags |= PackageManager.INSTALL_FROM_ADB;
11503
11504         } else {
11505             // Caller holds INSTALL_PACKAGES permission, so we're less strict
11506             // about installerPackageName.
11507
11508             installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11509             installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11510         }
11511
11512         UserHandle user;
11513         if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11514             user = UserHandle.ALL;
11515         } else {
11516             user = new UserHandle(userId);
11517         }
11518
11519         // Only system components can circumvent runtime permissions when installing.
11520         if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11521                 && mContext.checkCallingOrSelfPermission(Manifest.permission
11522                 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11523             throw new SecurityException("You need the "
11524                     + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11525                     + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11526         }
11527
11528         final File originFile = new File(originPath);
11529         final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11530
11531         final Message msg = mHandler.obtainMessage(INIT_COPY);
11532         final VerificationInfo verificationInfo = new VerificationInfo(
11533                 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11534         final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11535                 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11536                 null /*packageAbiOverride*/, null /*grantedPermissions*/,
11537                 null /*certificates*/);
11538         params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11539         msg.obj = params;
11540
11541         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11542                 System.identityHashCode(msg.obj));
11543         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11544                 System.identityHashCode(msg.obj));
11545
11546         mHandler.sendMessage(msg);
11547     }
11548
11549     void installStage(String packageName, File stagedDir, String stagedCid,
11550             IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11551             String installerPackageName, int installerUid, UserHandle user,
11552             Certificate[][] certificates) {
11553         if (DEBUG_EPHEMERAL) {
11554             if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11555                 Slog.d(TAG, "Ephemeral install of " + packageName);
11556             }
11557         }
11558         final VerificationInfo verificationInfo = new VerificationInfo(
11559                 sessionParams.originatingUri, sessionParams.referrerUri,
11560                 sessionParams.originatingUid, installerUid);
11561
11562         final OriginInfo origin;
11563         if (stagedDir != null) {
11564             origin = OriginInfo.fromStagedFile(stagedDir);
11565         } else {
11566             origin = OriginInfo.fromStagedContainer(stagedCid);
11567         }
11568
11569         final Message msg = mHandler.obtainMessage(INIT_COPY);
11570         final InstallParams params = new InstallParams(origin, null, observer,
11571                 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11572                 verificationInfo, user, sessionParams.abiOverride,
11573                 sessionParams.grantedRuntimePermissions, certificates);
11574         params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11575         msg.obj = params;
11576
11577         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11578                 System.identityHashCode(msg.obj));
11579         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11580                 System.identityHashCode(msg.obj));
11581
11582         mHandler.sendMessage(msg);
11583     }
11584
11585     private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11586             int userId) {
11587         final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11588         sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11589     }
11590
11591     private void sendPackageAddedForUser(String packageName, boolean isSystem,
11592             int appId, int userId) {
11593         Bundle extras = new Bundle(1);
11594         extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11595
11596         sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11597                 packageName, extras, 0, null, null, new int[] {userId});
11598         try {
11599             IActivityManager am = ActivityManagerNative.getDefault();
11600             if (isSystem && am.isUserRunning(userId, 0)) {
11601                 // The just-installed/enabled app is bundled on the system, so presumed
11602                 // to be able to run automatically without needing an explicit launch.
11603                 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11604                 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11605                         .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11606                         .setPackage(packageName);
11607                 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11608                         android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11609             }
11610         } catch (RemoteException e) {
11611             // shouldn't happen
11612             Slog.w(TAG, "Unable to bootstrap installed package", e);
11613         }
11614     }
11615
11616     @Override
11617     public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11618             int userId) {
11619         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11620         PackageSetting pkgSetting;
11621         final int uid = Binder.getCallingUid();
11622         enforceCrossUserPermission(uid, userId,
11623                 true /* requireFullPermission */, true /* checkShell */,
11624                 "setApplicationHiddenSetting for user " + userId);
11625
11626         if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11627             Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11628             return false;
11629         }
11630
11631         long callingId = Binder.clearCallingIdentity();
11632         try {
11633             boolean sendAdded = false;
11634             boolean sendRemoved = false;
11635             // writer
11636             synchronized (mPackages) {
11637                 pkgSetting = mSettings.mPackages.get(packageName);
11638                 if (pkgSetting == null) {
11639                     return false;
11640                 }
11641                 if (pkgSetting.getHidden(userId) != hidden) {
11642                     pkgSetting.setHidden(hidden, userId);
11643                     mSettings.writePackageRestrictionsLPr(userId);
11644                     if (hidden) {
11645                         sendRemoved = true;
11646                     } else {
11647                         sendAdded = true;
11648                     }
11649                 }
11650             }
11651             if (sendAdded) {
11652                 sendPackageAddedForUser(packageName, pkgSetting, userId);
11653                 return true;
11654             }
11655             if (sendRemoved) {
11656                 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11657                         "hiding pkg");
11658                 sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11659                 return true;
11660             }
11661         } finally {
11662             Binder.restoreCallingIdentity(callingId);
11663         }
11664         return false;
11665     }
11666
11667     private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11668             int userId) {
11669         final PackageRemovedInfo info = new PackageRemovedInfo();
11670         info.removedPackage = packageName;
11671         info.removedUsers = new int[] {userId};
11672         info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11673         info.sendPackageRemovedBroadcasts(true /*killApp*/);
11674     }
11675
11676     private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11677         if (pkgList.length > 0) {
11678             Bundle extras = new Bundle(1);
11679             extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11680
11681             sendPackageBroadcast(
11682                     suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11683                             : Intent.ACTION_PACKAGES_UNSUSPENDED,
11684                     null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11685                     new int[] {userId});
11686         }
11687     }
11688
11689     /**
11690      * Returns true if application is not found or there was an error. Otherwise it returns
11691      * the hidden state of the package for the given user.
11692      */
11693     @Override
11694     public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11695         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11696         enforceCrossUserPermission(Binder.getCallingUid(), userId,
11697                 true /* requireFullPermission */, false /* checkShell */,
11698                 "getApplicationHidden for user " + userId);
11699         PackageSetting pkgSetting;
11700         long callingId = Binder.clearCallingIdentity();
11701         try {
11702             // writer
11703             synchronized (mPackages) {
11704                 pkgSetting = mSettings.mPackages.get(packageName);
11705                 if (pkgSetting == null) {
11706                     return true;
11707                 }
11708                 return pkgSetting.getHidden(userId);
11709             }
11710         } finally {
11711             Binder.restoreCallingIdentity(callingId);
11712         }
11713     }
11714
11715     /**
11716      * @hide
11717      */
11718     @Override
11719     public int installExistingPackageAsUser(String packageName, int userId) {
11720         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11721                 null);
11722         PackageSetting pkgSetting;
11723         final int uid = Binder.getCallingUid();
11724         enforceCrossUserPermission(uid, userId,
11725                 true /* requireFullPermission */, true /* checkShell */,
11726                 "installExistingPackage for user " + userId);
11727         if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11728             return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11729         }
11730
11731         long callingId = Binder.clearCallingIdentity();
11732         try {
11733             boolean installed = false;
11734
11735             // writer
11736             synchronized (mPackages) {
11737                 pkgSetting = mSettings.mPackages.get(packageName);
11738                 if (pkgSetting == null) {
11739                     return PackageManager.INSTALL_FAILED_INVALID_URI;
11740                 }
11741                 if (!pkgSetting.getInstalled(userId)) {
11742                     pkgSetting.setInstalled(true, userId);
11743                     pkgSetting.setHidden(false, userId);
11744                     mSettings.writePackageRestrictionsLPr(userId);
11745                     installed = true;
11746                 }
11747             }
11748
11749             if (installed) {
11750                 if (pkgSetting.pkg != null) {
11751                     synchronized (mInstallLock) {
11752                         // We don't need to freeze for a brand new install
11753                         prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11754                     }
11755                 }
11756                 sendPackageAddedForUser(packageName, pkgSetting, userId);
11757             }
11758         } finally {
11759             Binder.restoreCallingIdentity(callingId);
11760         }
11761
11762         return PackageManager.INSTALL_SUCCEEDED;
11763     }
11764
11765     boolean isUserRestricted(int userId, String restrictionKey) {
11766         Bundle restrictions = sUserManager.getUserRestrictions(userId);
11767         if (restrictions.getBoolean(restrictionKey, false)) {
11768             Log.w(TAG, "User is restricted: " + restrictionKey);
11769             return true;
11770         }
11771         return false;
11772     }
11773
11774     @Override
11775     public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11776             int userId) {
11777         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11778         enforceCrossUserPermission(Binder.getCallingUid(), userId,
11779                 true /* requireFullPermission */, true /* checkShell */,
11780                 "setPackagesSuspended for user " + userId);
11781
11782         if (ArrayUtils.isEmpty(packageNames)) {
11783             return packageNames;
11784         }
11785
11786         // List of package names for whom the suspended state has changed.
11787         List<String> changedPackages = new ArrayList<>(packageNames.length);
11788         // List of package names for whom the suspended state is not set as requested in this
11789         // method.
11790         List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11791         long callingId = Binder.clearCallingIdentity();
11792         try {
11793             for (int i = 0; i < packageNames.length; i++) {
11794                 String packageName = packageNames[i];
11795                 boolean changed = false;
11796                 final int appId;
11797                 synchronized (mPackages) {
11798                     final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11799                     if (pkgSetting == null) {
11800                         Slog.w(TAG, "Could not find package setting for package \"" + packageName
11801                                 + "\". Skipping suspending/un-suspending.");
11802                         unactionedPackages.add(packageName);
11803                         continue;
11804                     }
11805                     appId = pkgSetting.appId;
11806                     if (pkgSetting.getSuspended(userId) != suspended) {
11807                         if (!canSuspendPackageForUserLocked(packageName, userId)) {
11808                             unactionedPackages.add(packageName);
11809                             continue;
11810                         }
11811                         pkgSetting.setSuspended(suspended, userId);
11812                         mSettings.writePackageRestrictionsLPr(userId);
11813                         changed = true;
11814                         changedPackages.add(packageName);
11815                     }
11816                 }
11817
11818                 if (changed && suspended) {
11819                     killApplication(packageName, UserHandle.getUid(userId, appId),
11820                             "suspending package");
11821                 }
11822             }
11823         } finally {
11824             Binder.restoreCallingIdentity(callingId);
11825         }
11826
11827         if (!changedPackages.isEmpty()) {
11828             sendPackagesSuspendedForUser(changedPackages.toArray(
11829                     new String[changedPackages.size()]), userId, suspended);
11830         }
11831
11832         return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11833     }
11834
11835     @Override
11836     public boolean isPackageSuspendedForUser(String packageName, int userId) {
11837         enforceCrossUserPermission(Binder.getCallingUid(), userId,
11838                 true /* requireFullPermission */, false /* checkShell */,
11839                 "isPackageSuspendedForUser for user " + userId);
11840         synchronized (mPackages) {
11841             final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11842             if (pkgSetting == null) {
11843                 throw new IllegalArgumentException("Unknown target package: " + packageName);
11844             }
11845             return pkgSetting.getSuspended(userId);
11846         }
11847     }
11848
11849     private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11850         if (isPackageDeviceAdmin(packageName, userId)) {
11851             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11852                     + "\": has an active device admin");
11853             return false;
11854         }
11855
11856         String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11857         if (packageName.equals(activeLauncherPackageName)) {
11858             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11859                     + "\": contains the active launcher");
11860             return false;
11861         }
11862
11863         if (packageName.equals(mRequiredInstallerPackage)) {
11864             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11865                     + "\": required for package installation");
11866             return false;
11867         }
11868
11869         if (packageName.equals(mRequiredVerifierPackage)) {
11870             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11871                     + "\": required for package verification");
11872             return false;
11873         }
11874
11875         if (packageName.equals(getDefaultDialerPackageName(userId))) {
11876             Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11877                     + "\": is the default dialer");
11878             return false;
11879         }
11880
11881         return true;
11882     }
11883
11884     private String getActiveLauncherPackageName(int userId) {
11885         Intent intent = new Intent(Intent.ACTION_MAIN);
11886         intent.addCategory(Intent.CATEGORY_HOME);
11887         ResolveInfo resolveInfo = resolveIntent(
11888                 intent,
11889                 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11890                 PackageManager.MATCH_DEFAULT_ONLY,
11891                 userId);
11892
11893         return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11894     }
11895
11896     private String getDefaultDialerPackageName(int userId) {
11897         synchronized (mPackages) {
11898             return mSettings.getDefaultDialerPackageNameLPw(userId);
11899         }
11900     }
11901
11902     @Override
11903     public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11904         mContext.enforceCallingOrSelfPermission(
11905                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11906                 "Only package verification agents can verify applications");
11907
11908         final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11909         final PackageVerificationResponse response = new PackageVerificationResponse(
11910                 verificationCode, Binder.getCallingUid());
11911         msg.arg1 = id;
11912         msg.obj = response;
11913         mHandler.sendMessage(msg);
11914     }
11915
11916     @Override
11917     public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11918             long millisecondsToDelay) {
11919         mContext.enforceCallingOrSelfPermission(
11920                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11921                 "Only package verification agents can extend verification timeouts");
11922
11923         final PackageVerificationState state = mPendingVerification.get(id);
11924         final PackageVerificationResponse response = new PackageVerificationResponse(
11925                 verificationCodeAtTimeout, Binder.getCallingUid());
11926
11927         if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11928             millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11929         }
11930         if (millisecondsToDelay < 0) {
11931             millisecondsToDelay = 0;
11932         }
11933         if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11934                 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11935             verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11936         }
11937
11938         if ((state != null) && !state.timeoutExtended()) {
11939             state.extendTimeout();
11940
11941             final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11942             msg.arg1 = id;
11943             msg.obj = response;
11944             mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11945         }
11946     }
11947
11948     private void broadcastPackageVerified(int verificationId, Uri packageUri,
11949             int verificationCode, UserHandle user) {
11950         final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11951         intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11952         intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11953         intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11954         intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11955
11956         mContext.sendBroadcastAsUser(intent, user,
11957                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11958     }
11959
11960     private ComponentName matchComponentForVerifier(String packageName,
11961             List<ResolveInfo> receivers) {
11962         ActivityInfo targetReceiver = null;
11963
11964         final int NR = receivers.size();
11965         for (int i = 0; i < NR; i++) {
11966             final ResolveInfo info = receivers.get(i);
11967             if (info.activityInfo == null) {
11968                 continue;
11969             }
11970
11971             if (packageName.equals(info.activityInfo.packageName)) {
11972                 targetReceiver = info.activityInfo;
11973                 break;
11974             }
11975         }
11976
11977         if (targetReceiver == null) {
11978             return null;
11979         }
11980
11981         return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11982     }
11983
11984     private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11985             List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11986         if (pkgInfo.verifiers.length == 0) {
11987             return null;
11988         }
11989
11990         final int N = pkgInfo.verifiers.length;
11991         final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11992         for (int i = 0; i < N; i++) {
11993             final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11994
11995             final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11996                     receivers);
11997             if (comp == null) {
11998                 continue;
11999             }
12000
12001             final int verifierUid = getUidForVerifier(verifierInfo);
12002             if (verifierUid == -1) {
12003                 continue;
12004             }
12005
12006             if (DEBUG_VERIFY) {
12007                 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12008                         + " with the correct signature");
12009             }
12010             sufficientVerifiers.add(comp);
12011             verificationState.addSufficientVerifier(verifierUid);
12012         }
12013
12014         return sufficientVerifiers;
12015     }
12016
12017     private int getUidForVerifier(VerifierInfo verifierInfo) {
12018         synchronized (mPackages) {
12019             final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12020             if (pkg == null) {
12021                 return -1;
12022             } else if (pkg.mSignatures.length != 1) {
12023                 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12024                         + " has more than one signature; ignoring");
12025                 return -1;
12026             }
12027
12028             /*
12029              * If the public key of the package's signature does not match
12030              * our expected public key, then this is a different package and
12031              * we should skip.
12032              */
12033
12034             final byte[] expectedPublicKey;
12035             try {
12036                 final Signature verifierSig = pkg.mSignatures[0];
12037                 final PublicKey publicKey = verifierSig.getPublicKey();
12038                 expectedPublicKey = publicKey.getEncoded();
12039             } catch (CertificateException e) {
12040                 return -1;
12041             }
12042
12043             final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12044
12045             if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12046                 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12047                         + " does not have the expected public key; ignoring");
12048                 return -1;
12049             }
12050
12051             return pkg.applicationInfo.uid;
12052         }
12053     }
12054
12055     @Override
12056     public void finishPackageInstall(int token, boolean didLaunch) {
12057         enforceSystemOrRoot("Only the system is allowed to finish installs");
12058
12059         if (DEBUG_INSTALL) {
12060             Slog.v(TAG, "BM finishing package install for " + token);
12061         }
12062         Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12063
12064         final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12065         mHandler.sendMessage(msg);
12066     }
12067
12068     /**
12069      * Get the verification agent timeout.
12070      *
12071      * @return verification timeout in milliseconds
12072      */
12073     private long getVerificationTimeout() {
12074         return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12075                 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12076                 DEFAULT_VERIFICATION_TIMEOUT);
12077     }
12078
12079     /**
12080      * Get the default verification agent response code.
12081      *
12082      * @return default verification response code
12083      */
12084     private int getDefaultVerificationResponse() {
12085         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12086                 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12087                 DEFAULT_VERIFICATION_RESPONSE);
12088     }
12089
12090     /**
12091      * Check whether or not package verification has been enabled.
12092      *
12093      * @return true if verification should be performed
12094      */
12095     private boolean isVerificationEnabled(int userId, int installFlags) {
12096         if (!DEFAULT_VERIFY_ENABLE) {
12097             return false;
12098         }
12099         // Ephemeral apps don't get the full verification treatment
12100         if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12101             if (DEBUG_EPHEMERAL) {
12102                 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12103             }
12104             return false;
12105         }
12106
12107         boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12108
12109         // Check if installing from ADB
12110         if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12111             // Do not run verification in a test harness environment
12112             if (ActivityManager.isRunningInTestHarness()) {
12113                 return false;
12114             }
12115             if (ensureVerifyAppsEnabled) {
12116                 return true;
12117             }
12118             // Check if the developer does not want package verification for ADB installs
12119             if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12120                     android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12121                 return false;
12122             }
12123         }
12124
12125         if (ensureVerifyAppsEnabled) {
12126             return true;
12127         }
12128
12129         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12130                 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12131     }
12132
12133     @Override
12134     public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12135             throws RemoteException {
12136         mContext.enforceCallingOrSelfPermission(
12137                 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12138                 "Only intentfilter verification agents can verify applications");
12139
12140         final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12141         final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12142                 Binder.getCallingUid(), verificationCode, failedDomains);
12143         msg.arg1 = id;
12144         msg.obj = response;
12145         mHandler.sendMessage(msg);
12146     }
12147
12148     @Override
12149     public int getIntentVerificationStatus(String packageName, int userId) {
12150         synchronized (mPackages) {
12151             return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12152         }
12153     }
12154
12155     @Override
12156     public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12157         mContext.enforceCallingOrSelfPermission(
12158                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12159
12160         boolean result = false;
12161         synchronized (mPackages) {
12162             result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12163         }
12164         if (result) {
12165             scheduleWritePackageRestrictionsLocked(userId);
12166         }
12167         return result;
12168     }
12169
12170     @Override
12171     public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12172             String packageName) {
12173         synchronized (mPackages) {
12174             return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12175         }
12176     }
12177
12178     @Override
12179     public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12180         if (TextUtils.isEmpty(packageName)) {
12181             return ParceledListSlice.emptyList();
12182         }
12183         synchronized (mPackages) {
12184             PackageParser.Package pkg = mPackages.get(packageName);
12185             if (pkg == null || pkg.activities == null) {
12186                 return ParceledListSlice.emptyList();
12187             }
12188             final int count = pkg.activities.size();
12189             ArrayList<IntentFilter> result = new ArrayList<>();
12190             for (int n=0; n<count; n++) {
12191                 PackageParser.Activity activity = pkg.activities.get(n);
12192                 if (activity.intents != null && activity.intents.size() > 0) {
12193                     result.addAll(activity.intents);
12194                 }
12195             }
12196             return new ParceledListSlice<>(result);
12197         }
12198     }
12199
12200     @Override
12201     public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12202         mContext.enforceCallingOrSelfPermission(
12203                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12204
12205         synchronized (mPackages) {
12206             boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12207             if (packageName != null) {
12208                 result |= updateIntentVerificationStatus(packageName,
12209                         PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12210                         userId);
12211                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12212                         packageName, userId);
12213             }
12214             return result;
12215         }
12216     }
12217
12218     @Override
12219     public String getDefaultBrowserPackageName(int userId) {
12220         synchronized (mPackages) {
12221             return mSettings.getDefaultBrowserPackageNameLPw(userId);
12222         }
12223     }
12224
12225     /**
12226      * Get the "allow unknown sources" setting.
12227      *
12228      * @return the current "allow unknown sources" setting
12229      */
12230     private int getUnknownSourcesSettings() {
12231         return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12232                 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12233                 -1);
12234     }
12235
12236     @Override
12237     public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12238         final int uid = Binder.getCallingUid();
12239         // writer
12240         synchronized (mPackages) {
12241             PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12242             if (targetPackageSetting == null) {
12243                 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12244             }
12245
12246             PackageSetting installerPackageSetting;
12247             if (installerPackageName != null) {
12248                 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12249                 if (installerPackageSetting == null) {
12250                     throw new IllegalArgumentException("Unknown installer package: "
12251                             + installerPackageName);
12252                 }
12253             } else {
12254                 installerPackageSetting = null;
12255             }
12256
12257             Signature[] callerSignature;
12258             Object obj = mSettings.getUserIdLPr(uid);
12259             if (obj != null) {
12260                 if (obj instanceof SharedUserSetting) {
12261                     callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12262                 } else if (obj instanceof PackageSetting) {
12263                     callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12264                 } else {
12265                     throw new SecurityException("Bad object " + obj + " for uid " + uid);
12266                 }
12267             } else {
12268                 throw new SecurityException("Unknown calling UID: " + uid);
12269             }
12270
12271             // Verify: can't set installerPackageName to a package that is
12272             // not signed with the same cert as the caller.
12273             if (installerPackageSetting != null) {
12274                 if (compareSignatures(callerSignature,
12275                         installerPackageSetting.signatures.mSignatures)
12276                         != PackageManager.SIGNATURE_MATCH) {
12277                     throw new SecurityException(
12278                             "Caller does not have same cert as new installer package "
12279                             + installerPackageName);
12280                 }
12281             }
12282
12283             // Verify: if target already has an installer package, it must
12284             // be signed with the same cert as the caller.
12285             if (targetPackageSetting.installerPackageName != null) {
12286                 PackageSetting setting = mSettings.mPackages.get(
12287                         targetPackageSetting.installerPackageName);
12288                 // If the currently set package isn't valid, then it's always
12289                 // okay to change it.
12290                 if (setting != null) {
12291                     if (compareSignatures(callerSignature,
12292                             setting.signatures.mSignatures)
12293                             != PackageManager.SIGNATURE_MATCH) {
12294                         throw new SecurityException(
12295                                 "Caller does not have same cert as old installer package "
12296                                 + targetPackageSetting.installerPackageName);
12297                     }
12298                 }
12299             }
12300
12301             // Okay!
12302             targetPackageSetting.installerPackageName = installerPackageName;
12303             if (installerPackageName != null) {
12304                 mSettings.mInstallerPackages.add(installerPackageName);
12305             }
12306             scheduleWriteSettingsLocked();
12307         }
12308     }
12309
12310     private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12311         // Queue up an async operation since the package installation may take a little while.
12312         mHandler.post(new Runnable() {
12313             public void run() {
12314                 mHandler.removeCallbacks(this);
12315                  // Result object to be returned
12316                 PackageInstalledInfo res = new PackageInstalledInfo();
12317                 res.setReturnCode(currentStatus);
12318                 res.uid = -1;
12319                 res.pkg = null;
12320                 res.removedInfo = null;
12321                 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12322                     args.doPreInstall(res.returnCode);
12323                     synchronized (mInstallLock) {
12324                         installPackageTracedLI(args, res);
12325                     }
12326                     args.doPostInstall(res.returnCode, res.uid);
12327                 }
12328
12329                 // A restore should be performed at this point if (a) the install
12330                 // succeeded, (b) the operation is not an update, and (c) the new
12331                 // package has not opted out of backup participation.
12332                 final boolean update = res.removedInfo != null
12333                         && res.removedInfo.removedPackage != null;
12334                 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12335                 boolean doRestore = !update
12336                         && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12337
12338                 // Set up the post-install work request bookkeeping.  This will be used
12339                 // and cleaned up by the post-install event handling regardless of whether
12340                 // there's a restore pass performed.  Token values are >= 1.
12341                 int token;
12342                 if (mNextInstallToken < 0) mNextInstallToken = 1;
12343                 token = mNextInstallToken++;
12344
12345                 PostInstallData data = new PostInstallData(args, res);
12346                 mRunningInstalls.put(token, data);
12347                 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12348
12349                 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12350                     // Pass responsibility to the Backup Manager.  It will perform a
12351                     // restore if appropriate, then pass responsibility back to the
12352                     // Package Manager to run the post-install observer callbacks
12353                     // and broadcasts.
12354                     IBackupManager bm = IBackupManager.Stub.asInterface(
12355                             ServiceManager.getService(Context.BACKUP_SERVICE));
12356                     if (bm != null) {
12357                         if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12358                                 + " to BM for possible restore");
12359                         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12360                         try {
12361                             // TODO: http://b/22388012
12362                             if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12363                                 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12364                             } else {
12365                                 doRestore = false;
12366                             }
12367                         } catch (RemoteException e) {
12368                             // can't happen; the backup manager is local
12369                         } catch (Exception e) {
12370                             Slog.e(TAG, "Exception trying to enqueue restore", e);
12371                             doRestore = false;
12372                         }
12373                     } else {
12374                         Slog.e(TAG, "Backup Manager not found!");
12375                         doRestore = false;
12376                     }
12377                 }
12378
12379                 if (!doRestore) {
12380                     // No restore possible, or the Backup Manager was mysteriously not
12381                     // available -- just fire the post-install work request directly.
12382                     if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12383
12384                     Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12385
12386                     Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12387                     mHandler.sendMessage(msg);
12388                 }
12389             }
12390         });
12391     }
12392
12393     /**
12394      * Callback from PackageSettings whenever an app is first transitioned out of the
12395      * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12396      * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12397      * here whether the app is the target of an ongoing install, and only send the
12398      * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12399      * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12400      * handling.
12401      */
12402     void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12403         // Serialize this with the rest of the install-process message chain.  In the
12404         // restore-at-install case, this Runnable will necessarily run before the
12405         // POST_INSTALL message is processed, so the contents of mRunningInstalls
12406         // are coherent.  In the non-restore case, the app has already completed install
12407         // and been launched through some other means, so it is not in a problematic
12408         // state for observers to see the FIRST_LAUNCH signal.
12409         mHandler.post(new Runnable() {
12410             @Override
12411             public void run() {
12412                 for (int i = 0; i < mRunningInstalls.size(); i++) {
12413                     final PostInstallData data = mRunningInstalls.valueAt(i);
12414                     if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12415                         // right package; but is it for the right user?
12416                         for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12417                             if (userId == data.res.newUsers[uIndex]) {
12418                                 if (DEBUG_BACKUP) {
12419                                     Slog.i(TAG, "Package " + pkgName
12420                                             + " being restored so deferring FIRST_LAUNCH");
12421                                 }
12422                                 return;
12423                             }
12424                         }
12425                     }
12426                 }
12427                 // didn't find it, so not being restored
12428                 if (DEBUG_BACKUP) {
12429                     Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12430                 }
12431                 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12432             }
12433         });
12434     }
12435
12436     private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12437         sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12438                 installerPkg, null, userIds);
12439     }
12440
12441     private abstract class HandlerParams {
12442         private static final int MAX_RETRIES = 4;
12443
12444         /**
12445          * Number of times startCopy() has been attempted and had a non-fatal
12446          * error.
12447          */
12448         private int mRetries = 0;
12449
12450         /** User handle for the user requesting the information or installation. */
12451         private final UserHandle mUser;
12452         String traceMethod;
12453         int traceCookie;
12454
12455         HandlerParams(UserHandle user) {
12456             mUser = user;
12457         }
12458
12459         UserHandle getUser() {
12460             return mUser;
12461         }
12462
12463         HandlerParams setTraceMethod(String traceMethod) {
12464             this.traceMethod = traceMethod;
12465             return this;
12466         }
12467
12468         HandlerParams setTraceCookie(int traceCookie) {
12469             this.traceCookie = traceCookie;
12470             return this;
12471         }
12472
12473         final boolean startCopy() {
12474             boolean res;
12475             try {
12476                 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12477
12478                 if (++mRetries > MAX_RETRIES) {
12479                     Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12480                     mHandler.sendEmptyMessage(MCS_GIVE_UP);
12481                     handleServiceError();
12482                     return false;
12483                 } else {
12484                     handleStartCopy();
12485                     res = true;
12486                 }
12487             } catch (RemoteException e) {
12488                 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12489                 mHandler.sendEmptyMessage(MCS_RECONNECT);
12490                 res = false;
12491             }
12492             handleReturnCode();
12493             return res;
12494         }
12495
12496         final void serviceError() {
12497             if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12498             handleServiceError();
12499             handleReturnCode();
12500         }
12501
12502         abstract void handleStartCopy() throws RemoteException;
12503         abstract void handleServiceError();
12504         abstract void handleReturnCode();
12505     }
12506
12507     class MeasureParams extends HandlerParams {
12508         private final PackageStats mStats;
12509         private boolean mSuccess;
12510
12511         private final IPackageStatsObserver mObserver;
12512
12513         public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12514             super(new UserHandle(stats.userHandle));
12515             mObserver = observer;
12516             mStats = stats;
12517         }
12518
12519         @Override
12520         public String toString() {
12521             return "MeasureParams{"
12522                 + Integer.toHexString(System.identityHashCode(this))
12523                 + " " + mStats.packageName + "}";
12524         }
12525
12526         @Override
12527         void handleStartCopy() throws RemoteException {
12528             synchronized (mInstallLock) {
12529                 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12530             }
12531
12532             if (mSuccess) {
12533                 boolean mounted = false;
12534                 try {
12535                     final String status = Environment.getExternalStorageState();
12536                     mounted = (Environment.MEDIA_MOUNTED.equals(status)
12537                             || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12538                 } catch (Exception e) {
12539                 }
12540
12541                 if (mounted) {
12542                     final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12543
12544                     mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12545                             userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12546
12547                     mStats.externalDataSize = calculateDirectorySize(mContainerService,
12548                             userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12549
12550                     // Always subtract cache size, since it's a subdirectory
12551                     mStats.externalDataSize -= mStats.externalCacheSize;
12552
12553                     mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12554                             userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12555
12556                     mStats.externalObbSize = calculateDirectorySize(mContainerService,
12557                             userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12558                 }
12559             }
12560         }
12561
12562         @Override
12563         void handleReturnCode() {
12564             if (mObserver != null) {
12565                 try {
12566                     mObserver.onGetStatsCompleted(mStats, mSuccess);
12567                 } catch (RemoteException e) {
12568                     Slog.i(TAG, "Observer no longer exists.");
12569                 }
12570             }
12571         }
12572
12573         @Override
12574         void handleServiceError() {
12575             Slog.e(TAG, "Could not measure application " + mStats.packageName
12576                             + " external storage");
12577         }
12578     }
12579
12580     private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12581             throws RemoteException {
12582         long result = 0;
12583         for (File path : paths) {
12584             result += mcs.calculateDirectorySize(path.getAbsolutePath());
12585         }
12586         return result;
12587     }
12588
12589     private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12590         for (File path : paths) {
12591             try {
12592                 mcs.clearDirectory(path.getAbsolutePath());
12593             } catch (RemoteException e) {
12594             }
12595         }
12596     }
12597
12598     static class OriginInfo {
12599         /**
12600          * Location where install is coming from, before it has been
12601          * copied/renamed into place. This could be a single monolithic APK
12602          * file, or a cluster directory. This location may be untrusted.
12603          */
12604         final File file;
12605         final String cid;
12606
12607         /**
12608          * Flag indicating that {@link #file} or {@link #cid} has already been
12609          * staged, meaning downstream users don't need to defensively copy the
12610          * contents.
12611          */
12612         final boolean staged;
12613
12614         /**
12615          * Flag indicating that {@link #file} or {@link #cid} is an already
12616          * installed app that is being moved.
12617          */
12618         final boolean existing;
12619
12620         final String resolvedPath;
12621         final File resolvedFile;
12622
12623         static OriginInfo fromNothing() {
12624             return new OriginInfo(null, null, false, false);
12625         }
12626
12627         static OriginInfo fromUntrustedFile(File file) {
12628             return new OriginInfo(file, null, false, false);
12629         }
12630
12631         static OriginInfo fromExistingFile(File file) {
12632             return new OriginInfo(file, null, false, true);
12633         }
12634
12635         static OriginInfo fromStagedFile(File file) {
12636             return new OriginInfo(file, null, true, false);
12637         }
12638
12639         static OriginInfo fromStagedContainer(String cid) {
12640             return new OriginInfo(null, cid, true, false);
12641         }
12642
12643         private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12644             this.file = file;
12645             this.cid = cid;
12646             this.staged = staged;
12647             this.existing = existing;
12648
12649             if (cid != null) {
12650                 resolvedPath = PackageHelper.getSdDir(cid);
12651                 resolvedFile = new File(resolvedPath);
12652             } else if (file != null) {
12653                 resolvedPath = file.getAbsolutePath();
12654                 resolvedFile = file;
12655             } else {
12656                 resolvedPath = null;
12657                 resolvedFile = null;
12658             }
12659         }
12660     }
12661
12662     static class MoveInfo {
12663         final int moveId;
12664         final String fromUuid;
12665         final String toUuid;
12666         final String packageName;
12667         final String dataAppName;
12668         final int appId;
12669         final String seinfo;
12670         final int targetSdkVersion;
12671
12672         public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12673                 String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12674             this.moveId = moveId;
12675             this.fromUuid = fromUuid;
12676             this.toUuid = toUuid;
12677             this.packageName = packageName;
12678             this.dataAppName = dataAppName;
12679             this.appId = appId;
12680             this.seinfo = seinfo;
12681             this.targetSdkVersion = targetSdkVersion;
12682         }
12683     }
12684
12685     static class VerificationInfo {
12686         /** A constant used to indicate that a uid value is not present. */
12687         public static final int NO_UID = -1;
12688
12689         /** URI referencing where the package was downloaded from. */
12690         final Uri originatingUri;
12691
12692         /** HTTP referrer URI associated with the originatingURI. */
12693         final Uri referrer;
12694
12695         /** UID of the application that the install request originated from. */
12696         final int originatingUid;
12697
12698         /** UID of application requesting the install */
12699         final int installerUid;
12700
12701         VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12702             this.originatingUri = originatingUri;
12703             this.referrer = referrer;
12704             this.originatingUid = originatingUid;
12705             this.installerUid = installerUid;
12706         }
12707     }
12708
12709     class InstallParams extends HandlerParams {
12710         final OriginInfo origin;
12711         final MoveInfo move;
12712         final IPackageInstallObserver2 observer;
12713         int installFlags;
12714         final String installerPackageName;
12715         final String volumeUuid;
12716         private InstallArgs mArgs;
12717         private int mRet;
12718         final String packageAbiOverride;
12719         final String[] grantedRuntimePermissions;
12720         final VerificationInfo verificationInfo;
12721         final Certificate[][] certificates;
12722
12723         InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12724                 int installFlags, String installerPackageName, String volumeUuid,
12725                 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12726                 String[] grantedPermissions, Certificate[][] certificates) {
12727             super(user);
12728             this.origin = origin;
12729             this.move = move;
12730             this.observer = observer;
12731             this.installFlags = installFlags;
12732             this.installerPackageName = installerPackageName;
12733             this.volumeUuid = volumeUuid;
12734             this.verificationInfo = verificationInfo;
12735             this.packageAbiOverride = packageAbiOverride;
12736             this.grantedRuntimePermissions = grantedPermissions;
12737             this.certificates = certificates;
12738         }
12739
12740         @Override
12741         public String toString() {
12742             return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12743                     + " file=" + origin.file + " cid=" + origin.cid + "}";
12744         }
12745
12746         private int installLocationPolicy(PackageInfoLite pkgLite) {
12747             String packageName = pkgLite.packageName;
12748             int installLocation = pkgLite.installLocation;
12749             boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12750             // reader
12751             synchronized (mPackages) {
12752                 // Currently installed package which the new package is attempting to replace or
12753                 // null if no such package is installed.
12754                 PackageParser.Package installedPkg = mPackages.get(packageName);
12755                 // Package which currently owns the data which the new package will own if installed.
12756                 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12757                 // will be null whereas dataOwnerPkg will contain information about the package
12758                 // which was uninstalled while keeping its data.
12759                 PackageParser.Package dataOwnerPkg = installedPkg;
12760                 if (dataOwnerPkg  == null) {
12761                     PackageSetting ps = mSettings.mPackages.get(packageName);
12762                     if (ps != null) {
12763                         dataOwnerPkg = ps.pkg;
12764                     }
12765                 }
12766
12767                 if (dataOwnerPkg != null) {
12768                     // If installed, the package will get access to data left on the device by its
12769                     // predecessor. As a security measure, this is permited only if this is not a
12770                     // version downgrade or if the predecessor package is marked as debuggable and
12771                     // a downgrade is explicitly requested.
12772                     //
12773                     // On debuggable platform builds, downgrades are permitted even for
12774                     // non-debuggable packages to make testing easier. Debuggable platform builds do
12775                     // not offer security guarantees and thus it's OK to disable some security
12776                     // mechanisms to make debugging/testing easier on those builds. However, even on
12777                     // debuggable builds downgrades of packages are permitted only if requested via
12778                     // installFlags. This is because we aim to keep the behavior of debuggable
12779                     // platform builds as close as possible to the behavior of non-debuggable
12780                     // platform builds.
12781                     final boolean downgradeRequested =
12782                             (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12783                     final boolean packageDebuggable =
12784                                 (dataOwnerPkg.applicationInfo.flags
12785                                         & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12786                     final boolean downgradePermitted =
12787                             (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12788                     if (!downgradePermitted) {
12789                         try {
12790                             checkDowngrade(dataOwnerPkg, pkgLite);
12791                         } catch (PackageManagerException e) {
12792                             Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12793                             return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12794                         }
12795                     }
12796                 }
12797
12798                 if (installedPkg != null) {
12799                     if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12800                         // Check for updated system application.
12801                         if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12802                             if (onSd) {
12803                                 Slog.w(TAG, "Cannot install update to system app on sdcard");
12804                                 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12805                             }
12806                             return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12807                         } else {
12808                             if (onSd) {
12809                                 // Install flag overrides everything.
12810                                 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12811                             }
12812                             // If current upgrade specifies particular preference
12813                             if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12814                                 // Application explicitly specified internal.
12815                                 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12816                             } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12817                                 // App explictly prefers external. Let policy decide
12818                             } else {
12819                                 // Prefer previous location
12820                                 if (isExternal(installedPkg)) {
12821                                     return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12822                                 }
12823                                 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12824                             }
12825                         }
12826                     } else {
12827                         // Invalid install. Return error code
12828                         return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12829                     }
12830                 }
12831             }
12832             // All the special cases have been taken care of.
12833             // Return result based on recommended install location.
12834             if (onSd) {
12835                 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12836             }
12837             return pkgLite.recommendedInstallLocation;
12838         }
12839
12840         /*
12841          * Invoke remote method to get package information and install
12842          * location values. Override install location based on default
12843          * policy if needed and then create install arguments based
12844          * on the install location.
12845          */
12846         public void handleStartCopy() throws RemoteException {
12847             int ret = PackageManager.INSTALL_SUCCEEDED;
12848
12849             // If we're already staged, we've firmly committed to an install location
12850             if (origin.staged) {
12851                 if (origin.file != null) {
12852                     installFlags |= PackageManager.INSTALL_INTERNAL;
12853                     installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12854                 } else if (origin.cid != null) {
12855                     installFlags |= PackageManager.INSTALL_EXTERNAL;
12856                     installFlags &= ~PackageManager.INSTALL_INTERNAL;
12857                 } else {
12858                     throw new IllegalStateException("Invalid stage location");
12859                 }
12860             }
12861
12862             final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12863             final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12864             final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12865             PackageInfoLite pkgLite = null;
12866
12867             if (onInt && onSd) {
12868                 // Check if both bits are set.
12869                 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12870                 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12871             } else if (onSd && ephemeral) {
12872                 Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12873                 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12874             } else {
12875                 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12876                         packageAbiOverride);
12877
12878                 if (DEBUG_EPHEMERAL && ephemeral) {
12879                     Slog.v(TAG, "pkgLite for install: " + pkgLite);
12880                 }
12881
12882                 /*
12883                  * If we have too little free space, try to free cache
12884                  * before giving up.
12885                  */
12886                 if (!origin.staged && pkgLite.recommendedInstallLocation
12887                         == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12888                     // TODO: focus freeing disk space on the target device
12889                     final StorageManager storage = StorageManager.from(mContext);
12890                     final long lowThreshold = storage.getStorageLowBytes(
12891                             Environment.getDataDirectory());
12892
12893                     final long sizeBytes = mContainerService.calculateInstalledSize(
12894                             origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12895
12896                     try {
12897                         mInstaller.freeCache(null, sizeBytes + lowThreshold);
12898                         pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12899                                 installFlags, packageAbiOverride);
12900                     } catch (InstallerException e) {
12901                         Slog.w(TAG, "Failed to free cache", e);
12902                     }
12903
12904                     /*
12905                      * The cache free must have deleted the file we
12906                      * downloaded to install.
12907                      *
12908                      * TODO: fix the "freeCache" call to not delete
12909                      *       the file we care about.
12910                      */
12911                     if (pkgLite.recommendedInstallLocation
12912                             == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12913                         pkgLite.recommendedInstallLocation
12914                             = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12915                     }
12916                 }
12917             }
12918
12919             if (ret == PackageManager.INSTALL_SUCCEEDED) {
12920                 int loc = pkgLite.recommendedInstallLocation;
12921                 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12922                     ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12923                 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12924                     ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12925                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12926                     ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12927                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12928                     ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12929                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12930                     ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12931                 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12932                     ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12933                 } else {
12934                     // Override with defaults if needed.
12935                     loc = installLocationPolicy(pkgLite);
12936                     if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12937                         ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12938                     } else if (!onSd && !onInt) {
12939                         // Override install location with flags
12940                         if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12941                             // Set the flag to install on external media.
12942                             installFlags |= PackageManager.INSTALL_EXTERNAL;
12943                             installFlags &= ~PackageManager.INSTALL_INTERNAL;
12944                         } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12945                             if (DEBUG_EPHEMERAL) {
12946                                 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12947                             }
12948                             installFlags |= PackageManager.INSTALL_EPHEMERAL;
12949                             installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12950                                     |PackageManager.INSTALL_INTERNAL);
12951                         } else {
12952                             // Make sure the flag for installing on external
12953                             // media is unset
12954                             installFlags |= PackageManager.INSTALL_INTERNAL;
12955                             installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12956                         }
12957                     }
12958                 }
12959             }
12960
12961             final InstallArgs args = createInstallArgs(this);
12962             mArgs = args;
12963
12964             if (ret == PackageManager.INSTALL_SUCCEEDED) {
12965                 // TODO: http://b/22976637
12966                 // Apps installed for "all" users use the device owner to verify the app
12967                 UserHandle verifierUser = getUser();
12968                 if (verifierUser == UserHandle.ALL) {
12969                     verifierUser = UserHandle.SYSTEM;
12970                 }
12971
12972                 /*
12973                  * Determine if we have any installed package verifiers. If we
12974                  * do, then we'll defer to them to verify the packages.
12975                  */
12976                 final int requiredUid = mRequiredVerifierPackage == null ? -1
12977                         : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12978                                 verifierUser.getIdentifier());
12979                 if (!origin.existing && requiredUid != -1
12980                         && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12981                     final Intent verification = new Intent(
12982                             Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12983                     verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12984                     verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12985                             PACKAGE_MIME_TYPE);
12986                     verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12987
12988                     // Query all live verifiers based on current user state
12989                     final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12990                             PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12991
12992                     if (DEBUG_VERIFY) {
12993                         Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12994                                 + verification.toString() + " with " + pkgLite.verifiers.length
12995                                 + " optional verifiers");
12996                     }
12997
12998                     final int verificationId = mPendingVerificationToken++;
12999
13000                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13001
13002                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13003                             installerPackageName);
13004
13005                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13006                             installFlags);
13007
13008                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13009                             pkgLite.packageName);
13010
13011                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13012                             pkgLite.versionCode);
13013
13014                     if (verificationInfo != null) {
13015                         if (verificationInfo.originatingUri != null) {
13016                             verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13017                                     verificationInfo.originatingUri);
13018                         }
13019                         if (verificationInfo.referrer != null) {
13020                             verification.putExtra(Intent.EXTRA_REFERRER,
13021                                     verificationInfo.referrer);
13022                         }
13023                         if (verificationInfo.originatingUid >= 0) {
13024                             verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13025                                     verificationInfo.originatingUid);
13026                         }
13027                         if (verificationInfo.installerUid >= 0) {
13028                             verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13029                                     verificationInfo.installerUid);
13030                         }
13031                     }
13032
13033                     final PackageVerificationState verificationState = new PackageVerificationState(
13034                             requiredUid, args);
13035
13036                     mPendingVerification.append(verificationId, verificationState);
13037
13038                     final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13039                             receivers, verificationState);
13040
13041                     /*
13042                      * If any sufficient verifiers were listed in the package
13043                      * manifest, attempt to ask them.
13044                      */
13045                     if (sufficientVerifiers != null) {
13046                         final int N = sufficientVerifiers.size();
13047                         if (N == 0) {
13048                             Slog.i(TAG, "Additional verifiers required, but none installed.");
13049                             ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13050                         } else {
13051                             for (int i = 0; i < N; i++) {
13052                                 final ComponentName verifierComponent = sufficientVerifiers.get(i);
13053
13054                                 final Intent sufficientIntent = new Intent(verification);
13055                                 sufficientIntent.setComponent(verifierComponent);
13056                                 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13057                             }
13058                         }
13059                     }
13060
13061                     final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13062                             mRequiredVerifierPackage, receivers);
13063                     if (ret == PackageManager.INSTALL_SUCCEEDED
13064                             && mRequiredVerifierPackage != null) {
13065                         Trace.asyncTraceBegin(
13066                                 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13067                         /*
13068                          * Send the intent to the required verification agent,
13069                          * but only start the verification timeout after the
13070                          * target BroadcastReceivers have run.
13071                          */
13072                         verification.setComponent(requiredVerifierComponent);
13073                         mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13074                                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13075                                 new BroadcastReceiver() {
13076                                     @Override
13077                                     public void onReceive(Context context, Intent intent) {
13078                                         final Message msg = mHandler
13079                                                 .obtainMessage(CHECK_PENDING_VERIFICATION);
13080                                         msg.arg1 = verificationId;
13081                                         mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13082                                     }
13083                                 }, null, 0, null, null);
13084
13085                         /*
13086                          * We don't want the copy to proceed until verification
13087                          * succeeds, so null out this field.
13088                          */
13089                         mArgs = null;
13090                     }
13091                 } else {
13092                     /*
13093                      * No package verification is enabled, so immediately start
13094                      * the remote call to initiate copy using temporary file.
13095                      */
13096                     ret = args.copyApk(mContainerService, true);
13097                 }
13098             }
13099
13100             mRet = ret;
13101         }
13102
13103         @Override
13104         void handleReturnCode() {
13105             // If mArgs is null, then MCS couldn't be reached. When it
13106             // reconnects, it will try again to install. At that point, this
13107             // will succeed.
13108             if (mArgs != null) {
13109                 processPendingInstall(mArgs, mRet);
13110             }
13111         }
13112
13113         @Override
13114         void handleServiceError() {
13115             mArgs = createInstallArgs(this);
13116             mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13117         }
13118
13119         public boolean isForwardLocked() {
13120             return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13121         }
13122     }
13123
13124     /**
13125      * Used during creation of InstallArgs
13126      *
13127      * @param installFlags package installation flags
13128      * @return true if should be installed on external storage
13129      */
13130     private static boolean installOnExternalAsec(int installFlags) {
13131         if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13132             return false;
13133         }
13134         if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13135             return true;
13136         }
13137         return false;
13138     }
13139
13140     /**
13141      * Used during creation of InstallArgs
13142      *
13143      * @param installFlags package installation flags
13144      * @return true if should be installed as forward locked
13145      */
13146     private static boolean installForwardLocked(int installFlags) {
13147         return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13148     }
13149
13150     private InstallArgs createInstallArgs(InstallParams params) {
13151         if (params.move != null) {
13152             return new MoveInstallArgs(params);
13153         } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13154             return new AsecInstallArgs(params);
13155         } else {
13156             return new FileInstallArgs(params);
13157         }
13158     }
13159
13160     /**
13161      * Create args that describe an existing installed package. Typically used
13162      * when cleaning up old installs, or used as a move source.
13163      */
13164     private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13165             String resourcePath, String[] instructionSets) {
13166         final boolean isInAsec;
13167         if (installOnExternalAsec(installFlags)) {
13168             /* Apps on SD card are always in ASEC containers. */
13169             isInAsec = true;
13170         } else if (installForwardLocked(installFlags)
13171                 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13172             /*
13173              * Forward-locked apps are only in ASEC containers if they're the
13174              * new style
13175              */
13176             isInAsec = true;
13177         } else {
13178             isInAsec = false;
13179         }
13180
13181         if (isInAsec) {
13182             return new AsecInstallArgs(codePath, instructionSets,
13183                     installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13184         } else {
13185             return new FileInstallArgs(codePath, resourcePath, instructionSets);
13186         }
13187     }
13188
13189     static abstract class InstallArgs {
13190         /** @see InstallParams#origin */
13191         final OriginInfo origin;
13192         /** @see InstallParams#move */
13193         final MoveInfo move;
13194
13195         final IPackageInstallObserver2 observer;
13196         // Always refers to PackageManager flags only
13197         final int installFlags;
13198         final String installerPackageName;
13199         final String volumeUuid;
13200         final UserHandle user;
13201         final String abiOverride;
13202         final String[] installGrantPermissions;
13203         /** If non-null, drop an async trace when the install completes */
13204         final String traceMethod;
13205         final int traceCookie;
13206         final Certificate[][] certificates;
13207
13208         // The list of instruction sets supported by this app. This is currently
13209         // only used during the rmdex() phase to clean up resources. We can get rid of this
13210         // if we move dex files under the common app path.
13211         /* nullable */ String[] instructionSets;
13212
13213         InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13214                 int installFlags, String installerPackageName, String volumeUuid,
13215                 UserHandle user, String[] instructionSets,
13216                 String abiOverride, String[] installGrantPermissions,
13217                 String traceMethod, int traceCookie, Certificate[][] certificates) {
13218             this.origin = origin;
13219             this.move = move;
13220             this.installFlags = installFlags;
13221             this.observer = observer;
13222             this.installerPackageName = installerPackageName;
13223             this.volumeUuid = volumeUuid;
13224             this.user = user;
13225             this.instructionSets = instructionSets;
13226             this.abiOverride = abiOverride;
13227             this.installGrantPermissions = installGrantPermissions;
13228             this.traceMethod = traceMethod;
13229             this.traceCookie = traceCookie;
13230             this.certificates = certificates;
13231         }
13232
13233         abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13234         abstract int doPreInstall(int status);
13235
13236         /**
13237          * Rename package into final resting place. All paths on the given
13238          * scanned package should be updated to reflect the rename.
13239          */
13240         abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13241         abstract int doPostInstall(int status, int uid);
13242
13243         /** @see PackageSettingBase#codePathString */
13244         abstract String getCodePath();
13245         /** @see PackageSettingBase#resourcePathString */
13246         abstract String getResourcePath();
13247
13248         // Need installer lock especially for dex file removal.
13249         abstract void cleanUpResourcesLI();
13250         abstract boolean doPostDeleteLI(boolean delete);
13251
13252         /**
13253          * Called before the source arguments are copied. This is used mostly
13254          * for MoveParams when it needs to read the source file to put it in the
13255          * destination.
13256          */
13257         int doPreCopy() {
13258             return PackageManager.INSTALL_SUCCEEDED;
13259         }
13260
13261         /**
13262          * Called after the source arguments are copied. This is used mostly for
13263          * MoveParams when it needs to read the source file to put it in the
13264          * destination.
13265          */
13266         int doPostCopy(int uid) {
13267             return PackageManager.INSTALL_SUCCEEDED;
13268         }
13269
13270         protected boolean isFwdLocked() {
13271             return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13272         }
13273
13274         protected boolean isExternalAsec() {
13275             return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13276         }
13277
13278         protected boolean isEphemeral() {
13279             return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13280         }
13281
13282         UserHandle getUser() {
13283             return user;
13284         }
13285     }
13286
13287     private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13288         if (!allCodePaths.isEmpty()) {
13289             if (instructionSets == null) {
13290                 throw new IllegalStateException("instructionSet == null");
13291             }
13292             String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13293             for (String codePath : allCodePaths) {
13294                 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13295                     try {
13296                         mInstaller.rmdex(codePath, dexCodeInstructionSet);
13297                     } catch (InstallerException ignored) {
13298                     }
13299                 }
13300             }
13301         }
13302     }
13303
13304     /**
13305      * Logic to handle installation of non-ASEC applications, including copying
13306      * and renaming logic.
13307      */
13308     class FileInstallArgs extends InstallArgs {
13309         private File codeFile;
13310         private File resourceFile;
13311
13312         // Example topology:
13313         // /data/app/com.example/base.apk
13314         // /data/app/com.example/split_foo.apk
13315         // /data/app/com.example/lib/arm/libfoo.so
13316         // /data/app/com.example/lib/arm64/libfoo.so
13317         // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13318
13319         /** New install */
13320         FileInstallArgs(InstallParams params) {
13321             super(params.origin, params.move, params.observer, params.installFlags,
13322                     params.installerPackageName, params.volumeUuid,
13323                     params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13324                     params.grantedRuntimePermissions,
13325                     params.traceMethod, params.traceCookie, params.certificates);
13326             if (isFwdLocked()) {
13327                 throw new IllegalArgumentException("Forward locking only supported in ASEC");
13328             }
13329         }
13330
13331         /** Existing install */
13332         FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13333             super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13334                     null, null, null, 0, null /*certificates*/);
13335             this.codeFile = (codePath != null) ? new File(codePath) : null;
13336             this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13337         }
13338
13339         int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13340             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13341             try {
13342                 return doCopyApk(imcs, temp);
13343             } finally {
13344                 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13345             }
13346         }
13347
13348         private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13349             if (origin.staged) {
13350                 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13351                 codeFile = origin.file;
13352                 resourceFile = origin.file;
13353                 return PackageManager.INSTALL_SUCCEEDED;
13354             }
13355
13356             try {
13357                 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13358                 final File tempDir =
13359                         mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13360                 codeFile = tempDir;
13361                 resourceFile = tempDir;
13362             } catch (IOException e) {
13363                 Slog.w(TAG, "Failed to create copy file: " + e);
13364                 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13365             }
13366
13367             final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13368                 @Override
13369                 public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13370                     if (!FileUtils.isValidExtFilename(name)) {
13371                         throw new IllegalArgumentException("Invalid filename: " + name);
13372                     }
13373                     try {
13374                         final File file = new File(codeFile, name);
13375                         final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13376                                 O_RDWR | O_CREAT, 0644);
13377                         Os.chmod(file.getAbsolutePath(), 0644);
13378                         return new ParcelFileDescriptor(fd);
13379                     } catch (ErrnoException e) {
13380                         throw new RemoteException("Failed to open: " + e.getMessage());
13381                     }
13382                 }
13383             };
13384
13385             int ret = PackageManager.INSTALL_SUCCEEDED;
13386             ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13387             if (ret != PackageManager.INSTALL_SUCCEEDED) {
13388                 Slog.e(TAG, "Failed to copy package");
13389                 return ret;
13390             }
13391
13392             final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13393             NativeLibraryHelper.Handle handle = null;
13394             try {
13395                 handle = NativeLibraryHelper.Handle.create(codeFile);
13396                 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13397                         abiOverride);
13398             } catch (IOException e) {
13399                 Slog.e(TAG, "Copying native libraries failed", e);
13400                 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13401             } finally {
13402                 IoUtils.closeQuietly(handle);
13403             }
13404
13405             return ret;
13406         }
13407
13408         int doPreInstall(int status) {
13409             if (status != PackageManager.INSTALL_SUCCEEDED) {
13410                 cleanUp();
13411             }
13412             return status;
13413         }
13414
13415         boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13416             if (status != PackageManager.INSTALL_SUCCEEDED) {
13417                 cleanUp();
13418                 return false;
13419             }
13420
13421             final File targetDir = codeFile.getParentFile();
13422             final File beforeCodeFile = codeFile;
13423             final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13424
13425             if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13426             try {
13427                 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13428             } catch (ErrnoException e) {
13429                 Slog.w(TAG, "Failed to rename", e);
13430                 return false;
13431             }
13432
13433             if (!SELinux.restoreconRecursive(afterCodeFile)) {
13434                 Slog.w(TAG, "Failed to restorecon");
13435                 return false;
13436             }
13437
13438             // Reflect the rename internally
13439             codeFile = afterCodeFile;
13440             resourceFile = afterCodeFile;
13441
13442             // Reflect the rename in scanned details
13443             pkg.setCodePath(afterCodeFile.getAbsolutePath());
13444             pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13445                     afterCodeFile, pkg.baseCodePath));
13446             pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13447                     afterCodeFile, pkg.splitCodePaths));
13448
13449             // Reflect the rename in app info
13450             pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13451             pkg.setApplicationInfoCodePath(pkg.codePath);
13452             pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13453             pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13454             pkg.setApplicationInfoResourcePath(pkg.codePath);
13455             pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13456             pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13457
13458             return true;
13459         }
13460
13461         int doPostInstall(int status, int uid) {
13462             if (status != PackageManager.INSTALL_SUCCEEDED) {
13463                 cleanUp();
13464             }
13465             return status;
13466         }
13467
13468         @Override
13469         String getCodePath() {
13470             return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13471         }
13472
13473         @Override
13474         String getResourcePath() {
13475             return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13476         }
13477
13478         private boolean cleanUp() {
13479             if (codeFile == null || !codeFile.exists()) {
13480                 return false;
13481             }
13482
13483             removeCodePathLI(codeFile);
13484
13485             if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13486                 resourceFile.delete();
13487             }
13488
13489             return true;
13490         }
13491
13492         void cleanUpResourcesLI() {
13493             // Try enumerating all code paths before deleting
13494             List<String> allCodePaths = Collections.EMPTY_LIST;
13495             if (codeFile != null && codeFile.exists()) {
13496                 try {
13497                     final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13498                     allCodePaths = pkg.getAllCodePaths();
13499                 } catch (PackageParserException e) {
13500                     // Ignored; we tried our best
13501                 }
13502             }
13503
13504             cleanUp();
13505             removeDexFiles(allCodePaths, instructionSets);
13506         }
13507
13508         boolean doPostDeleteLI(boolean delete) {
13509             // XXX err, shouldn't we respect the delete flag?
13510             cleanUpResourcesLI();
13511             return true;
13512         }
13513     }
13514
13515     private boolean isAsecExternal(String cid) {
13516         final String asecPath = PackageHelper.getSdFilesystem(cid);
13517         return !asecPath.startsWith(mAsecInternalPath);
13518     }
13519
13520     private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13521             PackageManagerException {
13522         if (copyRet < 0) {
13523             if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13524                     copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13525                 throw new PackageManagerException(copyRet, message);
13526             }
13527         }
13528     }
13529
13530     /**
13531      * Extract the MountService "container ID" from the full code path of an
13532      * .apk.
13533      */
13534     static String cidFromCodePath(String fullCodePath) {
13535         int eidx = fullCodePath.lastIndexOf("/");
13536         String subStr1 = fullCodePath.substring(0, eidx);
13537         int sidx = subStr1.lastIndexOf("/");
13538         return subStr1.substring(sidx+1, eidx);
13539     }
13540
13541     /**
13542      * Logic to handle installation of ASEC applications, including copying and
13543      * renaming logic.
13544      */
13545     class AsecInstallArgs extends InstallArgs {
13546         static final String RES_FILE_NAME = "pkg.apk";
13547         static final String PUBLIC_RES_FILE_NAME = "res.zip";
13548
13549         String cid;
13550         String packagePath;
13551         String resourcePath;
13552
13553         /** New install */
13554         AsecInstallArgs(InstallParams params) {
13555             super(params.origin, params.move, params.observer, params.installFlags,
13556                     params.installerPackageName, params.volumeUuid,
13557                     params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13558                     params.grantedRuntimePermissions,
13559                     params.traceMethod, params.traceCookie, params.certificates);
13560         }
13561
13562         /** Existing install */
13563         AsecInstallArgs(String fullCodePath, String[] instructionSets,
13564                         boolean isExternal, boolean isForwardLocked) {
13565             super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13566               | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13567                     instructionSets, null, null, null, 0, null /*certificates*/);
13568             // Hackily pretend we're still looking at a full code path
13569             if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13570                 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13571             }
13572
13573             // Extract cid from fullCodePath
13574             int eidx = fullCodePath.lastIndexOf("/");
13575             String subStr1 = fullCodePath.substring(0, eidx);
13576             int sidx = subStr1.lastIndexOf("/");
13577             cid = subStr1.substring(sidx+1, eidx);
13578             setMountPath(subStr1);
13579         }
13580
13581         AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13582             super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13583               | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13584                     instructionSets, null, null, null, 0, null /*certificates*/);
13585             this.cid = cid;
13586             setMountPath(PackageHelper.getSdDir(cid));
13587         }
13588
13589         void createCopyFile() {
13590             cid = mInstallerService.allocateExternalStageCidLegacy();
13591         }
13592
13593         int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13594             if (origin.staged && origin.cid != null) {
13595                 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13596                 cid = origin.cid;
13597                 setMountPath(PackageHelper.getSdDir(cid));
13598                 return PackageManager.INSTALL_SUCCEEDED;
13599             }
13600
13601             if (temp) {
13602                 createCopyFile();
13603             } else {
13604                 /*
13605                  * Pre-emptively destroy the container since it's destroyed if
13606                  * copying fails due to it existing anyway.
13607                  */
13608                 PackageHelper.destroySdDir(cid);
13609             }
13610
13611             final String newMountPath = imcs.copyPackageToContainer(
13612                     origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13613                     isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13614
13615             if (newMountPath != null) {
13616                 setMountPath(newMountPath);
13617                 return PackageManager.INSTALL_SUCCEEDED;
13618             } else {
13619                 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13620             }
13621         }
13622
13623         @Override
13624         String getCodePath() {
13625             return packagePath;
13626         }
13627
13628         @Override
13629         String getResourcePath() {
13630             return resourcePath;
13631         }
13632
13633         int doPreInstall(int status) {
13634             if (status != PackageManager.INSTALL_SUCCEEDED) {
13635                 // Destroy container
13636                 PackageHelper.destroySdDir(cid);
13637             } else {
13638                 boolean mounted = PackageHelper.isContainerMounted(cid);
13639                 if (!mounted) {
13640                     String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13641                             Process.SYSTEM_UID);
13642                     if (newMountPath != null) {
13643                         setMountPath(newMountPath);
13644                     } else {
13645                         return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13646                     }
13647                 }
13648             }
13649             return status;
13650         }
13651
13652         boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13653             String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13654             String newMountPath = null;
13655             if (PackageHelper.isContainerMounted(cid)) {
13656                 // Unmount the container
13657                 if (!PackageHelper.unMountSdDir(cid)) {
13658                     Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13659                     return false;
13660                 }
13661             }
13662             if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13663                 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13664                         " which might be stale. Will try to clean up.");
13665                 // Clean up the stale container and proceed to recreate.
13666                 if (!PackageHelper.destroySdDir(newCacheId)) {
13667                     Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13668                     return false;
13669                 }
13670                 // Successfully cleaned up stale container. Try to rename again.
13671                 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13672                     Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13673                             + " inspite of cleaning it up.");
13674                     return false;
13675                 }
13676             }
13677             if (!PackageHelper.isContainerMounted(newCacheId)) {
13678                 Slog.w(TAG, "Mounting container " + newCacheId);
13679                 newMountPath = PackageHelper.mountSdDir(newCacheId,
13680                         getEncryptKey(), Process.SYSTEM_UID);
13681             } else {
13682                 newMountPath = PackageHelper.getSdDir(newCacheId);
13683             }
13684             if (newMountPath == null) {
13685                 Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13686                 return false;
13687             }
13688             Log.i(TAG, "Succesfully renamed " + cid +
13689                     " to " + newCacheId +
13690                     " at new path: " + newMountPath);
13691             cid = newCacheId;
13692
13693             final File beforeCodeFile = new File(packagePath);
13694             setMountPath(newMountPath);
13695             final File afterCodeFile = new File(packagePath);
13696
13697             // Reflect the rename in scanned details
13698             pkg.setCodePath(afterCodeFile.getAbsolutePath());
13699             pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13700                     afterCodeFile, pkg.baseCodePath));
13701             pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13702                     afterCodeFile, pkg.splitCodePaths));
13703
13704             // Reflect the rename in app info
13705             pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13706             pkg.setApplicationInfoCodePath(pkg.codePath);
13707             pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13708             pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13709             pkg.setApplicationInfoResourcePath(pkg.codePath);
13710             pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13711             pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13712
13713             return true;
13714         }
13715
13716         private void setMountPath(String mountPath) {
13717             final File mountFile = new File(mountPath);
13718
13719             final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13720             if (monolithicFile.exists()) {
13721                 packagePath = monolithicFile.getAbsolutePath();
13722                 if (isFwdLocked()) {
13723                     resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13724                 } else {
13725                     resourcePath = packagePath;
13726                 }
13727             } else {
13728                 packagePath = mountFile.getAbsolutePath();
13729                 resourcePath = packagePath;
13730             }
13731         }
13732
13733         int doPostInstall(int status, int uid) {
13734             if (status != PackageManager.INSTALL_SUCCEEDED) {
13735                 cleanUp();
13736             } else {
13737                 final int groupOwner;
13738                 final String protectedFile;
13739                 if (isFwdLocked()) {
13740                     groupOwner = UserHandle.getSharedAppGid(uid);
13741                     protectedFile = RES_FILE_NAME;
13742                 } else {
13743                     groupOwner = -1;
13744                     protectedFile = null;
13745                 }
13746
13747                 if (uid < Process.FIRST_APPLICATION_UID
13748                         || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13749                     Slog.e(TAG, "Failed to finalize " + cid);
13750                     PackageHelper.destroySdDir(cid);
13751                     return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13752                 }
13753
13754                 boolean mounted = PackageHelper.isContainerMounted(cid);
13755                 if (!mounted) {
13756                     PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13757                 }
13758             }
13759             return status;
13760         }
13761
13762         private void cleanUp() {
13763             if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13764
13765             // Destroy secure container
13766             PackageHelper.destroySdDir(cid);
13767         }
13768
13769         private List<String> getAllCodePaths() {
13770             final File codeFile = new File(getCodePath());
13771             if (codeFile != null && codeFile.exists()) {
13772                 try {
13773                     final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13774                     return pkg.getAllCodePaths();
13775                 } catch (PackageParserException e) {
13776                     // Ignored; we tried our best
13777                 }
13778             }
13779             return Collections.EMPTY_LIST;
13780         }
13781
13782         void cleanUpResourcesLI() {
13783             // Enumerate all code paths before deleting
13784             cleanUpResourcesLI(getAllCodePaths());
13785         }
13786
13787         private void cleanUpResourcesLI(List<String> allCodePaths) {
13788             cleanUp();
13789             removeDexFiles(allCodePaths, instructionSets);
13790         }
13791
13792         String getPackageName() {
13793             return getAsecPackageName(cid);
13794         }
13795
13796         boolean doPostDeleteLI(boolean delete) {
13797             if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13798             final List<String> allCodePaths = getAllCodePaths();
13799             boolean mounted = PackageHelper.isContainerMounted(cid);
13800             if (mounted) {
13801                 // Unmount first
13802                 if (PackageHelper.unMountSdDir(cid)) {
13803                     mounted = false;
13804                 }
13805             }
13806             if (!mounted && delete) {
13807                 cleanUpResourcesLI(allCodePaths);
13808             }
13809             return !mounted;
13810         }
13811
13812         @Override
13813         int doPreCopy() {
13814             if (isFwdLocked()) {
13815                 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13816                         MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13817                     return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13818                 }
13819             }
13820
13821             return PackageManager.INSTALL_SUCCEEDED;
13822         }
13823
13824         @Override
13825         int doPostCopy(int uid) {
13826             if (isFwdLocked()) {
13827                 if (uid < Process.FIRST_APPLICATION_UID
13828                         || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13829                                 RES_FILE_NAME)) {
13830                     Slog.e(TAG, "Failed to finalize " + cid);
13831                     PackageHelper.destroySdDir(cid);
13832                     return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13833                 }
13834             }
13835
13836             return PackageManager.INSTALL_SUCCEEDED;
13837         }
13838     }
13839
13840     /**
13841      * Logic to handle movement of existing installed applications.
13842      */
13843     class MoveInstallArgs extends InstallArgs {
13844         private File codeFile;
13845         private File resourceFile;
13846
13847         /** New install */
13848         MoveInstallArgs(InstallParams params) {
13849             super(params.origin, params.move, params.observer, params.installFlags,
13850                     params.installerPackageName, params.volumeUuid,
13851                     params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13852                     params.grantedRuntimePermissions,
13853                     params.traceMethod, params.traceCookie, params.certificates);
13854         }
13855
13856         int copyApk(IMediaContainerService imcs, boolean temp) {
13857             if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13858                     + move.fromUuid + " to " + move.toUuid);
13859             synchronized (mInstaller) {
13860                 try {
13861                     mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13862                             move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13863                 } catch (InstallerException e) {
13864                     Slog.w(TAG, "Failed to move app", e);
13865                     return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13866                 }
13867             }
13868
13869             codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13870             resourceFile = codeFile;
13871             if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13872
13873             return PackageManager.INSTALL_SUCCEEDED;
13874         }
13875
13876         int doPreInstall(int status) {
13877             if (status != PackageManager.INSTALL_SUCCEEDED) {
13878                 cleanUp(move.toUuid);
13879             }
13880             return status;
13881         }
13882
13883         boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13884             if (status != PackageManager.INSTALL_SUCCEEDED) {
13885                 cleanUp(move.toUuid);
13886                 return false;
13887             }
13888
13889             // Reflect the move in app info
13890             pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13891             pkg.setApplicationInfoCodePath(pkg.codePath);
13892             pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13893             pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13894             pkg.setApplicationInfoResourcePath(pkg.codePath);
13895             pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13896             pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13897
13898             return true;
13899         }
13900
13901         int doPostInstall(int status, int uid) {
13902             if (status == PackageManager.INSTALL_SUCCEEDED) {
13903                 cleanUp(move.fromUuid);
13904             } else {
13905                 cleanUp(move.toUuid);
13906             }
13907             return status;
13908         }
13909
13910         @Override
13911         String getCodePath() {
13912             return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13913         }
13914
13915         @Override
13916         String getResourcePath() {
13917             return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13918         }
13919
13920         private boolean cleanUp(String volumeUuid) {
13921             final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13922                     move.dataAppName);
13923             Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13924             final int[] userIds = sUserManager.getUserIds();
13925             synchronized (mInstallLock) {
13926                 // Clean up both app data and code
13927                 // All package moves are frozen until finished
13928                 for (int userId : userIds) {
13929                     try {
13930                         mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13931                                 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13932                     } catch (InstallerException e) {
13933                         Slog.w(TAG, String.valueOf(e));
13934                     }
13935                 }
13936                 removeCodePathLI(codeFile);
13937             }
13938             return true;
13939         }
13940
13941         void cleanUpResourcesLI() {
13942             throw new UnsupportedOperationException();
13943         }
13944
13945         boolean doPostDeleteLI(boolean delete) {
13946             throw new UnsupportedOperationException();
13947         }
13948     }
13949
13950     static String getAsecPackageName(String packageCid) {
13951         int idx = packageCid.lastIndexOf("-");
13952         if (idx == -1) {
13953             return packageCid;
13954         }
13955         return packageCid.substring(0, idx);
13956     }
13957
13958     // Utility method used to create code paths based on package name and available index.
13959     private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13960         String idxStr = "";
13961         int idx = 1;
13962         // Fall back to default value of idx=1 if prefix is not
13963         // part of oldCodePath
13964         if (oldCodePath != null) {
13965             String subStr = oldCodePath;
13966             // Drop the suffix right away
13967             if (suffix != null && subStr.endsWith(suffix)) {
13968                 subStr = subStr.substring(0, subStr.length() - suffix.length());
13969             }
13970             // If oldCodePath already contains prefix find out the
13971             // ending index to either increment or decrement.
13972             int sidx = subStr.lastIndexOf(prefix);
13973             if (sidx != -1) {
13974                 subStr = subStr.substring(sidx + prefix.length());
13975                 if (subStr != null) {
13976                     if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13977                         subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13978                     }
13979                     try {
13980                         idx = Integer.parseInt(subStr);
13981                         if (idx <= 1) {
13982                             idx++;
13983                         } else {
13984                             idx--;
13985                         }
13986                     } catch(NumberFormatException e) {
13987                     }
13988                 }
13989             }
13990         }
13991         idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13992         return prefix + idxStr;
13993     }
13994
13995     private File getNextCodePath(File targetDir, String packageName) {
13996         int suffix = 1;
13997         File result;
13998         do {
13999             result = new File(targetDir, packageName + "-" + suffix);
14000             suffix++;
14001         } while (result.exists());
14002         return result;
14003     }
14004
14005     // Utility method that returns the relative package path with respect
14006     // to the installation directory. Like say for /data/data/com.test-1.apk
14007     // string com.test-1 is returned.
14008     static String deriveCodePathName(String codePath) {
14009         if (codePath == null) {
14010             return null;
14011         }
14012         final File codeFile = new File(codePath);
14013         final String name = codeFile.getName();
14014         if (codeFile.isDirectory()) {
14015             return name;
14016         } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14017             final int lastDot = name.lastIndexOf('.');
14018             return name.substring(0, lastDot);
14019         } else {
14020             Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14021             return null;
14022         }
14023     }
14024
14025     static class PackageInstalledInfo {
14026         String name;
14027         int uid;
14028         // The set of users that originally had this package installed.
14029         int[] origUsers;
14030         // The set of users that now have this package installed.
14031         int[] newUsers;
14032         PackageParser.Package pkg;
14033         int returnCode;
14034         String returnMsg;
14035         PackageRemovedInfo removedInfo;
14036         ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14037
14038         public void setError(int code, String msg) {
14039             setReturnCode(code);
14040             setReturnMessage(msg);
14041             Slog.w(TAG, msg);
14042         }
14043
14044         public void setError(String msg, PackageParserException e) {
14045             setReturnCode(e.error);
14046             setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14047             Slog.w(TAG, msg, e);
14048         }
14049
14050         public void setError(String msg, PackageManagerException e) {
14051             returnCode = e.error;
14052             setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14053             Slog.w(TAG, msg, e);
14054         }
14055
14056         public void setReturnCode(int returnCode) {
14057             this.returnCode = returnCode;
14058             final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14059             for (int i = 0; i < childCount; i++) {
14060                 addedChildPackages.valueAt(i).returnCode = returnCode;
14061             }
14062         }
14063
14064         private void setReturnMessage(String returnMsg) {
14065             this.returnMsg = returnMsg;
14066             final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14067             for (int i = 0; i < childCount; i++) {
14068                 addedChildPackages.valueAt(i).returnMsg = returnMsg;
14069             }
14070         }
14071
14072         // In some error cases we want to convey more info back to the observer
14073         String origPackage;
14074         String origPermission;
14075     }
14076
14077     /*
14078      * Install a non-existing package.
14079      */
14080     private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14081             int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14082             PackageInstalledInfo res) {
14083         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14084
14085         // Remember this for later, in case we need to rollback this install
14086         String pkgName = pkg.packageName;
14087
14088         if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14089
14090         synchronized(mPackages) {
14091             if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14092                 // A package with the same name is already installed, though
14093                 // it has been renamed to an older name.  The package we
14094                 // are trying to install should be installed as an update to
14095                 // the existing one, but that has not been requested, so bail.
14096                 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14097                         + " without first uninstalling package running as "
14098                         + mSettings.mRenamedPackages.get(pkgName));
14099                 return;
14100             }
14101             if (mPackages.containsKey(pkgName)) {
14102                 // Don't allow installation over an existing package with the same name.
14103                 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14104                         + " without first uninstalling.");
14105                 return;
14106             }
14107         }
14108
14109         try {
14110             PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14111                     System.currentTimeMillis(), user);
14112
14113             updateSettingsLI(newPackage, installerPackageName, null, res, user);
14114
14115             if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14116                 prepareAppDataAfterInstallLIF(newPackage);
14117
14118             } else {
14119                 // Remove package from internal structures, but keep around any
14120                 // data that might have already existed
14121                 deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14122                         PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14123             }
14124         } catch (PackageManagerException e) {
14125             res.setError("Package couldn't be installed in " + pkg.codePath, e);
14126         }
14127
14128         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14129     }
14130
14131     private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14132         // Can't rotate keys during boot or if sharedUser.
14133         if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14134                 || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14135             return false;
14136         }
14137         // app is using upgradeKeySets; make sure all are valid
14138         KeySetManagerService ksms = mSettings.mKeySetManagerService;
14139         long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14140         for (int i = 0; i < upgradeKeySets.length; i++) {
14141             if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14142                 Slog.wtf(TAG, "Package "
14143                          + (oldPs.name != null ? oldPs.name : "<null>")
14144                          + " contains upgrade-key-set reference to unknown key-set: "
14145                          + upgradeKeySets[i]
14146                          + " reverting to signatures check.");
14147                 return false;
14148             }
14149         }
14150         return true;
14151     }
14152
14153     private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14154         // Upgrade keysets are being used.  Determine if new package has a superset of the
14155         // required keys.
14156         long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14157         KeySetManagerService ksms = mSettings.mKeySetManagerService;
14158         for (int i = 0; i < upgradeKeySets.length; i++) {
14159             Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14160             if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14161                 return true;
14162             }
14163         }
14164         return false;
14165     }
14166
14167     private static void updateDigest(MessageDigest digest, File file) throws IOException {
14168         try (DigestInputStream digestStream =
14169                 new DigestInputStream(new FileInputStream(file), digest)) {
14170             while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14171         }
14172     }
14173
14174     private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14175             UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14176         final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14177
14178         final PackageParser.Package oldPackage;
14179         final String pkgName = pkg.packageName;
14180         final int[] allUsers;
14181         final int[] installedUsers;
14182
14183         synchronized(mPackages) {
14184             oldPackage = mPackages.get(pkgName);
14185             if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14186
14187             // don't allow upgrade to target a release SDK from a pre-release SDK
14188             final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14189                     == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14190             final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14191                     == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14192             if (oldTargetsPreRelease
14193                     && !newTargetsPreRelease
14194                     && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14195                 Slog.w(TAG, "Can't install package targeting released sdk");
14196                 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14197                 return;
14198             }
14199
14200             // don't allow an upgrade from full to ephemeral
14201             final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14202             if (isEphemeral && !oldIsEphemeral) {
14203                 // can't downgrade from full to ephemeral
14204                 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14205                 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14206                 return;
14207             }
14208
14209             // verify signatures are valid
14210             final PackageSetting ps = mSettings.mPackages.get(pkgName);
14211             if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14212                 if (!checkUpgradeKeySetLP(ps, pkg)) {
14213                     res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14214                             "New package not signed by keys specified by upgrade-keysets: "
14215                                     + pkgName);
14216                     return;
14217                 }
14218             } else {
14219                 // default to original signature matching
14220                 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14221                         != PackageManager.SIGNATURE_MATCH) {
14222                     res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14223                             "New package has a different signature: " + pkgName);
14224                     return;
14225                 }
14226             }
14227
14228             // don't allow a system upgrade unless the upgrade hash matches
14229             if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14230                 byte[] digestBytes = null;
14231                 try {
14232                     final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14233                     updateDigest(digest, new File(pkg.baseCodePath));
14234                     if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14235                         for (String path : pkg.splitCodePaths) {
14236                             updateDigest(digest, new File(path));
14237                         }
14238                     }
14239                     digestBytes = digest.digest();
14240                 } catch (NoSuchAlgorithmException | IOException e) {
14241                     res.setError(INSTALL_FAILED_INVALID_APK,
14242                             "Could not compute hash: " + pkgName);
14243                     return;
14244                 }
14245                 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14246                     res.setError(INSTALL_FAILED_INVALID_APK,
14247                             "New package fails restrict-update check: " + pkgName);
14248                     return;
14249                 }
14250                 // retain upgrade restriction
14251                 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14252             }
14253
14254             // Check for shared user id changes
14255             String invalidPackageName =
14256                     getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14257             if (invalidPackageName != null) {
14258                 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14259                         "Package " + invalidPackageName + " tried to change user "
14260                                 + oldPackage.mSharedUserId);
14261                 return;
14262             }
14263
14264             // In case of rollback, remember per-user/profile install state
14265             allUsers = sUserManager.getUserIds();
14266             installedUsers = ps.queryInstalledUsers(allUsers, true);
14267         }
14268
14269         // Update what is removed
14270         res.removedInfo = new PackageRemovedInfo();
14271         res.removedInfo.uid = oldPackage.applicationInfo.uid;
14272         res.removedInfo.removedPackage = oldPackage.packageName;
14273         res.removedInfo.isUpdate = true;
14274         res.removedInfo.origUsers = installedUsers;
14275         final int childCount = (oldPackage.childPackages != null)
14276                 ? oldPackage.childPackages.size() : 0;
14277         for (int i = 0; i < childCount; i++) {
14278             boolean childPackageUpdated = false;
14279             PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14280             if (res.addedChildPackages != null) {
14281                 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14282                 if (childRes != null) {
14283                     childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14284                     childRes.removedInfo.removedPackage = childPkg.packageName;
14285                     childRes.removedInfo.isUpdate = true;
14286                     childPackageUpdated = true;
14287                 }
14288             }
14289             if (!childPackageUpdated) {
14290                 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14291                 childRemovedRes.removedPackage = childPkg.packageName;
14292                 childRemovedRes.isUpdate = false;
14293                 childRemovedRes.dataRemoved = true;
14294                 synchronized (mPackages) {
14295                     PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14296                     if (childPs != null) {
14297                         childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14298                     }
14299                 }
14300                 if (res.removedInfo.removedChildPackages == null) {
14301                     res.removedInfo.removedChildPackages = new ArrayMap<>();
14302                 }
14303                 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14304             }
14305         }
14306
14307         boolean sysPkg = (isSystemApp(oldPackage));
14308         if (sysPkg) {
14309             // Set the system/privileged flags as needed
14310             final boolean privileged =
14311                     (oldPackage.applicationInfo.privateFlags
14312                             & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14313             final int systemPolicyFlags = policyFlags
14314                     | PackageParser.PARSE_IS_SYSTEM
14315                     | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14316
14317             replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14318                     user, allUsers, installerPackageName, res);
14319         } else {
14320             replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14321                     user, allUsers, installerPackageName, res);
14322         }
14323     }
14324
14325     public List<String> getPreviousCodePaths(String packageName) {
14326         final PackageSetting ps = mSettings.mPackages.get(packageName);
14327         final List<String> result = new ArrayList<String>();
14328         if (ps != null && ps.oldCodePaths != null) {
14329             result.addAll(ps.oldCodePaths);
14330         }
14331         return result;
14332     }
14333
14334     private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14335             PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14336             int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14337         if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14338                 + deletedPackage);
14339
14340         String pkgName = deletedPackage.packageName;
14341         boolean deletedPkg = true;
14342         boolean addedPkg = false;
14343         boolean updatedSettings = false;
14344         final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14345         final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14346                 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14347
14348         final long origUpdateTime = (pkg.mExtras != null)
14349                 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14350
14351         // First delete the existing package while retaining the data directory
14352         if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14353                 res.removedInfo, true, pkg)) {
14354             // If the existing package wasn't successfully deleted
14355             res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14356             deletedPkg = false;
14357         } else {
14358             // Successfully deleted the old package; proceed with replace.
14359
14360             // If deleted package lived in a container, give users a chance to
14361             // relinquish resources before killing.
14362             if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14363                 if (DEBUG_INSTALL) {
14364                     Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14365                 }
14366                 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14367                 final ArrayList<String> pkgList = new ArrayList<String>(1);
14368                 pkgList.add(deletedPackage.applicationInfo.packageName);
14369                 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14370             }
14371
14372             clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14373                     | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14374             clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14375
14376             try {
14377                 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14378                         scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14379                 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14380
14381                 // Update the in-memory copy of the previous code paths.
14382                 PackageSetting ps = mSettings.mPackages.get(pkgName);
14383                 if (!killApp) {
14384                     if (ps.oldCodePaths == null) {
14385                         ps.oldCodePaths = new ArraySet<>();
14386                     }
14387                     Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14388                     if (deletedPackage.splitCodePaths != null) {
14389                         Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14390                     }
14391                 } else {
14392                     ps.oldCodePaths = null;
14393                 }
14394                 if (ps.childPackageNames != null) {
14395                     for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14396                         final String childPkgName = ps.childPackageNames.get(i);
14397                         final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14398                         childPs.oldCodePaths = ps.oldCodePaths;
14399                     }
14400                 }
14401                 prepareAppDataAfterInstallLIF(newPackage);
14402                 addedPkg = true;
14403             } catch (PackageManagerException e) {
14404                 res.setError("Package couldn't be installed in " + pkg.codePath, e);
14405             }
14406         }
14407
14408         if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14409             if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14410
14411             // Revert all internal state mutations and added folders for the failed install
14412             if (addedPkg) {
14413                 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14414                         res.removedInfo, true, null);
14415             }
14416
14417             // Restore the old package
14418             if (deletedPkg) {
14419                 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14420                 File restoreFile = new File(deletedPackage.codePath);
14421                 // Parse old package
14422                 boolean oldExternal = isExternal(deletedPackage);
14423                 int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14424                         (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14425                         (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14426                 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14427                 try {
14428                     scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14429                             null);
14430                 } catch (PackageManagerException e) {
14431                     Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14432                             + e.getMessage());
14433                     return;
14434                 }
14435
14436                 synchronized (mPackages) {
14437                     // Ensure the installer package name up to date
14438                     setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14439
14440                     // Update permissions for restored package
14441                     updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14442
14443                     mSettings.writeLPr();
14444                 }
14445
14446                 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14447             }
14448         } else {
14449             synchronized (mPackages) {
14450                 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14451                 if (ps != null) {
14452                     res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14453                     if (res.removedInfo.removedChildPackages != null) {
14454                         final int childCount = res.removedInfo.removedChildPackages.size();
14455                         // Iterate in reverse as we may modify the collection
14456                         for (int i = childCount - 1; i >= 0; i--) {
14457                             String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14458                             if (res.addedChildPackages.containsKey(childPackageName)) {
14459                                 res.removedInfo.removedChildPackages.removeAt(i);
14460                             } else {
14461                                 PackageRemovedInfo childInfo = res.removedInfo
14462                                         .removedChildPackages.valueAt(i);
14463                                 childInfo.removedForAllUsers = mPackages.get(
14464                                         childInfo.removedPackage) == null;
14465                             }
14466                         }
14467                     }
14468                 }
14469             }
14470         }
14471     }
14472
14473     private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14474             PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14475             int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14476         if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14477                 + ", old=" + deletedPackage);
14478
14479         final boolean disabledSystem;
14480
14481         // Remove existing system package
14482         removePackageLI(deletedPackage, true);
14483
14484         synchronized (mPackages) {
14485             disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14486         }
14487         if (!disabledSystem) {
14488             // We didn't need to disable the .apk as a current system package,
14489             // which means we are replacing another update that is already
14490             // installed.  We need to make sure to delete the older one's .apk.
14491             res.removedInfo.args = createInstallArgsForExisting(0,
14492                     deletedPackage.applicationInfo.getCodePath(),
14493                     deletedPackage.applicationInfo.getResourcePath(),
14494                     getAppDexInstructionSets(deletedPackage.applicationInfo));
14495         } else {
14496             res.removedInfo.args = null;
14497         }
14498
14499         // Successfully disabled the old package. Now proceed with re-installation
14500         clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14501                 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14502         clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14503
14504         res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14505         pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14506                 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14507
14508         PackageParser.Package newPackage = null;
14509         try {
14510             // Add the package to the internal data structures
14511             newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14512
14513             // Set the update and install times
14514             PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14515             setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14516                     System.currentTimeMillis());
14517
14518             // Update the package dynamic state if succeeded
14519             if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14520                 // Now that the install succeeded make sure we remove data
14521                 // directories for any child package the update removed.
14522                 final int deletedChildCount = (deletedPackage.childPackages != null)
14523                         ? deletedPackage.childPackages.size() : 0;
14524                 final int newChildCount = (newPackage.childPackages != null)
14525                         ? newPackage.childPackages.size() : 0;
14526                 for (int i = 0; i < deletedChildCount; i++) {
14527                     PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14528                     boolean childPackageDeleted = true;
14529                     for (int j = 0; j < newChildCount; j++) {
14530                         PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14531                         if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14532                             childPackageDeleted = false;
14533                             break;
14534                         }
14535                     }
14536                     if (childPackageDeleted) {
14537                         PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14538                                 deletedChildPkg.packageName);
14539                         if (ps != null && res.removedInfo.removedChildPackages != null) {
14540                             PackageRemovedInfo removedChildRes = res.removedInfo
14541                                     .removedChildPackages.get(deletedChildPkg.packageName);
14542                             removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14543                             removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14544                         }
14545                     }
14546                 }
14547
14548                 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14549                 prepareAppDataAfterInstallLIF(newPackage);
14550             }
14551         } catch (PackageManagerException e) {
14552             res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14553             res.setError("Package couldn't be installed in " + pkg.codePath, e);
14554         }
14555
14556         if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14557             // Re installation failed. Restore old information
14558             // Remove new pkg information
14559             if (newPackage != null) {
14560                 removeInstalledPackageLI(newPackage, true);
14561             }
14562             // Add back the old system package
14563             try {
14564                 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14565             } catch (PackageManagerException e) {
14566                 Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14567             }
14568
14569             synchronized (mPackages) {
14570                 if (disabledSystem) {
14571                     enableSystemPackageLPw(deletedPackage);
14572                 }
14573
14574                 // Ensure the installer package name up to date
14575                 setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14576
14577                 // Update permissions for restored package
14578                 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14579
14580                 mSettings.writeLPr();
14581             }
14582
14583             Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14584                     + " after failed upgrade");
14585         }
14586     }
14587
14588     /**
14589      * Checks whether the parent or any of the child packages have a change shared
14590      * user. For a package to be a valid update the shred users of the parent and
14591      * the children should match. We may later support changing child shared users.
14592      * @param oldPkg The updated package.
14593      * @param newPkg The update package.
14594      * @return The shared user that change between the versions.
14595      */
14596     private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14597             PackageParser.Package newPkg) {
14598         // Check parent shared user
14599         if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14600             return newPkg.packageName;
14601         }
14602         // Check child shared users
14603         final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14604         final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14605         for (int i = 0; i < newChildCount; i++) {
14606             PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14607             // If this child was present, did it have the same shared user?
14608             for (int j = 0; j < oldChildCount; j++) {
14609                 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14610                 if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14611                         && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14612                     return newChildPkg.packageName;
14613                 }
14614             }
14615         }
14616         return null;
14617     }
14618
14619     private void removeNativeBinariesLI(PackageSetting ps) {
14620         // Remove the lib path for the parent package
14621         if (ps != null) {
14622             NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14623             // Remove the lib path for the child packages
14624             final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14625             for (int i = 0; i < childCount; i++) {
14626                 PackageSetting childPs = null;
14627                 synchronized (mPackages) {
14628                     childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14629                 }
14630                 if (childPs != null) {
14631                     NativeLibraryHelper.removeNativeBinariesLI(childPs
14632                             .legacyNativeLibraryPathString);
14633                 }
14634             }
14635         }
14636     }
14637
14638     private void enableSystemPackageLPw(PackageParser.Package pkg) {
14639         // Enable the parent package
14640         mSettings.enableSystemPackageLPw(pkg.packageName);
14641         // Enable the child packages
14642         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14643         for (int i = 0; i < childCount; i++) {
14644             PackageParser.Package childPkg = pkg.childPackages.get(i);
14645             mSettings.enableSystemPackageLPw(childPkg.packageName);
14646         }
14647     }
14648
14649     private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14650             PackageParser.Package newPkg) {
14651         // Disable the parent package (parent always replaced)
14652         boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14653         // Disable the child packages
14654         final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14655         for (int i = 0; i < childCount; i++) {
14656             PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14657             final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14658             disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14659         }
14660         return disabled;
14661     }
14662
14663     private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14664             String installerPackageName) {
14665         // Enable the parent package
14666         mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14667         // Enable the child packages
14668         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14669         for (int i = 0; i < childCount; i++) {
14670             PackageParser.Package childPkg = pkg.childPackages.get(i);
14671             mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14672         }
14673     }
14674
14675     private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14676         // Collect all used permissions in the UID
14677         ArraySet<String> usedPermissions = new ArraySet<>();
14678         final int packageCount = su.packages.size();
14679         for (int i = 0; i < packageCount; i++) {
14680             PackageSetting ps = su.packages.valueAt(i);
14681             if (ps.pkg == null) {
14682                 continue;
14683             }
14684             final int requestedPermCount = ps.pkg.requestedPermissions.size();
14685             for (int j = 0; j < requestedPermCount; j++) {
14686                 String permission = ps.pkg.requestedPermissions.get(j);
14687                 BasePermission bp = mSettings.mPermissions.get(permission);
14688                 if (bp != null) {
14689                     usedPermissions.add(permission);
14690                 }
14691             }
14692         }
14693
14694         PermissionsState permissionsState = su.getPermissionsState();
14695         // Prune install permissions
14696         List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14697         final int installPermCount = installPermStates.size();
14698         for (int i = installPermCount - 1; i >= 0;  i--) {
14699             PermissionState permissionState = installPermStates.get(i);
14700             if (!usedPermissions.contains(permissionState.getName())) {
14701                 BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14702                 if (bp != null) {
14703                     permissionsState.revokeInstallPermission(bp);
14704                     permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14705                             PackageManager.MASK_PERMISSION_FLAGS, 0);
14706                 }
14707             }
14708         }
14709
14710         int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14711
14712         // Prune runtime permissions
14713         for (int userId : allUserIds) {
14714             List<PermissionState> runtimePermStates = permissionsState
14715                     .getRuntimePermissionStates(userId);
14716             final int runtimePermCount = runtimePermStates.size();
14717             for (int i = runtimePermCount - 1; i >= 0; i--) {
14718                 PermissionState permissionState = runtimePermStates.get(i);
14719                 if (!usedPermissions.contains(permissionState.getName())) {
14720                     BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14721                     if (bp != null) {
14722                         permissionsState.revokeRuntimePermission(bp, userId);
14723                         permissionsState.updatePermissionFlags(bp, userId,
14724                                 PackageManager.MASK_PERMISSION_FLAGS, 0);
14725                         runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14726                                 runtimePermissionChangedUserIds, userId);
14727                     }
14728                 }
14729             }
14730         }
14731
14732         return runtimePermissionChangedUserIds;
14733     }
14734
14735     private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14736             int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14737         // Update the parent package setting
14738         updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14739                 res, user);
14740         // Update the child packages setting
14741         final int childCount = (newPackage.childPackages != null)
14742                 ? newPackage.childPackages.size() : 0;
14743         for (int i = 0; i < childCount; i++) {
14744             PackageParser.Package childPackage = newPackage.childPackages.get(i);
14745             PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14746             updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14747                     childRes.origUsers, childRes, user);
14748         }
14749     }
14750
14751     private void updateSettingsInternalLI(PackageParser.Package newPackage,
14752             String installerPackageName, int[] allUsers, int[] installedForUsers,
14753             PackageInstalledInfo res, UserHandle user) {
14754         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14755
14756         String pkgName = newPackage.packageName;
14757         synchronized (mPackages) {
14758             //write settings. the installStatus will be incomplete at this stage.
14759             //note that the new package setting would have already been
14760             //added to mPackages. It hasn't been persisted yet.
14761             mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14762             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14763             mSettings.writeLPr();
14764             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14765         }
14766
14767         if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14768         synchronized (mPackages) {
14769             updatePermissionsLPw(newPackage.packageName, newPackage,
14770                     UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14771                             ? UPDATE_PERMISSIONS_ALL : 0));
14772             // For system-bundled packages, we assume that installing an upgraded version
14773             // of the package implies that the user actually wants to run that new code,
14774             // so we enable the package.
14775             PackageSetting ps = mSettings.mPackages.get(pkgName);
14776             final int userId = user.getIdentifier();
14777             if (ps != null) {
14778                 if (isSystemApp(newPackage)) {
14779                     if (DEBUG_INSTALL) {
14780                         Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14781                     }
14782                     // Enable system package for requested users
14783                     if (res.origUsers != null) {
14784                         for (int origUserId : res.origUsers) {
14785                             if (userId == UserHandle.USER_ALL || userId == origUserId) {
14786                                 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14787                                         origUserId, installerPackageName);
14788                             }
14789                         }
14790                     }
14791                     // Also convey the prior install/uninstall state
14792                     if (allUsers != null && installedForUsers != null) {
14793                         for (int currentUserId : allUsers) {
14794                             final boolean installed = ArrayUtils.contains(
14795                                     installedForUsers, currentUserId);
14796                             if (DEBUG_INSTALL) {
14797                                 Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14798                             }
14799                             ps.setInstalled(installed, currentUserId);
14800                         }
14801                         // these install state changes will be persisted in the
14802                         // upcoming call to mSettings.writeLPr().
14803                     }
14804                 }
14805                 // It's implied that when a user requests installation, they want the app to be
14806                 // installed and enabled.
14807                 if (userId != UserHandle.USER_ALL) {
14808                     ps.setInstalled(true, userId);
14809                     ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14810                 }
14811             }
14812             res.name = pkgName;
14813             res.uid = newPackage.applicationInfo.uid;
14814             res.pkg = newPackage;
14815             mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14816             mSettings.setInstallerPackageName(pkgName, installerPackageName);
14817             res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14818             //to update install status
14819             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14820             mSettings.writeLPr();
14821             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14822         }
14823
14824         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14825     }
14826
14827     private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14828         try {
14829             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14830             installPackageLI(args, res);
14831         } finally {
14832             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14833         }
14834     }
14835
14836     private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14837         final int installFlags = args.installFlags;
14838         final String installerPackageName = args.installerPackageName;
14839         final String volumeUuid = args.volumeUuid;
14840         final File tmpPackageFile = new File(args.getCodePath());
14841         final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14842         final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14843                 || (args.volumeUuid != null));
14844         final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14845         final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14846         boolean replace = false;
14847         int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14848         if (args.move != null) {
14849             // moving a complete application; perform an initial scan on the new install location
14850             scanFlags |= SCAN_INITIAL;
14851         }
14852         if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14853             scanFlags |= SCAN_DONT_KILL_APP;
14854         }
14855
14856         // Result object to be returned
14857         res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14858
14859         if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14860
14861         // Sanity check
14862         if (ephemeral && (forwardLocked || onExternal)) {
14863             Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14864                     + " external=" + onExternal);
14865             res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14866             return;
14867         }
14868
14869         // Retrieve PackageSettings and parse package
14870         final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14871                 | PackageParser.PARSE_ENFORCE_CODE
14872                 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14873                 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14874                 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14875                 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14876         PackageParser pp = new PackageParser();
14877         pp.setSeparateProcesses(mSeparateProcesses);
14878         pp.setDisplayMetrics(mMetrics);
14879
14880         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14881         final PackageParser.Package pkg;
14882         try {
14883             pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14884         } catch (PackageParserException e) {
14885             res.setError("Failed parse during installPackageLI", e);
14886             return;
14887         } finally {
14888             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14889         }
14890
14891         // If we are installing a clustered package add results for the children
14892         if (pkg.childPackages != null) {
14893             synchronized (mPackages) {
14894                 final int childCount = pkg.childPackages.size();
14895                 for (int i = 0; i < childCount; i++) {
14896                     PackageParser.Package childPkg = pkg.childPackages.get(i);
14897                     PackageInstalledInfo childRes = new PackageInstalledInfo();
14898                     childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14899                     childRes.pkg = childPkg;
14900                     childRes.name = childPkg.packageName;
14901                     PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14902                     if (childPs != null) {
14903                         childRes.origUsers = childPs.queryInstalledUsers(
14904                                 sUserManager.getUserIds(), true);
14905                     }
14906                     if ((mPackages.containsKey(childPkg.packageName))) {
14907                         childRes.removedInfo = new PackageRemovedInfo();
14908                         childRes.removedInfo.removedPackage = childPkg.packageName;
14909                     }
14910                     if (res.addedChildPackages == null) {
14911                         res.addedChildPackages = new ArrayMap<>();
14912                     }
14913                     res.addedChildPackages.put(childPkg.packageName, childRes);
14914                 }
14915             }
14916         }
14917
14918         // If package doesn't declare API override, mark that we have an install
14919         // time CPU ABI override.
14920         if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14921             pkg.cpuAbiOverride = args.abiOverride;
14922         }
14923
14924         String pkgName = res.name = pkg.packageName;
14925         if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14926             if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14927                 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14928                 return;
14929             }
14930         }
14931
14932         try {
14933             // either use what we've been given or parse directly from the APK
14934             if (args.certificates != null) {
14935                 try {
14936                     PackageParser.populateCertificates(pkg, args.certificates);
14937                 } catch (PackageParserException e) {
14938                     // there was something wrong with the certificates we were given;
14939                     // try to pull them from the APK
14940                     PackageParser.collectCertificates(pkg, parseFlags);
14941                 }
14942             } else {
14943                 PackageParser.collectCertificates(pkg, parseFlags);
14944             }
14945         } catch (PackageParserException e) {
14946             res.setError("Failed collect during installPackageLI", e);
14947             return;
14948         }
14949
14950         // Get rid of all references to package scan path via parser.
14951         pp = null;
14952         String oldCodePath = null;
14953         boolean systemApp = false;
14954         synchronized (mPackages) {
14955             // Check if installing already existing package
14956             if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14957                 String oldName = mSettings.mRenamedPackages.get(pkgName);
14958                 if (pkg.mOriginalPackages != null
14959                         && pkg.mOriginalPackages.contains(oldName)
14960                         && mPackages.containsKey(oldName)) {
14961                     // This package is derived from an original package,
14962                     // and this device has been updating from that original
14963                     // name.  We must continue using the original name, so
14964                     // rename the new package here.
14965                     pkg.setPackageName(oldName);
14966                     pkgName = pkg.packageName;
14967                     replace = true;
14968                     if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14969                             + oldName + " pkgName=" + pkgName);
14970                 } else if (mPackages.containsKey(pkgName)) {
14971                     // This package, under its official name, already exists
14972                     // on the device; we should replace it.
14973                     replace = true;
14974                     if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14975                 }
14976
14977                 // Child packages are installed through the parent package
14978                 if (pkg.parentPackage != null) {
14979                     res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14980                             "Package " + pkg.packageName + " is child of package "
14981                                     + pkg.parentPackage.parentPackage + ". Child packages "
14982                                     + "can be updated only through the parent package.");
14983                     return;
14984                 }
14985
14986                 if (replace) {
14987                     // Prevent apps opting out from runtime permissions
14988                     PackageParser.Package oldPackage = mPackages.get(pkgName);
14989                     final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14990                     final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14991                     if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14992                             && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14993                         res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14994                                 "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14995                                         + " doesn't support runtime permissions but the old"
14996                                         + " target SDK " + oldTargetSdk + " does.");
14997                         return;
14998                     }
14999
15000                     // Prevent installing of child packages
15001                     if (oldPackage.parentPackage != null) {
15002                         res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15003                                 "Package " + pkg.packageName + " is child of package "
15004                                         + oldPackage.parentPackage + ". Child packages "
15005                                         + "can be updated only through the parent package.");
15006                         return;
15007                     }
15008                 }
15009             }
15010
15011             PackageSetting ps = mSettings.mPackages.get(pkgName);
15012             if (ps != null) {
15013                 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15014
15015                 // Quick sanity check that we're signed correctly if updating;
15016                 // we'll check this again later when scanning, but we want to
15017                 // bail early here before tripping over redefined permissions.
15018                 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15019                     if (!checkUpgradeKeySetLP(ps, pkg)) {
15020                         res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15021                                 + pkg.packageName + " upgrade keys do not match the "
15022                                 + "previously installed version");
15023                         return;
15024                     }
15025                 } else {
15026                     try {
15027                         verifySignaturesLP(ps, pkg);
15028                     } catch (PackageManagerException e) {
15029                         res.setError(e.error, e.getMessage());
15030                         return;
15031                     }
15032                 }
15033
15034                 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15035                 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15036                     systemApp = (ps.pkg.applicationInfo.flags &
15037                             ApplicationInfo.FLAG_SYSTEM) != 0;
15038                 }
15039                 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15040             }
15041
15042             // Check whether the newly-scanned package wants to define an already-defined perm
15043             int N = pkg.permissions.size();
15044             for (int i = N-1; i >= 0; i--) {
15045                 PackageParser.Permission perm = pkg.permissions.get(i);
15046                 BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15047                 if (bp != null) {
15048                     // If the defining package is signed with our cert, it's okay.  This
15049                     // also includes the "updating the same package" case, of course.
15050                     // "updating same package" could also involve key-rotation.
15051                     final boolean sigsOk;
15052                     if (bp.sourcePackage.equals(pkg.packageName)
15053                             && (bp.packageSetting instanceof PackageSetting)
15054                             && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15055                                     scanFlags))) {
15056                         sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15057                     } else {
15058                         sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15059                                 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15060                     }
15061                     if (!sigsOk) {
15062                         // If the owning package is the system itself, we log but allow
15063                         // install to proceed; we fail the install on all other permission
15064                         // redefinitions.
15065                         if (!bp.sourcePackage.equals("android")) {
15066                             res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15067                                     + pkg.packageName + " attempting to redeclare permission "
15068                                     + perm.info.name + " already owned by " + bp.sourcePackage);
15069                             res.origPermission = perm.info.name;
15070                             res.origPackage = bp.sourcePackage;
15071                             return;
15072                         } else {
15073                             Slog.w(TAG, "Package " + pkg.packageName
15074                                     + " attempting to redeclare system permission "
15075                                     + perm.info.name + "; ignoring new declaration");
15076                             pkg.permissions.remove(i);
15077                         }
15078                     }
15079                 }
15080             }
15081         }
15082
15083         if (systemApp) {
15084             if (onExternal) {
15085                 // Abort update; system app can't be replaced with app on sdcard
15086                 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15087                         "Cannot install updates to system apps on sdcard");
15088                 return;
15089             } else if (ephemeral) {
15090                 // Abort update; system app can't be replaced with an ephemeral app
15091                 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15092                         "Cannot update a system app with an ephemeral app");
15093                 return;
15094             }
15095         }
15096
15097         if (args.move != null) {
15098             // We did an in-place move, so dex is ready to roll
15099             scanFlags |= SCAN_NO_DEX;
15100             scanFlags |= SCAN_MOVE;
15101
15102             synchronized (mPackages) {
15103                 final PackageSetting ps = mSettings.mPackages.get(pkgName);
15104                 if (ps == null) {
15105                     res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15106                             "Missing settings for moved package " + pkgName);
15107                 }
15108
15109                 // We moved the entire application as-is, so bring over the
15110                 // previously derived ABI information.
15111                 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15112                 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15113             }
15114
15115         } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15116             // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15117             scanFlags |= SCAN_NO_DEX;
15118
15119             try {
15120                 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15121                     args.abiOverride : pkg.cpuAbiOverride);
15122                 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15123                         true /* extract libs */);
15124             } catch (PackageManagerException pme) {
15125                 Slog.e(TAG, "Error deriving application ABI", pme);
15126                 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15127                 return;
15128             }
15129
15130             // Shared libraries for the package need to be updated.
15131             synchronized (mPackages) {
15132                 try {
15133                     updateSharedLibrariesLPw(pkg, null);
15134                 } catch (PackageManagerException e) {
15135                     Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15136                 }
15137             }
15138             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15139             // Do not run PackageDexOptimizer through the local performDexOpt
15140             // method because `pkg` may not be in `mPackages` yet.
15141             //
15142             // Also, don't fail application installs if the dexopt step fails.
15143             mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15144                     null /* instructionSets */, false /* checkProfiles */,
15145                     getCompilerFilterForReason(REASON_INSTALL));
15146             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15147
15148             // Notify BackgroundDexOptService that the package has been changed.
15149             // If this is an update of a package which used to fail to compile,
15150             // BDOS will remove it from its blacklist.
15151             BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15152         }
15153
15154         if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15155             res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15156             return;
15157         }
15158
15159         startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15160
15161         try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15162                 "installPackageLI")) {
15163             if (replace) {
15164                 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15165                         installerPackageName, res);
15166             } else {
15167                 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15168                         args.user, installerPackageName, volumeUuid, res);
15169             }
15170         }
15171         synchronized (mPackages) {
15172             final PackageSetting ps = mSettings.mPackages.get(pkgName);
15173             if (ps != null) {
15174                 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15175             }
15176
15177             final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15178             for (int i = 0; i < childCount; i++) {
15179                 PackageParser.Package childPkg = pkg.childPackages.get(i);
15180                 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15181                 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15182                 if (childPs != null) {
15183                     childRes.newUsers = childPs.queryInstalledUsers(
15184                             sUserManager.getUserIds(), true);
15185                 }
15186             }
15187         }
15188     }
15189
15190     private void startIntentFilterVerifications(int userId, boolean replacing,
15191             PackageParser.Package pkg) {
15192         if (mIntentFilterVerifierComponent == null) {
15193             Slog.w(TAG, "No IntentFilter verification will not be done as "
15194                     + "there is no IntentFilterVerifier available!");
15195             return;
15196         }
15197
15198         final int verifierUid = getPackageUid(
15199                 mIntentFilterVerifierComponent.getPackageName(),
15200                 MATCH_DEBUG_TRIAGED_MISSING,
15201                 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15202
15203         Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15204         msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15205         mHandler.sendMessage(msg);
15206
15207         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15208         for (int i = 0; i < childCount; i++) {
15209             PackageParser.Package childPkg = pkg.childPackages.get(i);
15210             msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15211             msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15212             mHandler.sendMessage(msg);
15213         }
15214     }
15215
15216     private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15217             PackageParser.Package pkg) {
15218         int size = pkg.activities.size();
15219         if (size == 0) {
15220             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15221                     "No activity, so no need to verify any IntentFilter!");
15222             return;
15223         }
15224
15225         final boolean hasDomainURLs = hasDomainURLs(pkg);
15226         if (!hasDomainURLs) {
15227             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15228                     "No domain URLs, so no need to verify any IntentFilter!");
15229             return;
15230         }
15231
15232         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15233                 + " if any IntentFilter from the " + size
15234                 + " Activities needs verification ...");
15235
15236         int count = 0;
15237         final String packageName = pkg.packageName;
15238
15239         synchronized (mPackages) {
15240             // If this is a new install and we see that we've already run verification for this
15241             // package, we have nothing to do: it means the state was restored from backup.
15242             if (!replacing) {
15243                 IntentFilterVerificationInfo ivi =
15244                         mSettings.getIntentFilterVerificationLPr(packageName);
15245                 if (ivi != null) {
15246                     if (DEBUG_DOMAIN_VERIFICATION) {
15247                         Slog.i(TAG, "Package " + packageName+ " already verified: status="
15248                                 + ivi.getStatusString());
15249                     }
15250                     return;
15251                 }
15252             }
15253
15254             // If any filters need to be verified, then all need to be.
15255             boolean needToVerify = false;
15256             for (PackageParser.Activity a : pkg.activities) {
15257                 for (ActivityIntentInfo filter : a.intents) {
15258                     if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15259                         if (DEBUG_DOMAIN_VERIFICATION) {
15260                             Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15261                         }
15262                         needToVerify = true;
15263                         break;
15264                     }
15265                 }
15266             }
15267
15268             if (needToVerify) {
15269                 final int verificationId = mIntentFilterVerificationToken++;
15270                 for (PackageParser.Activity a : pkg.activities) {
15271                     for (ActivityIntentInfo filter : a.intents) {
15272                         if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15273                             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15274                                     "Verification needed for IntentFilter:" + filter.toString());
15275                             mIntentFilterVerifier.addOneIntentFilterVerification(
15276                                     verifierUid, userId, verificationId, filter, packageName);
15277                             count++;
15278                         }
15279                     }
15280                 }
15281             }
15282         }
15283
15284         if (count > 0) {
15285             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15286                     + " IntentFilter verification" + (count > 1 ? "s" : "")
15287                     +  " for userId:" + userId);
15288             mIntentFilterVerifier.startVerifications(userId);
15289         } else {
15290             if (DEBUG_DOMAIN_VERIFICATION) {
15291                 Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15292             }
15293         }
15294     }
15295
15296     private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15297         final ComponentName cn  = filter.activity.getComponentName();
15298         final String packageName = cn.getPackageName();
15299
15300         IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15301                 packageName);
15302         if (ivi == null) {
15303             return true;
15304         }
15305         int status = ivi.getStatus();
15306         switch (status) {
15307             case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15308             case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15309                 return true;
15310
15311             default:
15312                 // Nothing to do
15313                 return false;
15314         }
15315     }
15316
15317     private static boolean isMultiArch(ApplicationInfo info) {
15318         return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15319     }
15320
15321     private static boolean isExternal(PackageParser.Package pkg) {
15322         return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15323     }
15324
15325     private static boolean isExternal(PackageSetting ps) {
15326         return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15327     }
15328
15329     private static boolean isEphemeral(PackageParser.Package pkg) {
15330         return pkg.applicationInfo.isEphemeralApp();
15331     }
15332
15333     private static boolean isEphemeral(PackageSetting ps) {
15334         return ps.pkg != null && isEphemeral(ps.pkg);
15335     }
15336
15337     private static boolean isSystemApp(PackageParser.Package pkg) {
15338         return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15339     }
15340
15341     private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15342         return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15343     }
15344
15345     private static boolean hasDomainURLs(PackageParser.Package pkg) {
15346         return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15347     }
15348
15349     private static boolean isSystemApp(PackageSetting ps) {
15350         return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15351     }
15352
15353     private static boolean isUpdatedSystemApp(PackageSetting ps) {
15354         return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15355     }
15356
15357     private int packageFlagsToInstallFlags(PackageSetting ps) {
15358         int installFlags = 0;
15359         if (isEphemeral(ps)) {
15360             installFlags |= PackageManager.INSTALL_EPHEMERAL;
15361         }
15362         if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15363             // This existing package was an external ASEC install when we have
15364             // the external flag without a UUID
15365             installFlags |= PackageManager.INSTALL_EXTERNAL;
15366         }
15367         if (ps.isForwardLocked()) {
15368             installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15369         }
15370         return installFlags;
15371     }
15372
15373     private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15374         if (isExternal(pkg)) {
15375             if (TextUtils.isEmpty(pkg.volumeUuid)) {
15376                 return StorageManager.UUID_PRIMARY_PHYSICAL;
15377             } else {
15378                 return pkg.volumeUuid;
15379             }
15380         } else {
15381             return StorageManager.UUID_PRIVATE_INTERNAL;
15382         }
15383     }
15384
15385     private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15386         if (isExternal(pkg)) {
15387             if (TextUtils.isEmpty(pkg.volumeUuid)) {
15388                 return mSettings.getExternalVersion();
15389             } else {
15390                 return mSettings.findOrCreateVersion(pkg.volumeUuid);
15391             }
15392         } else {
15393             return mSettings.getInternalVersion();
15394         }
15395     }
15396
15397     private void deleteTempPackageFiles() {
15398         final FilenameFilter filter = new FilenameFilter() {
15399             public boolean accept(File dir, String name) {
15400                 return name.startsWith("vmdl") && name.endsWith(".tmp");
15401             }
15402         };
15403         for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15404             file.delete();
15405         }
15406     }
15407
15408     @Override
15409     public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15410             int flags) {
15411         deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15412                 flags);
15413     }
15414
15415     @Override
15416     public void deletePackage(final String packageName,
15417             final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15418         mContext.enforceCallingOrSelfPermission(
15419                 android.Manifest.permission.DELETE_PACKAGES, null);
15420         Preconditions.checkNotNull(packageName);
15421         Preconditions.checkNotNull(observer);
15422         final int uid = Binder.getCallingUid();
15423         final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15424         final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15425         if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15426             mContext.enforceCallingOrSelfPermission(
15427                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15428                     "deletePackage for user " + userId);
15429         }
15430
15431         if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15432             try {
15433                 observer.onPackageDeleted(packageName,
15434                         PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15435             } catch (RemoteException re) {
15436             }
15437             return;
15438         }
15439
15440         if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15441             try {
15442                 observer.onPackageDeleted(packageName,
15443                         PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15444             } catch (RemoteException re) {
15445             }
15446             return;
15447         }
15448
15449         if (DEBUG_REMOVE) {
15450             Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15451                     + " deleteAllUsers: " + deleteAllUsers );
15452         }
15453         // Queue up an async operation since the package deletion may take a little while.
15454         mHandler.post(new Runnable() {
15455             public void run() {
15456                 mHandler.removeCallbacks(this);
15457                 int returnCode;
15458                 if (!deleteAllUsers) {
15459                     returnCode = deletePackageX(packageName, userId, deleteFlags);
15460                 } else {
15461                     int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15462                     // If nobody is blocking uninstall, proceed with delete for all users
15463                     if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15464                         returnCode = deletePackageX(packageName, userId, deleteFlags);
15465                     } else {
15466                         // Otherwise uninstall individually for users with blockUninstalls=false
15467                         final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15468                         for (int userId : users) {
15469                             if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15470                                 returnCode = deletePackageX(packageName, userId, userFlags);
15471                                 if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15472                                     Slog.w(TAG, "Package delete failed for user " + userId
15473                                             + ", returnCode " + returnCode);
15474                                 }
15475                             }
15476                         }
15477                         // The app has only been marked uninstalled for certain users.
15478                         // We still need to report that delete was blocked
15479                         returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15480                     }
15481                 }
15482                 try {
15483                     observer.onPackageDeleted(packageName, returnCode, null);
15484                 } catch (RemoteException e) {
15485                     Log.i(TAG, "Observer no longer exists.");
15486                 } //end catch
15487             } //end run
15488         });
15489     }
15490
15491     private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15492         int[] result = EMPTY_INT_ARRAY;
15493         for (int userId : userIds) {
15494             if (getBlockUninstallForUser(packageName, userId)) {
15495                 result = ArrayUtils.appendInt(result, userId);
15496             }
15497         }
15498         return result;
15499     }
15500
15501     @Override
15502     public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15503         return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15504     }
15505
15506     private boolean isPackageDeviceAdmin(String packageName, int userId) {
15507         IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15508                 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15509         try {
15510             if (dpm != null) {
15511                 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15512                         /* callingUserOnly =*/ false);
15513                 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15514                         : deviceOwnerComponentName.getPackageName();
15515                 // Does the package contains the device owner?
15516                 // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15517                 // this check is probably not needed, since DO should be registered as a device
15518                 // admin on some user too. (Original bug for this: b/17657954)
15519                 if (packageName.equals(deviceOwnerPackageName)) {
15520                     return true;
15521                 }
15522                 // Does it contain a device admin for any user?
15523                 int[] users;
15524                 if (userId == UserHandle.USER_ALL) {
15525                     users = sUserManager.getUserIds();
15526                 } else {
15527                     users = new int[]{userId};
15528                 }
15529                 for (int i = 0; i < users.length; ++i) {
15530                     if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15531                         return true;
15532                     }
15533                 }
15534             }
15535         } catch (RemoteException e) {
15536         }
15537         return false;
15538     }
15539
15540     private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15541         return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15542     }
15543
15544     /**
15545      *  This method is an internal method that could be get invoked either
15546      *  to delete an installed package or to clean up a failed installation.
15547      *  After deleting an installed package, a broadcast is sent to notify any
15548      *  listeners that the package has been removed. For cleaning up a failed
15549      *  installation, the broadcast is not necessary since the package's
15550      *  installation wouldn't have sent the initial broadcast either
15551      *  The key steps in deleting a package are
15552      *  deleting the package information in internal structures like mPackages,
15553      *  deleting the packages base directories through installd
15554      *  updating mSettings to reflect current status
15555      *  persisting settings for later use
15556      *  sending a broadcast if necessary
15557      */
15558     private int deletePackageX(String packageName, int userId, int deleteFlags) {
15559         final PackageRemovedInfo info = new PackageRemovedInfo();
15560         final boolean res;
15561
15562         final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15563                 ? UserHandle.USER_ALL : userId;
15564
15565         if (isPackageDeviceAdmin(packageName, removeUser)) {
15566             Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15567             return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15568         }
15569
15570         PackageSetting uninstalledPs = null;
15571
15572         // for the uninstall-updates case and restricted profiles, remember the per-
15573         // user handle installed state
15574         int[] allUsers;
15575         synchronized (mPackages) {
15576             uninstalledPs = mSettings.mPackages.get(packageName);
15577             if (uninstalledPs == null) {
15578                 Slog.w(TAG, "Not removing non-existent package " + packageName);
15579                 return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15580             }
15581             allUsers = sUserManager.getUserIds();
15582             info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15583         }
15584
15585         final int freezeUser;
15586         if (isUpdatedSystemApp(uninstalledPs)
15587                 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15588             // We're downgrading a system app, which will apply to all users, so
15589             // freeze them all during the downgrade
15590             freezeUser = UserHandle.USER_ALL;
15591         } else {
15592             freezeUser = removeUser;
15593         }
15594
15595         synchronized (mInstallLock) {
15596             if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15597             try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15598                     deleteFlags, "deletePackageX")) {
15599                 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15600                         deleteFlags | REMOVE_CHATTY, info, true, null);
15601             }
15602             synchronized (mPackages) {
15603                 if (res) {
15604                     mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15605                 }
15606             }
15607         }
15608
15609         if (res) {
15610             final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15611             info.sendPackageRemovedBroadcasts(killApp);
15612             info.sendSystemPackageUpdatedBroadcasts();
15613             info.sendSystemPackageAppearedBroadcasts();
15614         }
15615         // Force a gc here.
15616         Runtime.getRuntime().gc();
15617         // Delete the resources here after sending the broadcast to let
15618         // other processes clean up before deleting resources.
15619         if (info.args != null) {
15620             synchronized (mInstallLock) {
15621                 info.args.doPostDeleteLI(true);
15622             }
15623         }
15624
15625         return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15626     }
15627
15628     class PackageRemovedInfo {
15629         String removedPackage;
15630         int uid = -1;
15631         int removedAppId = -1;
15632         int[] origUsers;
15633         int[] removedUsers = null;
15634         boolean isRemovedPackageSystemUpdate = false;
15635         boolean isUpdate;
15636         boolean dataRemoved;
15637         boolean removedForAllUsers;
15638         // Clean up resources deleted packages.
15639         InstallArgs args = null;
15640         ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15641         ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15642
15643         void sendPackageRemovedBroadcasts(boolean killApp) {
15644             sendPackageRemovedBroadcastInternal(killApp);
15645             final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15646             for (int i = 0; i < childCount; i++) {
15647                 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15648                 childInfo.sendPackageRemovedBroadcastInternal(killApp);
15649             }
15650         }
15651
15652         void sendSystemPackageUpdatedBroadcasts() {
15653             if (isRemovedPackageSystemUpdate) {
15654                 sendSystemPackageUpdatedBroadcastsInternal();
15655                 final int childCount = (removedChildPackages != null)
15656                         ? removedChildPackages.size() : 0;
15657                 for (int i = 0; i < childCount; i++) {
15658                     PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15659                     if (childInfo.isRemovedPackageSystemUpdate) {
15660                         childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15661                     }
15662                 }
15663             }
15664         }
15665
15666         void sendSystemPackageAppearedBroadcasts() {
15667             final int packageCount = (appearedChildPackages != null)
15668                     ? appearedChildPackages.size() : 0;
15669             for (int i = 0; i < packageCount; i++) {
15670                 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15671                 for (int userId : installedInfo.newUsers) {
15672                     sendPackageAddedForUser(installedInfo.name, true,
15673                             UserHandle.getAppId(installedInfo.uid), userId);
15674                 }
15675             }
15676         }
15677
15678         private void sendSystemPackageUpdatedBroadcastsInternal() {
15679             Bundle extras = new Bundle(2);
15680             extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15681             extras.putBoolean(Intent.EXTRA_REPLACING, true);
15682             sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15683                     extras, 0, null, null, null);
15684             sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15685                     extras, 0, null, null, null);
15686             sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15687                     null, 0, removedPackage, null, null);
15688         }
15689
15690         private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15691             Bundle extras = new Bundle(2);
15692             extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15693             extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15694             extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15695             if (isUpdate || isRemovedPackageSystemUpdate) {
15696                 extras.putBoolean(Intent.EXTRA_REPLACING, true);
15697             }
15698             extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15699             if (removedPackage != null) {
15700                 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15701                         extras, 0, null, null, removedUsers);
15702                 if (dataRemoved && !isRemovedPackageSystemUpdate) {
15703                     sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15704                             removedPackage, extras, 0, null, null, removedUsers);
15705                 }
15706             }
15707             if (removedAppId >= 0) {
15708                 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15709                         removedUsers);
15710             }
15711         }
15712     }
15713
15714     /*
15715      * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15716      * flag is not set, the data directory is removed as well.
15717      * make sure this flag is set for partially installed apps. If not its meaningless to
15718      * delete a partially installed application.
15719      */
15720     private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15721             PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15722         String packageName = ps.name;
15723         if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15724         // Retrieve object to delete permissions for shared user later on
15725         final PackageParser.Package deletedPkg;
15726         final PackageSetting deletedPs;
15727         // reader
15728         synchronized (mPackages) {
15729             deletedPkg = mPackages.get(packageName);
15730             deletedPs = mSettings.mPackages.get(packageName);
15731             if (outInfo != null) {
15732                 outInfo.removedPackage = packageName;
15733                 outInfo.removedUsers = deletedPs != null
15734                         ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15735                         : null;
15736             }
15737         }
15738
15739         removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15740
15741         if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15742             final PackageParser.Package resolvedPkg;
15743             if (deletedPkg != null) {
15744                 resolvedPkg = deletedPkg;
15745             } else {
15746                 // We don't have a parsed package when it lives on an ejected
15747                 // adopted storage device, so fake something together
15748                 resolvedPkg = new PackageParser.Package(ps.name);
15749                 resolvedPkg.setVolumeUuid(ps.volumeUuid);
15750             }
15751             destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15752                     StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15753             destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15754             if (outInfo != null) {
15755                 outInfo.dataRemoved = true;
15756             }
15757             schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15758         }
15759
15760         // writer
15761         synchronized (mPackages) {
15762             if (deletedPs != null) {
15763                 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15764                     clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15765                     clearDefaultBrowserIfNeeded(packageName);
15766                     if (outInfo != null) {
15767                         mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15768                         outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15769                     }
15770                     updatePermissionsLPw(deletedPs.name, null, 0);
15771                     if (deletedPs.sharedUser != null) {
15772                         // Remove permissions associated with package. Since runtime
15773                         // permissions are per user we have to kill the removed package
15774                         // or packages running under the shared user of the removed
15775                         // package if revoking the permissions requested only by the removed
15776                         // package is successful and this causes a change in gids.
15777                         for (int userId : UserManagerService.getInstance().getUserIds()) {
15778                             final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15779                                     userId);
15780                             if (userIdToKill == UserHandle.USER_ALL
15781                                     || userIdToKill >= UserHandle.USER_SYSTEM) {
15782                                 // If gids changed for this user, kill all affected packages.
15783                                 mHandler.post(new Runnable() {
15784                                     @Override
15785                                     public void run() {
15786                                         // This has to happen with no lock held.
15787                                         killApplication(deletedPs.name, deletedPs.appId,
15788                                                 KILL_APP_REASON_GIDS_CHANGED);
15789                                     }
15790                                 });
15791                                 break;
15792                             }
15793                         }
15794                     }
15795                     clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15796                 }
15797                 // make sure to preserve per-user disabled state if this removal was just
15798                 // a downgrade of a system app to the factory package
15799                 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15800                     if (DEBUG_REMOVE) {
15801                         Slog.d(TAG, "Propagating install state across downgrade");
15802                     }
15803                     for (int userId : allUserHandles) {
15804                         final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15805                         if (DEBUG_REMOVE) {
15806                             Slog.d(TAG, "    user " + userId + " => " + installed);
15807                         }
15808                         ps.setInstalled(installed, userId);
15809                     }
15810                 }
15811             }
15812             // can downgrade to reader
15813             if (writeSettings) {
15814                 // Save settings now
15815                 mSettings.writeLPr();
15816             }
15817         }
15818         if (outInfo != null) {
15819             // A user ID was deleted here. Go through all users and remove it
15820             // from KeyStore.
15821             removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15822         }
15823     }
15824
15825     static boolean locationIsPrivileged(File path) {
15826         try {
15827             final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15828                     .getCanonicalPath();
15829             return path.getCanonicalPath().startsWith(privilegedAppDir);
15830         } catch (IOException e) {
15831             Slog.e(TAG, "Unable to access code path " + path);
15832         }
15833         return false;
15834     }
15835
15836     /*
15837      * Tries to delete system package.
15838      */
15839     private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15840             PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15841             boolean writeSettings) {
15842         if (deletedPs.parentPackageName != null) {
15843             Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15844             return false;
15845         }
15846
15847         final boolean applyUserRestrictions
15848                 = (allUserHandles != null) && (outInfo.origUsers != null);
15849         final PackageSetting disabledPs;
15850         // Confirm if the system package has been updated
15851         // An updated system app can be deleted. This will also have to restore
15852         // the system pkg from system partition
15853         // reader
15854         synchronized (mPackages) {
15855             disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15856         }
15857
15858         if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15859                 + " disabledPs=" + disabledPs);
15860
15861         if (disabledPs == null) {
15862             Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15863             return false;
15864         } else if (DEBUG_REMOVE) {
15865             Slog.d(TAG, "Deleting system pkg from data partition");
15866         }
15867
15868         if (DEBUG_REMOVE) {
15869             if (applyUserRestrictions) {
15870                 Slog.d(TAG, "Remembering install states:");
15871                 for (int userId : allUserHandles) {
15872                     final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15873                     Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15874                 }
15875             }
15876         }
15877
15878         // Delete the updated package
15879         outInfo.isRemovedPackageSystemUpdate = true;
15880         if (outInfo.removedChildPackages != null) {
15881             final int childCount = (deletedPs.childPackageNames != null)
15882                     ? deletedPs.childPackageNames.size() : 0;
15883             for (int i = 0; i < childCount; i++) {
15884                 String childPackageName = deletedPs.childPackageNames.get(i);
15885                 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15886                         .contains(childPackageName)) {
15887                     PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15888                             childPackageName);
15889                     if (childInfo != null) {
15890                         childInfo.isRemovedPackageSystemUpdate = true;
15891                     }
15892                 }
15893             }
15894         }
15895
15896         if (disabledPs.versionCode < deletedPs.versionCode) {
15897             // Delete data for downgrades
15898             flags &= ~PackageManager.DELETE_KEEP_DATA;
15899         } else {
15900             // Preserve data by setting flag
15901             flags |= PackageManager.DELETE_KEEP_DATA;
15902         }
15903
15904         boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15905                 outInfo, writeSettings, disabledPs.pkg);
15906         if (!ret) {
15907             return false;
15908         }
15909
15910         // writer
15911         synchronized (mPackages) {
15912             // Reinstate the old system package
15913             enableSystemPackageLPw(disabledPs.pkg);
15914             // Remove any native libraries from the upgraded package.
15915             removeNativeBinariesLI(deletedPs);
15916         }
15917
15918         // Install the system package
15919         if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15920         int parseFlags = mDefParseFlags
15921                 | PackageParser.PARSE_MUST_BE_APK
15922                 | PackageParser.PARSE_IS_SYSTEM
15923                 | PackageParser.PARSE_IS_SYSTEM_DIR;
15924         if (locationIsPrivileged(disabledPs.codePath)) {
15925             parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15926         }
15927
15928         final PackageParser.Package newPkg;
15929         try {
15930             newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15931         } catch (PackageManagerException e) {
15932             Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15933                     + e.getMessage());
15934             return false;
15935         }
15936         try {
15937             // update shared libraries for the newly re-installed system package
15938             updateSharedLibrariesLPw(newPkg, null);
15939         } catch (PackageManagerException e) {
15940             Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
15941         }
15942
15943         prepareAppDataAfterInstallLIF(newPkg);
15944
15945         // writer
15946         synchronized (mPackages) {
15947             PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15948
15949             // Propagate the permissions state as we do not want to drop on the floor
15950             // runtime permissions. The update permissions method below will take
15951             // care of removing obsolete permissions and grant install permissions.
15952             ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15953             updatePermissionsLPw(newPkg.packageName, newPkg,
15954                     UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15955
15956             if (applyUserRestrictions) {
15957                 if (DEBUG_REMOVE) {
15958                     Slog.d(TAG, "Propagating install state across reinstall");
15959                 }
15960                 for (int userId : allUserHandles) {
15961                     final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15962                     if (DEBUG_REMOVE) {
15963                         Slog.d(TAG, "    user " + userId + " => " + installed);
15964                     }
15965                     ps.setInstalled(installed, userId);
15966
15967                     mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15968                 }
15969                 // Regardless of writeSettings we need to ensure that this restriction
15970                 // state propagation is persisted
15971                 mSettings.writeAllUsersPackageRestrictionsLPr();
15972             }
15973             // can downgrade to reader here
15974             if (writeSettings) {
15975                 mSettings.writeLPr();
15976             }
15977         }
15978         return true;
15979     }
15980
15981     private boolean deleteInstalledPackageLIF(PackageSetting ps,
15982             boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15983             PackageRemovedInfo outInfo, boolean writeSettings,
15984             PackageParser.Package replacingPackage) {
15985         synchronized (mPackages) {
15986             if (outInfo != null) {
15987                 outInfo.uid = ps.appId;
15988             }
15989
15990             if (outInfo != null && outInfo.removedChildPackages != null) {
15991                 final int childCount = (ps.childPackageNames != null)
15992                         ? ps.childPackageNames.size() : 0;
15993                 for (int i = 0; i < childCount; i++) {
15994                     String childPackageName = ps.childPackageNames.get(i);
15995                     PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15996                     if (childPs == null) {
15997                         return false;
15998                     }
15999                     PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
16000                             childPackageName);
16001                     if (childInfo != null) {
16002                         childInfo.uid = childPs.appId;
16003                     }
16004                 }
16005             }
16006         }
16007
16008         // Delete package data from internal structures and also remove data if flag is set
16009         removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
16010
16011         // Delete the child packages data
16012         final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16013         for (int i = 0; i < childCount; i++) {
16014             PackageSetting childPs;
16015             synchronized (mPackages) {
16016                 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16017             }
16018             if (childPs != null) {
16019                 PackageRemovedInfo childOutInfo = (outInfo != null
16020                         && outInfo.removedChildPackages != null)
16021                         ? outInfo.removedChildPackages.get(childPs.name) : null;
16022                 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16023                         && (replacingPackage != null
16024                         && !replacingPackage.hasChildPackage(childPs.name))
16025                         ? flags & ~DELETE_KEEP_DATA : flags;
16026                 removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16027                         deleteFlags, writeSettings);
16028             }
16029         }
16030
16031         // Delete application code and resources only for parent packages
16032         if (ps.parentPackageName == null) {
16033             if (deleteCodeAndResources && (outInfo != null)) {
16034                 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16035                         ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16036                 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16037             }
16038         }
16039
16040         return true;
16041     }
16042
16043     @Override
16044     public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16045             int userId) {
16046         mContext.enforceCallingOrSelfPermission(
16047                 android.Manifest.permission.DELETE_PACKAGES, null);
16048         synchronized (mPackages) {
16049             PackageSetting ps = mSettings.mPackages.get(packageName);
16050             if (ps == null) {
16051                 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16052                 return false;
16053             }
16054             if (!ps.getInstalled(userId)) {
16055                 // Can't block uninstall for an app that is not installed or enabled.
16056                 Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16057                 return false;
16058             }
16059             ps.setBlockUninstall(blockUninstall, userId);
16060             mSettings.writePackageRestrictionsLPr(userId);
16061         }
16062         return true;
16063     }
16064
16065     @Override
16066     public boolean getBlockUninstallForUser(String packageName, int userId) {
16067         synchronized (mPackages) {
16068             PackageSetting ps = mSettings.mPackages.get(packageName);
16069             if (ps == null) {
16070                 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16071                 return false;
16072             }
16073             return ps.getBlockUninstall(userId);
16074         }
16075     }
16076
16077     @Override
16078     public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16079         int callingUid = Binder.getCallingUid();
16080         if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16081             throw new SecurityException(
16082                     "setRequiredForSystemUser can only be run by the system or root");
16083         }
16084         synchronized (mPackages) {
16085             PackageSetting ps = mSettings.mPackages.get(packageName);
16086             if (ps == null) {
16087                 Log.w(TAG, "Package doesn't exist: " + packageName);
16088                 return false;
16089             }
16090             if (systemUserApp) {
16091                 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16092             } else {
16093                 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16094             }
16095             mSettings.writeLPr();
16096         }
16097         return true;
16098     }
16099
16100     /*
16101      * This method handles package deletion in general
16102      */
16103     private boolean deletePackageLIF(String packageName, UserHandle user,
16104             boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16105             PackageRemovedInfo outInfo, boolean writeSettings,
16106             PackageParser.Package replacingPackage) {
16107         if (packageName == null) {
16108             Slog.w(TAG, "Attempt to delete null packageName.");
16109             return false;
16110         }
16111
16112         if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16113
16114         PackageSetting ps;
16115
16116         synchronized (mPackages) {
16117             ps = mSettings.mPackages.get(packageName);
16118             if (ps == null) {
16119                 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16120                 return false;
16121             }
16122
16123             if (ps.parentPackageName != null && (!isSystemApp(ps)
16124                     || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16125                 if (DEBUG_REMOVE) {
16126                     Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16127                             + ((user == null) ? UserHandle.USER_ALL : user));
16128                 }
16129                 final int removedUserId = (user != null) ? user.getIdentifier()
16130                         : UserHandle.USER_ALL;
16131                 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16132                     return false;
16133                 }
16134                 markPackageUninstalledForUserLPw(ps, user);
16135                 scheduleWritePackageRestrictionsLocked(user);
16136                 return true;
16137             }
16138         }
16139
16140         if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16141                 && user.getIdentifier() != UserHandle.USER_ALL)) {
16142             // The caller is asking that the package only be deleted for a single
16143             // user.  To do this, we just mark its uninstalled state and delete
16144             // its data. If this is a system app, we only allow this to happen if
16145             // they have set the special DELETE_SYSTEM_APP which requests different
16146             // semantics than normal for uninstalling system apps.
16147             markPackageUninstalledForUserLPw(ps, user);
16148
16149             if (!isSystemApp(ps)) {
16150                 // Do not uninstall the APK if an app should be cached
16151                 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16152                 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16153                     // Other user still have this package installed, so all
16154                     // we need to do is clear this user's data and save that
16155                     // it is uninstalled.
16156                     if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16157                     if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16158                         return false;
16159                     }
16160                     scheduleWritePackageRestrictionsLocked(user);
16161                     return true;
16162                 } else {
16163                     // We need to set it back to 'installed' so the uninstall
16164                     // broadcasts will be sent correctly.
16165                     if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16166                     ps.setInstalled(true, user.getIdentifier());
16167                 }
16168             } else {
16169                 // This is a system app, so we assume that the
16170                 // other users still have this package installed, so all
16171                 // we need to do is clear this user's data and save that
16172                 // it is uninstalled.
16173                 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16174                 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16175                     return false;
16176                 }
16177                 scheduleWritePackageRestrictionsLocked(user);
16178                 return true;
16179             }
16180         }
16181
16182         // If we are deleting a composite package for all users, keep track
16183         // of result for each child.
16184         if (ps.childPackageNames != null && outInfo != null) {
16185             synchronized (mPackages) {
16186                 final int childCount = ps.childPackageNames.size();
16187                 outInfo.removedChildPackages = new ArrayMap<>(childCount);
16188                 for (int i = 0; i < childCount; i++) {
16189                     String childPackageName = ps.childPackageNames.get(i);
16190                     PackageRemovedInfo childInfo = new PackageRemovedInfo();
16191                     childInfo.removedPackage = childPackageName;
16192                     outInfo.removedChildPackages.put(childPackageName, childInfo);
16193                     PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16194                     if (childPs != null) {
16195                         childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16196                     }
16197                 }
16198             }
16199         }
16200
16201         boolean ret = false;
16202         if (isSystemApp(ps)) {
16203             if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16204             // When an updated system application is deleted we delete the existing resources
16205             // as well and fall back to existing code in system partition
16206             ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16207         } else {
16208             if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16209             ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16210                     outInfo, writeSettings, replacingPackage);
16211         }
16212
16213         // Take a note whether we deleted the package for all users
16214         if (outInfo != null) {
16215             outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16216             if (outInfo.removedChildPackages != null) {
16217                 synchronized (mPackages) {
16218                     final int childCount = outInfo.removedChildPackages.size();
16219                     for (int i = 0; i < childCount; i++) {
16220                         PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16221                         if (childInfo != null) {
16222                             childInfo.removedForAllUsers = mPackages.get(
16223                                     childInfo.removedPackage) == null;
16224                         }
16225                     }
16226                 }
16227             }
16228             // If we uninstalled an update to a system app there may be some
16229             // child packages that appeared as they are declared in the system
16230             // app but were not declared in the update.
16231             if (isSystemApp(ps)) {
16232                 synchronized (mPackages) {
16233                     PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16234                     final int childCount = (updatedPs.childPackageNames != null)
16235                             ? updatedPs.childPackageNames.size() : 0;
16236                     for (int i = 0; i < childCount; i++) {
16237                         String childPackageName = updatedPs.childPackageNames.get(i);
16238                         if (outInfo.removedChildPackages == null
16239                                 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16240                             PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16241                             if (childPs == null) {
16242                                 continue;
16243                             }
16244                             PackageInstalledInfo installRes = new PackageInstalledInfo();
16245                             installRes.name = childPackageName;
16246                             installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16247                             installRes.pkg = mPackages.get(childPackageName);
16248                             installRes.uid = childPs.pkg.applicationInfo.uid;
16249                             if (outInfo.appearedChildPackages == null) {
16250                                 outInfo.appearedChildPackages = new ArrayMap<>();
16251                             }
16252                             outInfo.appearedChildPackages.put(childPackageName, installRes);
16253                         }
16254                     }
16255                 }
16256             }
16257         }
16258
16259         return ret;
16260     }
16261
16262     private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16263         final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16264                 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16265         for (int nextUserId : userIds) {
16266             if (DEBUG_REMOVE) {
16267                 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16268             }
16269             ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16270                     false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16271                     false /*hidden*/, false /*suspended*/, null, null, null,
16272                     false /*blockUninstall*/,
16273                     ps.readUserState(nextUserId).domainVerificationStatus, 0);
16274         }
16275     }
16276
16277     private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16278             PackageRemovedInfo outInfo) {
16279         final PackageParser.Package pkg;
16280         synchronized (mPackages) {
16281             pkg = mPackages.get(ps.name);
16282         }
16283
16284         final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16285                 : new int[] {userId};
16286         for (int nextUserId : userIds) {
16287             if (DEBUG_REMOVE) {
16288                 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16289                         + nextUserId);
16290             }
16291
16292             destroyAppDataLIF(pkg, userId,
16293                     StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16294             destroyAppProfilesLIF(pkg, userId);
16295             removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16296             schedulePackageCleaning(ps.name, nextUserId, false);
16297             synchronized (mPackages) {
16298                 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16299                     scheduleWritePackageRestrictionsLocked(nextUserId);
16300                 }
16301                 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16302             }
16303         }
16304
16305         if (outInfo != null) {
16306             outInfo.removedPackage = ps.name;
16307             outInfo.removedAppId = ps.appId;
16308             outInfo.removedUsers = userIds;
16309         }
16310
16311         return true;
16312     }
16313
16314     private final class ClearStorageConnection implements ServiceConnection {
16315         IMediaContainerService mContainerService;
16316
16317         @Override
16318         public void onServiceConnected(ComponentName name, IBinder service) {
16319             synchronized (this) {
16320                 mContainerService = IMediaContainerService.Stub.asInterface(service);
16321                 notifyAll();
16322             }
16323         }
16324
16325         @Override
16326         public void onServiceDisconnected(ComponentName name) {
16327         }
16328     }
16329
16330     private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16331         if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16332
16333         final boolean mounted;
16334         if (Environment.isExternalStorageEmulated()) {
16335             mounted = true;
16336         } else {
16337             final String status = Environment.getExternalStorageState();
16338
16339             mounted = status.equals(Environment.MEDIA_MOUNTED)
16340                     || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16341         }
16342
16343         if (!mounted) {
16344             return;
16345         }
16346
16347         final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16348         int[] users;
16349         if (userId == UserHandle.USER_ALL) {
16350             users = sUserManager.getUserIds();
16351         } else {
16352             users = new int[] { userId };
16353         }
16354         final ClearStorageConnection conn = new ClearStorageConnection();
16355         if (mContext.bindServiceAsUser(
16356                 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16357             try {
16358                 for (int curUser : users) {
16359                     long timeout = SystemClock.uptimeMillis() + 5000;
16360                     synchronized (conn) {
16361                         long now;
16362                         while (conn.mContainerService == null &&
16363                                 (now = SystemClock.uptimeMillis()) < timeout) {
16364                             try {
16365                                 conn.wait(timeout - now);
16366                             } catch (InterruptedException e) {
16367                             }
16368                         }
16369                     }
16370                     if (conn.mContainerService == null) {
16371                         return;
16372                     }
16373
16374                     final UserEnvironment userEnv = new UserEnvironment(curUser);
16375                     clearDirectory(conn.mContainerService,
16376                             userEnv.buildExternalStorageAppCacheDirs(packageName));
16377                     if (allData) {
16378                         clearDirectory(conn.mContainerService,
16379                                 userEnv.buildExternalStorageAppDataDirs(packageName));
16380                         clearDirectory(conn.mContainerService,
16381                                 userEnv.buildExternalStorageAppMediaDirs(packageName));
16382                     }
16383                 }
16384             } finally {
16385                 mContext.unbindService(conn);
16386             }
16387         }
16388     }
16389
16390     @Override
16391     public void clearApplicationProfileData(String packageName) {
16392         enforceSystemOrRoot("Only the system can clear all profile data");
16393
16394         final PackageParser.Package pkg;
16395         synchronized (mPackages) {
16396             pkg = mPackages.get(packageName);
16397         }
16398
16399         try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16400             synchronized (mInstallLock) {
16401                 clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16402                 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16403                         true /* removeBaseMarker */);
16404             }
16405         }
16406     }
16407
16408     @Override
16409     public void clearApplicationUserData(final String packageName,
16410             final IPackageDataObserver observer, final int userId) {
16411         mContext.enforceCallingOrSelfPermission(
16412                 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16413
16414         enforceCrossUserPermission(Binder.getCallingUid(), userId,
16415                 true /* requireFullPermission */, false /* checkShell */, "clear application data");
16416
16417         if (mProtectedPackages.canPackageBeWiped(userId, packageName)) {
16418             throw new SecurityException("Cannot clear data for a device owner or a profile owner");
16419         }
16420         // Queue up an async operation since the package deletion may take a little while.
16421         mHandler.post(new Runnable() {
16422             public void run() {
16423                 mHandler.removeCallbacks(this);
16424                 final boolean succeeded;
16425                 try (PackageFreezer freezer = freezePackage(packageName,
16426                         "clearApplicationUserData")) {
16427                     synchronized (mInstallLock) {
16428                         succeeded = clearApplicationUserDataLIF(packageName, userId);
16429                     }
16430                     clearExternalStorageDataSync(packageName, userId, true);
16431                 }
16432                 if (succeeded) {
16433                     // invoke DeviceStorageMonitor's update method to clear any notifications
16434                     DeviceStorageMonitorInternal dsm = LocalServices
16435                             .getService(DeviceStorageMonitorInternal.class);
16436                     if (dsm != null) {
16437                         dsm.checkMemory();
16438                     }
16439                 }
16440                 if(observer != null) {
16441                     try {
16442                         observer.onRemoveCompleted(packageName, succeeded);
16443                     } catch (RemoteException e) {
16444                         Log.i(TAG, "Observer no longer exists.");
16445                     }
16446                 } //end if observer
16447             } //end run
16448         });
16449     }
16450
16451     private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16452         if (packageName == null) {
16453             Slog.w(TAG, "Attempt to delete null packageName.");
16454             return false;
16455         }
16456
16457         // Try finding details about the requested package
16458         PackageParser.Package pkg;
16459         synchronized (mPackages) {
16460             pkg = mPackages.get(packageName);
16461             if (pkg == null) {
16462                 final PackageSetting ps = mSettings.mPackages.get(packageName);
16463                 if (ps != null) {
16464                     pkg = ps.pkg;
16465                 }
16466             }
16467
16468             if (pkg == null) {
16469                 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16470                 return false;
16471             }
16472
16473             PackageSetting ps = (PackageSetting) pkg.mExtras;
16474             resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16475         }
16476
16477         clearAppDataLIF(pkg, userId,
16478                 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16479
16480         final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16481         removeKeystoreDataIfNeeded(userId, appId);
16482
16483         UserManagerInternal umInternal = getUserManagerInternal();
16484         final int flags;
16485         if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16486             flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16487         } else if (umInternal.isUserRunning(userId)) {
16488             flags = StorageManager.FLAG_STORAGE_DE;
16489         } else {
16490             flags = 0;
16491         }
16492         prepareAppDataContentsLIF(pkg, userId, flags);
16493
16494         return true;
16495     }
16496
16497     /**
16498      * Reverts user permission state changes (permissions and flags) in
16499      * all packages for a given user.
16500      *
16501      * @param userId The device user for which to do a reset.
16502      */
16503     private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16504         final int packageCount = mPackages.size();
16505         for (int i = 0; i < packageCount; i++) {
16506             PackageParser.Package pkg = mPackages.valueAt(i);
16507             PackageSetting ps = (PackageSetting) pkg.mExtras;
16508             resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16509         }
16510     }
16511
16512     private void resetNetworkPolicies(int userId) {
16513         LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16514     }
16515
16516     /**
16517      * Reverts user permission state changes (permissions and flags).
16518      *
16519      * @param ps The package for which to reset.
16520      * @param userId The device user for which to do a reset.
16521      */
16522     private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16523             final PackageSetting ps, final int userId) {
16524         if (ps.pkg == null) {
16525             return;
16526         }
16527
16528         // These are flags that can change base on user actions.
16529         final int userSettableMask = FLAG_PERMISSION_USER_SET
16530                 | FLAG_PERMISSION_USER_FIXED
16531                 | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16532                 | FLAG_PERMISSION_REVIEW_REQUIRED;
16533
16534         final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16535                 | FLAG_PERMISSION_POLICY_FIXED;
16536
16537         boolean writeInstallPermissions = false;
16538         boolean writeRuntimePermissions = false;
16539
16540         final int permissionCount = ps.pkg.requestedPermissions.size();
16541         for (int i = 0; i < permissionCount; i++) {
16542             String permission = ps.pkg.requestedPermissions.get(i);
16543
16544             BasePermission bp = mSettings.mPermissions.get(permission);
16545             if (bp == null) {
16546                 continue;
16547             }
16548
16549             // If shared user we just reset the state to which only this app contributed.
16550             if (ps.sharedUser != null) {
16551                 boolean used = false;
16552                 final int packageCount = ps.sharedUser.packages.size();
16553                 for (int j = 0; j < packageCount; j++) {
16554                     PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16555                     if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16556                             && pkg.pkg.requestedPermissions.contains(permission)) {
16557                         used = true;
16558                         break;
16559                     }
16560                 }
16561                 if (used) {
16562                     continue;
16563                 }
16564             }
16565
16566             PermissionsState permissionsState = ps.getPermissionsState();
16567
16568             final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16569
16570             // Always clear the user settable flags.
16571             final boolean hasInstallState = permissionsState.getInstallPermissionState(
16572                     bp.name) != null;
16573             // If permission review is enabled and this is a legacy app, mark the
16574             // permission as requiring a review as this is the initial state.
16575             int flags = 0;
16576             if (Build.PERMISSIONS_REVIEW_REQUIRED
16577                     && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16578                 flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16579             }
16580             if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16581                 if (hasInstallState) {
16582                     writeInstallPermissions = true;
16583                 } else {
16584                     writeRuntimePermissions = true;
16585                 }
16586             }
16587
16588             // Below is only runtime permission handling.
16589             if (!bp.isRuntime()) {
16590                 continue;
16591             }
16592
16593             // Never clobber system or policy.
16594             if ((oldFlags & policyOrSystemFlags) != 0) {
16595                 continue;
16596             }
16597
16598             // If this permission was granted by default, make sure it is.
16599             if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16600                 if (permissionsState.grantRuntimePermission(bp, userId)
16601                         != PERMISSION_OPERATION_FAILURE) {
16602                     writeRuntimePermissions = true;
16603                 }
16604             // If permission review is enabled the permissions for a legacy apps
16605             // are represented as constantly granted runtime ones, so don't revoke.
16606             } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16607                 // Otherwise, reset the permission.
16608                 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16609                 switch (revokeResult) {
16610                     case PERMISSION_OPERATION_SUCCESS:
16611                     case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16612                         writeRuntimePermissions = true;
16613                         final int appId = ps.appId;
16614                         mHandler.post(new Runnable() {
16615                             @Override
16616                             public void run() {
16617                                 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16618                             }
16619                         });
16620                     } break;
16621                 }
16622             }
16623         }
16624
16625         // Synchronously write as we are taking permissions away.
16626         if (writeRuntimePermissions) {
16627             mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16628         }
16629
16630         // Synchronously write as we are taking permissions away.
16631         if (writeInstallPermissions) {
16632             mSettings.writeLPr();
16633         }
16634     }
16635
16636     /**
16637      * Remove entries from the keystore daemon. Will only remove it if the
16638      * {@code appId} is valid.
16639      */
16640     private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16641         if (appId < 0) {
16642             return;
16643         }
16644
16645         final KeyStore keyStore = KeyStore.getInstance();
16646         if (keyStore != null) {
16647             if (userId == UserHandle.USER_ALL) {
16648                 for (final int individual : sUserManager.getUserIds()) {
16649                     keyStore.clearUid(UserHandle.getUid(individual, appId));
16650                 }
16651             } else {
16652                 keyStore.clearUid(UserHandle.getUid(userId, appId));
16653             }
16654         } else {
16655             Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16656         }
16657     }
16658
16659     @Override
16660     public void deleteApplicationCacheFiles(final String packageName,
16661             final IPackageDataObserver observer) {
16662         final int userId = UserHandle.getCallingUserId();
16663         deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16664     }
16665
16666     @Override
16667     public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16668             final IPackageDataObserver observer) {
16669         mContext.enforceCallingOrSelfPermission(
16670                 android.Manifest.permission.DELETE_CACHE_FILES, null);
16671         enforceCrossUserPermission(Binder.getCallingUid(), userId,
16672                 /* requireFullPermission= */ true, /* checkShell= */ false,
16673                 "delete application cache files");
16674
16675         final PackageParser.Package pkg;
16676         synchronized (mPackages) {
16677             pkg = mPackages.get(packageName);
16678         }
16679
16680         // Queue up an async operation since the package deletion may take a little while.
16681         mHandler.post(new Runnable() {
16682             public void run() {
16683                 synchronized (mInstallLock) {
16684                     final int flags = StorageManager.FLAG_STORAGE_DE
16685                             | StorageManager.FLAG_STORAGE_CE;
16686                     // We're only clearing cache files, so we don't care if the
16687                     // app is unfrozen and still able to run
16688                     clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16689                     clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16690                 }
16691                 clearExternalStorageDataSync(packageName, userId, false);
16692                 if (observer != null) {
16693                     try {
16694                         observer.onRemoveCompleted(packageName, true);
16695                     } catch (RemoteException e) {
16696                         Log.i(TAG, "Observer no longer exists.");
16697                     }
16698                 }
16699             }
16700         });
16701     }
16702
16703     @Override
16704     public void getPackageSizeInfo(final String packageName, int userHandle,
16705             final IPackageStatsObserver observer) {
16706         mContext.enforceCallingOrSelfPermission(
16707                 android.Manifest.permission.GET_PACKAGE_SIZE, null);
16708         if (packageName == null) {
16709             throw new IllegalArgumentException("Attempt to get size of null packageName");
16710         }
16711
16712         PackageStats stats = new PackageStats(packageName, userHandle);
16713
16714         /*
16715          * Queue up an async operation since the package measurement may take a
16716          * little while.
16717          */
16718         Message msg = mHandler.obtainMessage(INIT_COPY);
16719         msg.obj = new MeasureParams(stats, observer);
16720         mHandler.sendMessage(msg);
16721     }
16722
16723     private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16724         final PackageSetting ps;
16725         synchronized (mPackages) {
16726             ps = mSettings.mPackages.get(packageName);
16727             if (ps == null) {
16728                 Slog.w(TAG, "Failed to find settings for " + packageName);
16729                 return false;
16730             }
16731         }
16732         try {
16733             mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16734                     StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16735                     ps.getCeDataInode(userId), ps.codePathString, stats);
16736         } catch (InstallerException e) {
16737             Slog.w(TAG, String.valueOf(e));
16738             return false;
16739         }
16740
16741         // For now, ignore code size of packages on system partition
16742         if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16743             stats.codeSize = 0;
16744         }
16745
16746         return true;
16747     }
16748
16749     private int getUidTargetSdkVersionLockedLPr(int uid) {
16750         Object obj = mSettings.getUserIdLPr(uid);
16751         if (obj instanceof SharedUserSetting) {
16752             final SharedUserSetting sus = (SharedUserSetting) obj;
16753             int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16754             final Iterator<PackageSetting> it = sus.packages.iterator();
16755             while (it.hasNext()) {
16756                 final PackageSetting ps = it.next();
16757                 if (ps.pkg != null) {
16758                     int v = ps.pkg.applicationInfo.targetSdkVersion;
16759                     if (v < vers) vers = v;
16760                 }
16761             }
16762             return vers;
16763         } else if (obj instanceof PackageSetting) {
16764             final PackageSetting ps = (PackageSetting) obj;
16765             if (ps.pkg != null) {
16766                 return ps.pkg.applicationInfo.targetSdkVersion;
16767             }
16768         }
16769         return Build.VERSION_CODES.CUR_DEVELOPMENT;
16770     }
16771
16772     @Override
16773     public void addPreferredActivity(IntentFilter filter, int match,
16774             ComponentName[] set, ComponentName activity, int userId) {
16775         addPreferredActivityInternal(filter, match, set, activity, true, userId,
16776                 "Adding preferred");
16777     }
16778
16779     private void addPreferredActivityInternal(IntentFilter filter, int match,
16780             ComponentName[] set, ComponentName activity, boolean always, int userId,
16781             String opname) {
16782         // writer
16783         int callingUid = Binder.getCallingUid();
16784         enforceCrossUserPermission(callingUid, userId,
16785                 true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16786         if (filter.countActions() == 0) {
16787             Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16788             return;
16789         }
16790         synchronized (mPackages) {
16791             if (mContext.checkCallingOrSelfPermission(
16792                     android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16793                     != PackageManager.PERMISSION_GRANTED) {
16794                 if (getUidTargetSdkVersionLockedLPr(callingUid)
16795                         < Build.VERSION_CODES.FROYO) {
16796                     Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16797                             + callingUid);
16798                     return;
16799                 }
16800                 mContext.enforceCallingOrSelfPermission(
16801                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16802             }
16803
16804             PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16805             Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16806                     + userId + ":");
16807             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16808             pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16809             scheduleWritePackageRestrictionsLocked(userId);
16810         }
16811     }
16812
16813     @Override
16814     public void replacePreferredActivity(IntentFilter filter, int match,
16815             ComponentName[] set, ComponentName activity, int userId) {
16816         if (filter.countActions() != 1) {
16817             throw new IllegalArgumentException(
16818                     "replacePreferredActivity expects filter to have only 1 action.");
16819         }
16820         if (filter.countDataAuthorities() != 0
16821                 || filter.countDataPaths() != 0
16822                 || filter.countDataSchemes() > 1
16823                 || filter.countDataTypes() != 0) {
16824             throw new IllegalArgumentException(
16825                     "replacePreferredActivity expects filter to have no data authorities, " +
16826                     "paths, or types; and at most one scheme.");
16827         }
16828
16829         final int callingUid = Binder.getCallingUid();
16830         enforceCrossUserPermission(callingUid, userId,
16831                 true /* requireFullPermission */, false /* checkShell */,
16832                 "replace preferred activity");
16833         synchronized (mPackages) {
16834             if (mContext.checkCallingOrSelfPermission(
16835                     android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16836                     != PackageManager.PERMISSION_GRANTED) {
16837                 if (getUidTargetSdkVersionLockedLPr(callingUid)
16838                         < Build.VERSION_CODES.FROYO) {
16839                     Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16840                             + Binder.getCallingUid());
16841                     return;
16842                 }
16843                 mContext.enforceCallingOrSelfPermission(
16844                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16845             }
16846
16847             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16848             if (pir != null) {
16849                 // Get all of the existing entries that exactly match this filter.
16850                 ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16851                 if (existing != null && existing.size() == 1) {
16852                     PreferredActivity cur = existing.get(0);
16853                     if (DEBUG_PREFERRED) {
16854                         Slog.i(TAG, "Checking replace of preferred:");
16855                         filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16856                         if (!cur.mPref.mAlways) {
16857                             Slog.i(TAG, "  -- CUR; not mAlways!");
16858                         } else {
16859                             Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16860                             Slog.i(TAG, "  -- CUR: mSet="
16861                                     + Arrays.toString(cur.mPref.mSetComponents));
16862                             Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16863                             Slog.i(TAG, "  -- NEW: mMatch="
16864                                     + (match&IntentFilter.MATCH_CATEGORY_MASK));
16865                             Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16866                             Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16867                         }
16868                     }
16869                     if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16870                             && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16871                             && cur.mPref.sameSet(set)) {
16872                         // Setting the preferred activity to what it happens to be already
16873                         if (DEBUG_PREFERRED) {
16874                             Slog.i(TAG, "Replacing with same preferred activity "
16875                                     + cur.mPref.mShortComponent + " for user "
16876                                     + userId + ":");
16877                             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16878                         }
16879                         return;
16880                     }
16881                 }
16882
16883                 if (existing != null) {
16884                     if (DEBUG_PREFERRED) {
16885                         Slog.i(TAG, existing.size() + " existing preferred matches for:");
16886                         filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16887                     }
16888                     for (int i = 0; i < existing.size(); i++) {
16889                         PreferredActivity pa = existing.get(i);
16890                         if (DEBUG_PREFERRED) {
16891                             Slog.i(TAG, "Removing existing preferred activity "
16892                                     + pa.mPref.mComponent + ":");
16893                             pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16894                         }
16895                         pir.removeFilter(pa);
16896                     }
16897                 }
16898             }
16899             addPreferredActivityInternal(filter, match, set, activity, true, userId,
16900                     "Replacing preferred");
16901         }
16902     }
16903
16904     @Override
16905     public void clearPackagePreferredActivities(String packageName) {
16906         final int uid = Binder.getCallingUid();
16907         // writer
16908         synchronized (mPackages) {
16909             PackageParser.Package pkg = mPackages.get(packageName);
16910             if (pkg == null || pkg.applicationInfo.uid != uid) {
16911                 if (mContext.checkCallingOrSelfPermission(
16912                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16913                         != PackageManager.PERMISSION_GRANTED) {
16914                     if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16915                             < Build.VERSION_CODES.FROYO) {
16916                         Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16917                                 + Binder.getCallingUid());
16918                         return;
16919                     }
16920                     mContext.enforceCallingOrSelfPermission(
16921                             android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16922                 }
16923             }
16924
16925             int user = UserHandle.getCallingUserId();
16926             if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16927                 scheduleWritePackageRestrictionsLocked(user);
16928             }
16929         }
16930     }
16931
16932     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16933     boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16934         ArrayList<PreferredActivity> removed = null;
16935         boolean changed = false;
16936         for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16937             final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16938             PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16939             if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16940                 continue;
16941             }
16942             Iterator<PreferredActivity> it = pir.filterIterator();
16943             while (it.hasNext()) {
16944                 PreferredActivity pa = it.next();
16945                 // Mark entry for removal only if it matches the package name
16946                 // and the entry is of type "always".
16947                 if (packageName == null ||
16948                         (pa.mPref.mComponent.getPackageName().equals(packageName)
16949                                 && pa.mPref.mAlways)) {
16950                     if (removed == null) {
16951                         removed = new ArrayList<PreferredActivity>();
16952                     }
16953                     removed.add(pa);
16954                 }
16955             }
16956             if (removed != null) {
16957                 for (int j=0; j<removed.size(); j++) {
16958                     PreferredActivity pa = removed.get(j);
16959                     pir.removeFilter(pa);
16960                 }
16961                 changed = true;
16962             }
16963         }
16964         return changed;
16965     }
16966
16967     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16968     private void clearIntentFilterVerificationsLPw(int userId) {
16969         final int packageCount = mPackages.size();
16970         for (int i = 0; i < packageCount; i++) {
16971             PackageParser.Package pkg = mPackages.valueAt(i);
16972             clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16973         }
16974     }
16975
16976     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16977     void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16978         if (userId == UserHandle.USER_ALL) {
16979             if (mSettings.removeIntentFilterVerificationLPw(packageName,
16980                     sUserManager.getUserIds())) {
16981                 for (int oneUserId : sUserManager.getUserIds()) {
16982                     scheduleWritePackageRestrictionsLocked(oneUserId);
16983                 }
16984             }
16985         } else {
16986             if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16987                 scheduleWritePackageRestrictionsLocked(userId);
16988             }
16989         }
16990     }
16991
16992     void clearDefaultBrowserIfNeeded(String packageName) {
16993         for (int oneUserId : sUserManager.getUserIds()) {
16994             String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16995             if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16996             if (packageName.equals(defaultBrowserPackageName)) {
16997                 setDefaultBrowserPackageName(null, oneUserId);
16998             }
16999         }
17000     }
17001
17002     @Override
17003     public void resetApplicationPreferences(int userId) {
17004         mContext.enforceCallingOrSelfPermission(
17005                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
17006         final long identity = Binder.clearCallingIdentity();
17007         // writer
17008         try {
17009             synchronized (mPackages) {
17010                 clearPackagePreferredActivitiesLPw(null, userId);
17011                 mSettings.applyDefaultPreferredAppsLPw(this, userId);
17012                 // TODO: We have to reset the default SMS and Phone. This requires
17013                 // significant refactoring to keep all default apps in the package
17014                 // manager (cleaner but more work) or have the services provide
17015                 // callbacks to the package manager to request a default app reset.
17016                 applyFactoryDefaultBrowserLPw(userId);
17017                 clearIntentFilterVerificationsLPw(userId);
17018                 primeDomainVerificationsLPw(userId);
17019                 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17020                 scheduleWritePackageRestrictionsLocked(userId);
17021             }
17022             resetNetworkPolicies(userId);
17023         } finally {
17024             Binder.restoreCallingIdentity(identity);
17025         }
17026     }
17027
17028     @Override
17029     public int getPreferredActivities(List<IntentFilter> outFilters,
17030             List<ComponentName> outActivities, String packageName) {
17031
17032         int num = 0;
17033         final int userId = UserHandle.getCallingUserId();
17034         // reader
17035         synchronized (mPackages) {
17036             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17037             if (pir != null) {
17038                 final Iterator<PreferredActivity> it = pir.filterIterator();
17039                 while (it.hasNext()) {
17040                     final PreferredActivity pa = it.next();
17041                     if (packageName == null
17042                             || (pa.mPref.mComponent.getPackageName().equals(packageName)
17043                                     && pa.mPref.mAlways)) {
17044                         if (outFilters != null) {
17045                             outFilters.add(new IntentFilter(pa));
17046                         }
17047                         if (outActivities != null) {
17048                             outActivities.add(pa.mPref.mComponent);
17049                         }
17050                     }
17051                 }
17052             }
17053         }
17054
17055         return num;
17056     }
17057
17058     @Override
17059     public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17060             int userId) {
17061         int callingUid = Binder.getCallingUid();
17062         if (callingUid != Process.SYSTEM_UID) {
17063             throw new SecurityException(
17064                     "addPersistentPreferredActivity can only be run by the system");
17065         }
17066         if (filter.countActions() == 0) {
17067             Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17068             return;
17069         }
17070         synchronized (mPackages) {
17071             Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17072                     ":");
17073             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17074             mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17075                     new PersistentPreferredActivity(filter, activity));
17076             scheduleWritePackageRestrictionsLocked(userId);
17077         }
17078     }
17079
17080     @Override
17081     public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17082         int callingUid = Binder.getCallingUid();
17083         if (callingUid != Process.SYSTEM_UID) {
17084             throw new SecurityException(
17085                     "clearPackagePersistentPreferredActivities can only be run by the system");
17086         }
17087         ArrayList<PersistentPreferredActivity> removed = null;
17088         boolean changed = false;
17089         synchronized (mPackages) {
17090             for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17091                 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17092                 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17093                         .valueAt(i);
17094                 if (userId != thisUserId) {
17095                     continue;
17096                 }
17097                 Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17098                 while (it.hasNext()) {
17099                     PersistentPreferredActivity ppa = it.next();
17100                     // Mark entry for removal only if it matches the package name.
17101                     if (ppa.mComponent.getPackageName().equals(packageName)) {
17102                         if (removed == null) {
17103                             removed = new ArrayList<PersistentPreferredActivity>();
17104                         }
17105                         removed.add(ppa);
17106                     }
17107                 }
17108                 if (removed != null) {
17109                     for (int j=0; j<removed.size(); j++) {
17110                         PersistentPreferredActivity ppa = removed.get(j);
17111                         ppir.removeFilter(ppa);
17112                     }
17113                     changed = true;
17114                 }
17115             }
17116
17117             if (changed) {
17118                 scheduleWritePackageRestrictionsLocked(userId);
17119             }
17120         }
17121     }
17122
17123     /**
17124      * Common machinery for picking apart a restored XML blob and passing
17125      * it to a caller-supplied functor to be applied to the running system.
17126      */
17127     private void restoreFromXml(XmlPullParser parser, int userId,
17128             String expectedStartTag, BlobXmlRestorer functor)
17129             throws IOException, XmlPullParserException {
17130         int type;
17131         while ((type = parser.next()) != XmlPullParser.START_TAG
17132                 && type != XmlPullParser.END_DOCUMENT) {
17133         }
17134         if (type != XmlPullParser.START_TAG) {
17135             // oops didn't find a start tag?!
17136             if (DEBUG_BACKUP) {
17137                 Slog.e(TAG, "Didn't find start tag during restore");
17138             }
17139             return;
17140         }
17141 Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17142         // this is supposed to be TAG_PREFERRED_BACKUP
17143         if (!expectedStartTag.equals(parser.getName())) {
17144             if (DEBUG_BACKUP) {
17145                 Slog.e(TAG, "Found unexpected tag " + parser.getName());
17146             }
17147             return;
17148         }
17149
17150         // skip interfering stuff, then we're aligned with the backing implementation
17151         while ((type = parser.next()) == XmlPullParser.TEXT) { }
17152 Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17153         functor.apply(parser, userId);
17154     }
17155
17156     private interface BlobXmlRestorer {
17157         public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17158     }
17159
17160     /**
17161      * Non-Binder method, support for the backup/restore mechanism: write the
17162      * full set of preferred activities in its canonical XML format.  Returns the
17163      * XML output as a byte array, or null if there is none.
17164      */
17165     @Override
17166     public byte[] getPreferredActivityBackup(int userId) {
17167         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17168             throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17169         }
17170
17171         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17172         try {
17173             final XmlSerializer serializer = new FastXmlSerializer();
17174             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17175             serializer.startDocument(null, true);
17176             serializer.startTag(null, TAG_PREFERRED_BACKUP);
17177
17178             synchronized (mPackages) {
17179                 mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17180             }
17181
17182             serializer.endTag(null, TAG_PREFERRED_BACKUP);
17183             serializer.endDocument();
17184             serializer.flush();
17185         } catch (Exception e) {
17186             if (DEBUG_BACKUP) {
17187                 Slog.e(TAG, "Unable to write preferred activities for backup", e);
17188             }
17189             return null;
17190         }
17191
17192         return dataStream.toByteArray();
17193     }
17194
17195     @Override
17196     public void restorePreferredActivities(byte[] backup, int userId) {
17197         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17198             throw new SecurityException("Only the system may call restorePreferredActivities()");
17199         }
17200
17201         try {
17202             final XmlPullParser parser = Xml.newPullParser();
17203             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17204             restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17205                     new BlobXmlRestorer() {
17206                         @Override
17207                         public void apply(XmlPullParser parser, int userId)
17208                                 throws XmlPullParserException, IOException {
17209                             synchronized (mPackages) {
17210                                 mSettings.readPreferredActivitiesLPw(parser, userId);
17211                             }
17212                         }
17213                     } );
17214         } catch (Exception e) {
17215             if (DEBUG_BACKUP) {
17216                 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17217             }
17218         }
17219     }
17220
17221     /**
17222      * Non-Binder method, support for the backup/restore mechanism: write the
17223      * default browser (etc) settings in its canonical XML format.  Returns the default
17224      * browser XML representation as a byte array, or null if there is none.
17225      */
17226     @Override
17227     public byte[] getDefaultAppsBackup(int userId) {
17228         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17229             throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17230         }
17231
17232         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17233         try {
17234             final XmlSerializer serializer = new FastXmlSerializer();
17235             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17236             serializer.startDocument(null, true);
17237             serializer.startTag(null, TAG_DEFAULT_APPS);
17238
17239             synchronized (mPackages) {
17240                 mSettings.writeDefaultAppsLPr(serializer, userId);
17241             }
17242
17243             serializer.endTag(null, TAG_DEFAULT_APPS);
17244             serializer.endDocument();
17245             serializer.flush();
17246         } catch (Exception e) {
17247             if (DEBUG_BACKUP) {
17248                 Slog.e(TAG, "Unable to write default apps for backup", e);
17249             }
17250             return null;
17251         }
17252
17253         return dataStream.toByteArray();
17254     }
17255
17256     @Override
17257     public void restoreDefaultApps(byte[] backup, int userId) {
17258         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17259             throw new SecurityException("Only the system may call restoreDefaultApps()");
17260         }
17261
17262         try {
17263             final XmlPullParser parser = Xml.newPullParser();
17264             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17265             restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17266                     new BlobXmlRestorer() {
17267                         @Override
17268                         public void apply(XmlPullParser parser, int userId)
17269                                 throws XmlPullParserException, IOException {
17270                             synchronized (mPackages) {
17271                                 mSettings.readDefaultAppsLPw(parser, userId);
17272                             }
17273                         }
17274                     } );
17275         } catch (Exception e) {
17276             if (DEBUG_BACKUP) {
17277                 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17278             }
17279         }
17280     }
17281
17282     @Override
17283     public byte[] getIntentFilterVerificationBackup(int userId) {
17284         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17285             throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17286         }
17287
17288         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17289         try {
17290             final XmlSerializer serializer = new FastXmlSerializer();
17291             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17292             serializer.startDocument(null, true);
17293             serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17294
17295             synchronized (mPackages) {
17296                 mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17297             }
17298
17299             serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17300             serializer.endDocument();
17301             serializer.flush();
17302         } catch (Exception e) {
17303             if (DEBUG_BACKUP) {
17304                 Slog.e(TAG, "Unable to write default apps for backup", e);
17305             }
17306             return null;
17307         }
17308
17309         return dataStream.toByteArray();
17310     }
17311
17312     @Override
17313     public void restoreIntentFilterVerification(byte[] backup, int userId) {
17314         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17315             throw new SecurityException("Only the system may call restorePreferredActivities()");
17316         }
17317
17318         try {
17319             final XmlPullParser parser = Xml.newPullParser();
17320             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17321             restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17322                     new BlobXmlRestorer() {
17323                         @Override
17324                         public void apply(XmlPullParser parser, int userId)
17325                                 throws XmlPullParserException, IOException {
17326                             synchronized (mPackages) {
17327                                 mSettings.readAllDomainVerificationsLPr(parser, userId);
17328                                 mSettings.writeLPr();
17329                             }
17330                         }
17331                     } );
17332         } catch (Exception e) {
17333             if (DEBUG_BACKUP) {
17334                 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17335             }
17336         }
17337     }
17338
17339     @Override
17340     public byte[] getPermissionGrantBackup(int userId) {
17341         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17342             throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17343         }
17344
17345         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17346         try {
17347             final XmlSerializer serializer = new FastXmlSerializer();
17348             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17349             serializer.startDocument(null, true);
17350             serializer.startTag(null, TAG_PERMISSION_BACKUP);
17351
17352             synchronized (mPackages) {
17353                 serializeRuntimePermissionGrantsLPr(serializer, userId);
17354             }
17355
17356             serializer.endTag(null, TAG_PERMISSION_BACKUP);
17357             serializer.endDocument();
17358             serializer.flush();
17359         } catch (Exception e) {
17360             if (DEBUG_BACKUP) {
17361                 Slog.e(TAG, "Unable to write default apps for backup", e);
17362             }
17363             return null;
17364         }
17365
17366         return dataStream.toByteArray();
17367     }
17368
17369     @Override
17370     public void restorePermissionGrants(byte[] backup, int userId) {
17371         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17372             throw new SecurityException("Only the system may call restorePermissionGrants()");
17373         }
17374
17375         try {
17376             final XmlPullParser parser = Xml.newPullParser();
17377             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17378             restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17379                     new BlobXmlRestorer() {
17380                         @Override
17381                         public void apply(XmlPullParser parser, int userId)
17382                                 throws XmlPullParserException, IOException {
17383                             synchronized (mPackages) {
17384                                 processRestoredPermissionGrantsLPr(parser, userId);
17385                             }
17386                         }
17387                     } );
17388         } catch (Exception e) {
17389             if (DEBUG_BACKUP) {
17390                 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17391             }
17392         }
17393     }
17394
17395     private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17396             throws IOException {
17397         serializer.startTag(null, TAG_ALL_GRANTS);
17398
17399         final int N = mSettings.mPackages.size();
17400         for (int i = 0; i < N; i++) {
17401             final PackageSetting ps = mSettings.mPackages.valueAt(i);
17402             boolean pkgGrantsKnown = false;
17403
17404             PermissionsState packagePerms = ps.getPermissionsState();
17405
17406             for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17407                 final int grantFlags = state.getFlags();
17408                 // only look at grants that are not system/policy fixed
17409                 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17410                     final boolean isGranted = state.isGranted();
17411                     // And only back up the user-twiddled state bits
17412                     if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17413                         final String packageName = mSettings.mPackages.keyAt(i);
17414                         if (!pkgGrantsKnown) {
17415                             serializer.startTag(null, TAG_GRANT);
17416                             serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17417                             pkgGrantsKnown = true;
17418                         }
17419
17420                         final boolean userSet =
17421                                 (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17422                         final boolean userFixed =
17423                                 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17424                         final boolean revoke =
17425                                 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17426
17427                         serializer.startTag(null, TAG_PERMISSION);
17428                         serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17429                         if (isGranted) {
17430                             serializer.attribute(null, ATTR_IS_GRANTED, "true");
17431                         }
17432                         if (userSet) {
17433                             serializer.attribute(null, ATTR_USER_SET, "true");
17434                         }
17435                         if (userFixed) {
17436                             serializer.attribute(null, ATTR_USER_FIXED, "true");
17437                         }
17438                         if (revoke) {
17439                             serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17440                         }
17441                         serializer.endTag(null, TAG_PERMISSION);
17442                     }
17443                 }
17444             }
17445
17446             if (pkgGrantsKnown) {
17447                 serializer.endTag(null, TAG_GRANT);
17448             }
17449         }
17450
17451         serializer.endTag(null, TAG_ALL_GRANTS);
17452     }
17453
17454     private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17455             throws XmlPullParserException, IOException {
17456         String pkgName = null;
17457         int outerDepth = parser.getDepth();
17458         int type;
17459         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17460                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17461             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17462                 continue;
17463             }
17464
17465             final String tagName = parser.getName();
17466             if (tagName.equals(TAG_GRANT)) {
17467                 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17468                 if (DEBUG_BACKUP) {
17469                     Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17470                 }
17471             } else if (tagName.equals(TAG_PERMISSION)) {
17472
17473                 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17474                 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17475
17476                 int newFlagSet = 0;
17477                 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17478                     newFlagSet |= FLAG_PERMISSION_USER_SET;
17479                 }
17480                 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17481                     newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17482                 }
17483                 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17484                     newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17485                 }
17486                 if (DEBUG_BACKUP) {
17487                     Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17488                             + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17489                 }
17490                 final PackageSetting ps = mSettings.mPackages.get(pkgName);
17491                 if (ps != null) {
17492                     // Already installed so we apply the grant immediately
17493                     if (DEBUG_BACKUP) {
17494                         Slog.v(TAG, "        + already installed; applying");
17495                     }
17496                     PermissionsState perms = ps.getPermissionsState();
17497                     BasePermission bp = mSettings.mPermissions.get(permName);
17498                     if (bp != null) {
17499                         if (isGranted) {
17500                             perms.grantRuntimePermission(bp, userId);
17501                         }
17502                         if (newFlagSet != 0) {
17503                             perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17504                         }
17505                     }
17506                 } else {
17507                     // Need to wait for post-restore install to apply the grant
17508                     if (DEBUG_BACKUP) {
17509                         Slog.v(TAG, "        - not yet installed; saving for later");
17510                     }
17511                     mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17512                             isGranted, newFlagSet, userId);
17513                 }
17514             } else {
17515                 PackageManagerService.reportSettingsProblem(Log.WARN,
17516                         "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17517                 XmlUtils.skipCurrentTag(parser);
17518             }
17519         }
17520
17521         scheduleWriteSettingsLocked();
17522         mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17523     }
17524
17525     @Override
17526     public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17527             int sourceUserId, int targetUserId, int flags) {
17528         mContext.enforceCallingOrSelfPermission(
17529                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17530         int callingUid = Binder.getCallingUid();
17531         enforceOwnerRights(ownerPackage, callingUid);
17532         enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17533         if (intentFilter.countActions() == 0) {
17534             Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17535             return;
17536         }
17537         synchronized (mPackages) {
17538             CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17539                     ownerPackage, targetUserId, flags);
17540             CrossProfileIntentResolver resolver =
17541                     mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17542             ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17543             // We have all those whose filter is equal. Now checking if the rest is equal as well.
17544             if (existing != null) {
17545                 int size = existing.size();
17546                 for (int i = 0; i < size; i++) {
17547                     if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17548                         return;
17549                     }
17550                 }
17551             }
17552             resolver.addFilter(newFilter);
17553             scheduleWritePackageRestrictionsLocked(sourceUserId);
17554         }
17555     }
17556
17557     @Override
17558     public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17559         mContext.enforceCallingOrSelfPermission(
17560                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17561         int callingUid = Binder.getCallingUid();
17562         enforceOwnerRights(ownerPackage, callingUid);
17563         enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17564         synchronized (mPackages) {
17565             CrossProfileIntentResolver resolver =
17566                     mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17567             ArraySet<CrossProfileIntentFilter> set =
17568                     new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17569             for (CrossProfileIntentFilter filter : set) {
17570                 if (filter.getOwnerPackage().equals(ownerPackage)) {
17571                     resolver.removeFilter(filter);
17572                 }
17573             }
17574             scheduleWritePackageRestrictionsLocked(sourceUserId);
17575         }
17576     }
17577
17578     // Enforcing that callingUid is owning pkg on userId
17579     private void enforceOwnerRights(String pkg, int callingUid) {
17580         // The system owns everything.
17581         if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17582             return;
17583         }
17584         int callingUserId = UserHandle.getUserId(callingUid);
17585         PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17586         if (pi == null) {
17587             throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17588                     + callingUserId);
17589         }
17590         if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17591             throw new SecurityException("Calling uid " + callingUid
17592                     + " does not own package " + pkg);
17593         }
17594     }
17595
17596     @Override
17597     public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17598         return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17599     }
17600
17601     private Intent getHomeIntent() {
17602         Intent intent = new Intent(Intent.ACTION_MAIN);
17603         intent.addCategory(Intent.CATEGORY_HOME);
17604         return intent;
17605     }
17606
17607     private IntentFilter getHomeFilter() {
17608         IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17609         filter.addCategory(Intent.CATEGORY_HOME);
17610         filter.addCategory(Intent.CATEGORY_DEFAULT);
17611         return filter;
17612     }
17613
17614     ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17615             int userId) {
17616         Intent intent  = getHomeIntent();
17617         List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17618                 PackageManager.GET_META_DATA, userId);
17619         ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17620                 true, false, false, userId);
17621
17622         allHomeCandidates.clear();
17623         if (list != null) {
17624             for (ResolveInfo ri : list) {
17625                 allHomeCandidates.add(ri);
17626             }
17627         }
17628         return (preferred == null || preferred.activityInfo == null)
17629                 ? null
17630                 : new ComponentName(preferred.activityInfo.packageName,
17631                         preferred.activityInfo.name);
17632     }
17633
17634     @Override
17635     public void setHomeActivity(ComponentName comp, int userId) {
17636         ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17637         getHomeActivitiesAsUser(homeActivities, userId);
17638
17639         boolean found = false;
17640
17641         final int size = homeActivities.size();
17642         final ComponentName[] set = new ComponentName[size];
17643         for (int i = 0; i < size; i++) {
17644             final ResolveInfo candidate = homeActivities.get(i);
17645             final ActivityInfo info = candidate.activityInfo;
17646             final ComponentName activityName = new ComponentName(info.packageName, info.name);
17647             set[i] = activityName;
17648             if (!found && activityName.equals(comp)) {
17649                 found = true;
17650             }
17651         }
17652         if (!found) {
17653             throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17654                     + userId);
17655         }
17656         replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17657                 set, comp, userId);
17658     }
17659
17660     private @Nullable String getSetupWizardPackageName() {
17661         final Intent intent = new Intent(Intent.ACTION_MAIN);
17662         intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17663
17664         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17665                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17666                         | MATCH_DISABLED_COMPONENTS,
17667                 UserHandle.myUserId());
17668         if (matches.size() == 1) {
17669             return matches.get(0).getComponentInfo().packageName;
17670         } else {
17671             Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17672                     + ": matches=" + matches);
17673             return null;
17674         }
17675     }
17676
17677     @Override
17678     public void setApplicationEnabledSetting(String appPackageName,
17679             int newState, int flags, int userId, String callingPackage) {
17680         if (!sUserManager.exists(userId)) return;
17681         if (callingPackage == null) {
17682             callingPackage = Integer.toString(Binder.getCallingUid());
17683         }
17684         setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17685     }
17686
17687     @Override
17688     public void setComponentEnabledSetting(ComponentName componentName,
17689             int newState, int flags, int userId) {
17690         if (!sUserManager.exists(userId)) return;
17691         setEnabledSetting(componentName.getPackageName(),
17692                 componentName.getClassName(), newState, flags, userId, null);
17693     }
17694
17695     private void setEnabledSetting(final String packageName, String className, int newState,
17696             final int flags, int userId, String callingPackage) {
17697         if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17698               || newState == COMPONENT_ENABLED_STATE_ENABLED
17699               || newState == COMPONENT_ENABLED_STATE_DISABLED
17700               || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17701               || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17702             throw new IllegalArgumentException("Invalid new component state: "
17703                     + newState);
17704         }
17705         PackageSetting pkgSetting;
17706         final int uid = Binder.getCallingUid();
17707         final int permission;
17708         if (uid == Process.SYSTEM_UID) {
17709             permission = PackageManager.PERMISSION_GRANTED;
17710         } else {
17711             permission = mContext.checkCallingOrSelfPermission(
17712                     android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17713         }
17714         enforceCrossUserPermission(uid, userId,
17715                 false /* requireFullPermission */, true /* checkShell */, "set enabled");
17716         final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17717         boolean sendNow = false;
17718         boolean isApp = (className == null);
17719         String componentName = isApp ? packageName : className;
17720         int packageUid = -1;
17721         ArrayList<String> components;
17722
17723         // writer
17724         synchronized (mPackages) {
17725             pkgSetting = mSettings.mPackages.get(packageName);
17726             if (pkgSetting == null) {
17727                 if (className == null) {
17728                     throw new IllegalArgumentException("Unknown package: " + packageName);
17729                 }
17730                 throw new IllegalArgumentException(
17731                         "Unknown component: " + packageName + "/" + className);
17732             }
17733         }
17734
17735         // Limit who can change which apps
17736         if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17737             // Don't allow apps that don't have permission to modify other apps
17738             if (!allowedByPermission) {
17739                 throw new SecurityException(
17740                         "Permission Denial: attempt to change component state from pid="
17741                         + Binder.getCallingPid()
17742                         + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17743             }
17744             // Don't allow changing profile and device owners.
17745             if (mProtectedPackages.canPackageStateBeChanged(userId, packageName)) {
17746                 throw new SecurityException("Cannot disable a device owner or a profile owner");
17747             }
17748         }
17749
17750         synchronized (mPackages) {
17751             if (uid == Process.SHELL_UID) {
17752                 // Shell can only change whole packages between ENABLED and DISABLED_USER states
17753                 int oldState = pkgSetting.getEnabled(userId);
17754                 if (className == null
17755                     &&
17756                     (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17757                      || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17758                      || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17759                     &&
17760                     (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17761                      || newState == COMPONENT_ENABLED_STATE_DEFAULT
17762                      || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17763                     // ok
17764                 } else {
17765                     throw new SecurityException(
17766                             "Shell cannot change component state for " + packageName + "/"
17767                             + className + " to " + newState);
17768                 }
17769             }
17770             if (className == null) {
17771                 // We're dealing with an application/package level state change
17772                 if (pkgSetting.getEnabled(userId) == newState) {
17773                     // Nothing to do
17774                     return;
17775                 }
17776                 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17777                     || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17778                     // Don't care about who enables an app.
17779                     callingPackage = null;
17780                 }
17781                 pkgSetting.setEnabled(newState, userId, callingPackage);
17782                 // pkgSetting.pkg.mSetEnabled = newState;
17783             } else {
17784                 // We're dealing with a component level state change
17785                 // First, verify that this is a valid class name.
17786                 PackageParser.Package pkg = pkgSetting.pkg;
17787                 if (pkg == null || !pkg.hasComponentClassName(className)) {
17788                     if (pkg != null &&
17789                             pkg.applicationInfo.targetSdkVersion >=
17790                                     Build.VERSION_CODES.JELLY_BEAN) {
17791                         throw new IllegalArgumentException("Component class " + className
17792                                 + " does not exist in " + packageName);
17793                     } else {
17794                         Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17795                                 + className + " does not exist in " + packageName);
17796                     }
17797                 }
17798                 switch (newState) {
17799                 case COMPONENT_ENABLED_STATE_ENABLED:
17800                     if (!pkgSetting.enableComponentLPw(className, userId)) {
17801                         return;
17802                     }
17803                     break;
17804                 case COMPONENT_ENABLED_STATE_DISABLED:
17805                     if (!pkgSetting.disableComponentLPw(className, userId)) {
17806                         return;
17807                     }
17808                     break;
17809                 case COMPONENT_ENABLED_STATE_DEFAULT:
17810                     if (!pkgSetting.restoreComponentLPw(className, userId)) {
17811                         return;
17812                     }
17813                     break;
17814                 default:
17815                     Slog.e(TAG, "Invalid new component state: " + newState);
17816                     return;
17817                 }
17818             }
17819             scheduleWritePackageRestrictionsLocked(userId);
17820             components = mPendingBroadcasts.get(userId, packageName);
17821             final boolean newPackage = components == null;
17822             if (newPackage) {
17823                 components = new ArrayList<String>();
17824             }
17825             if (!components.contains(componentName)) {
17826                 components.add(componentName);
17827             }
17828             if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17829                 sendNow = true;
17830                 // Purge entry from pending broadcast list if another one exists already
17831                 // since we are sending one right away.
17832                 mPendingBroadcasts.remove(userId, packageName);
17833             } else {
17834                 if (newPackage) {
17835                     mPendingBroadcasts.put(userId, packageName, components);
17836                 }
17837                 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17838                     // Schedule a message
17839                     mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17840                 }
17841             }
17842         }
17843
17844         long callingId = Binder.clearCallingIdentity();
17845         try {
17846             if (sendNow) {
17847                 packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17848                 sendPackageChangedBroadcast(packageName,
17849                         (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17850             }
17851         } finally {
17852             Binder.restoreCallingIdentity(callingId);
17853         }
17854     }
17855
17856     @Override
17857     public void flushPackageRestrictionsAsUser(int userId) {
17858         if (!sUserManager.exists(userId)) {
17859             return;
17860         }
17861         enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17862                 false /* checkShell */, "flushPackageRestrictions");
17863         synchronized (mPackages) {
17864             mSettings.writePackageRestrictionsLPr(userId);
17865             mDirtyUsers.remove(userId);
17866             if (mDirtyUsers.isEmpty()) {
17867                 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17868             }
17869         }
17870     }
17871
17872     private void sendPackageChangedBroadcast(String packageName,
17873             boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17874         if (DEBUG_INSTALL)
17875             Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17876                     + componentNames);
17877         Bundle extras = new Bundle(4);
17878         extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17879         String nameList[] = new String[componentNames.size()];
17880         componentNames.toArray(nameList);
17881         extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17882         extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17883         extras.putInt(Intent.EXTRA_UID, packageUid);
17884         // If this is not reporting a change of the overall package, then only send it
17885         // to registered receivers.  We don't want to launch a swath of apps for every
17886         // little component state change.
17887         final int flags = !componentNames.contains(packageName)
17888                 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17889         sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17890                 new int[] {UserHandle.getUserId(packageUid)});
17891     }
17892
17893     @Override
17894     public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17895         if (!sUserManager.exists(userId)) return;
17896         final int uid = Binder.getCallingUid();
17897         final int permission = mContext.checkCallingOrSelfPermission(
17898                 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17899         final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17900         enforceCrossUserPermission(uid, userId,
17901                 true /* requireFullPermission */, true /* checkShell */, "stop package");
17902         // writer
17903         synchronized (mPackages) {
17904             if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17905                     allowedByPermission, uid, userId)) {
17906                 scheduleWritePackageRestrictionsLocked(userId);
17907             }
17908         }
17909     }
17910
17911     @Override
17912     public String getInstallerPackageName(String packageName) {
17913         // reader
17914         synchronized (mPackages) {
17915             return mSettings.getInstallerPackageNameLPr(packageName);
17916         }
17917     }
17918
17919     public boolean isOrphaned(String packageName) {
17920         // reader
17921         synchronized (mPackages) {
17922             return mSettings.isOrphaned(packageName);
17923         }
17924     }
17925
17926     @Override
17927     public int getApplicationEnabledSetting(String packageName, int userId) {
17928         if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17929         int uid = Binder.getCallingUid();
17930         enforceCrossUserPermission(uid, userId,
17931                 false /* requireFullPermission */, false /* checkShell */, "get enabled");
17932         // reader
17933         synchronized (mPackages) {
17934             return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17935         }
17936     }
17937
17938     @Override
17939     public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17940         if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17941         int uid = Binder.getCallingUid();
17942         enforceCrossUserPermission(uid, userId,
17943                 false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17944         // reader
17945         synchronized (mPackages) {
17946             return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17947         }
17948     }
17949
17950     @Override
17951     public void enterSafeMode() {
17952         enforceSystemOrRoot("Only the system can request entering safe mode");
17953
17954         if (!mSystemReady) {
17955             mSafeMode = true;
17956         }
17957     }
17958
17959     @Override
17960     public void systemReady() {
17961         mSystemReady = true;
17962
17963         // Read the compatibilty setting when the system is ready.
17964         boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17965                 mContext.getContentResolver(),
17966                 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17967         PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17968         if (DEBUG_SETTINGS) {
17969             Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17970         }
17971
17972         int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17973
17974         synchronized (mPackages) {
17975             // Verify that all of the preferred activity components actually
17976             // exist.  It is possible for applications to be updated and at
17977             // that point remove a previously declared activity component that
17978             // had been set as a preferred activity.  We try to clean this up
17979             // the next time we encounter that preferred activity, but it is
17980             // possible for the user flow to never be able to return to that
17981             // situation so here we do a sanity check to make sure we haven't
17982             // left any junk around.
17983             ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17984             for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17985                 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17986                 removed.clear();
17987                 for (PreferredActivity pa : pir.filterSet()) {
17988                     if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17989                         removed.add(pa);
17990                     }
17991                 }
17992                 if (removed.size() > 0) {
17993                     for (int r=0; r<removed.size(); r++) {
17994                         PreferredActivity pa = removed.get(r);
17995                         Slog.w(TAG, "Removing dangling preferred activity: "
17996                                 + pa.mPref.mComponent);
17997                         pir.removeFilter(pa);
17998                     }
17999                     mSettings.writePackageRestrictionsLPr(
18000                             mSettings.mPreferredActivities.keyAt(i));
18001                 }
18002             }
18003
18004             for (int userId : UserManagerService.getInstance().getUserIds()) {
18005                 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
18006                     grantPermissionsUserIds = ArrayUtils.appendInt(
18007                             grantPermissionsUserIds, userId);
18008                 }
18009             }
18010         }
18011         sUserManager.systemReady();
18012
18013         // If we upgraded grant all default permissions before kicking off.
18014         for (int userId : grantPermissionsUserIds) {
18015             mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18016         }
18017
18018         // Kick off any messages waiting for system ready
18019         if (mPostSystemReadyMessages != null) {
18020             for (Message msg : mPostSystemReadyMessages) {
18021                 msg.sendToTarget();
18022             }
18023             mPostSystemReadyMessages = null;
18024         }
18025
18026         // Watch for external volumes that come and go over time
18027         final StorageManager storage = mContext.getSystemService(StorageManager.class);
18028         storage.registerListener(mStorageListener);
18029
18030         mInstallerService.systemReady();
18031         mPackageDexOptimizer.systemReady();
18032
18033         MountServiceInternal mountServiceInternal = LocalServices.getService(
18034                 MountServiceInternal.class);
18035         mountServiceInternal.addExternalStoragePolicy(
18036                 new MountServiceInternal.ExternalStorageMountPolicy() {
18037             @Override
18038             public int getMountMode(int uid, String packageName) {
18039                 if (Process.isIsolated(uid)) {
18040                     return Zygote.MOUNT_EXTERNAL_NONE;
18041                 }
18042                 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18043                     return Zygote.MOUNT_EXTERNAL_DEFAULT;
18044                 }
18045                 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18046                     return Zygote.MOUNT_EXTERNAL_DEFAULT;
18047                 }
18048                 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18049                     return Zygote.MOUNT_EXTERNAL_READ;
18050                 }
18051                 return Zygote.MOUNT_EXTERNAL_WRITE;
18052             }
18053
18054             @Override
18055             public boolean hasExternalStorage(int uid, String packageName) {
18056                 return true;
18057             }
18058         });
18059
18060         // Now that we're mostly running, clean up stale users and apps
18061         reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18062         reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18063     }
18064
18065     @Override
18066     public boolean isSafeMode() {
18067         return mSafeMode;
18068     }
18069
18070     @Override
18071     public boolean hasSystemUidErrors() {
18072         return mHasSystemUidErrors;
18073     }
18074
18075     static String arrayToString(int[] array) {
18076         StringBuffer buf = new StringBuffer(128);
18077         buf.append('[');
18078         if (array != null) {
18079             for (int i=0; i<array.length; i++) {
18080                 if (i > 0) buf.append(", ");
18081                 buf.append(array[i]);
18082             }
18083         }
18084         buf.append(']');
18085         return buf.toString();
18086     }
18087
18088     static class DumpState {
18089         public static final int DUMP_LIBS = 1 << 0;
18090         public static final int DUMP_FEATURES = 1 << 1;
18091         public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18092         public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18093         public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18094         public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18095         public static final int DUMP_PERMISSIONS = 1 << 6;
18096         public static final int DUMP_PACKAGES = 1 << 7;
18097         public static final int DUMP_SHARED_USERS = 1 << 8;
18098         public static final int DUMP_MESSAGES = 1 << 9;
18099         public static final int DUMP_PROVIDERS = 1 << 10;
18100         public static final int DUMP_VERIFIERS = 1 << 11;
18101         public static final int DUMP_PREFERRED = 1 << 12;
18102         public static final int DUMP_PREFERRED_XML = 1 << 13;
18103         public static final int DUMP_KEYSETS = 1 << 14;
18104         public static final int DUMP_VERSION = 1 << 15;
18105         public static final int DUMP_INSTALLS = 1 << 16;
18106         public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18107         public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18108         public static final int DUMP_FROZEN = 1 << 19;
18109         public static final int DUMP_DEXOPT = 1 << 20;
18110
18111         public static final int OPTION_SHOW_FILTERS = 1 << 0;
18112
18113         private int mTypes;
18114
18115         private int mOptions;
18116
18117         private boolean mTitlePrinted;
18118
18119         private SharedUserSetting mSharedUser;
18120
18121         public boolean isDumping(int type) {
18122             if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18123                 return true;
18124             }
18125
18126             return (mTypes & type) != 0;
18127         }
18128
18129         public void setDump(int type) {
18130             mTypes |= type;
18131         }
18132
18133         public boolean isOptionEnabled(int option) {
18134             return (mOptions & option) != 0;
18135         }
18136
18137         public void setOptionEnabled(int option) {
18138             mOptions |= option;
18139         }
18140
18141         public boolean onTitlePrinted() {
18142             final boolean printed = mTitlePrinted;
18143             mTitlePrinted = true;
18144             return printed;
18145         }
18146
18147         public boolean getTitlePrinted() {
18148             return mTitlePrinted;
18149         }
18150
18151         public void setTitlePrinted(boolean enabled) {
18152             mTitlePrinted = enabled;
18153         }
18154
18155         public SharedUserSetting getSharedUser() {
18156             return mSharedUser;
18157         }
18158
18159         public void setSharedUser(SharedUserSetting user) {
18160             mSharedUser = user;
18161         }
18162     }
18163
18164     @Override
18165     public void onShellCommand(FileDescriptor in, FileDescriptor out,
18166             FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18167         (new PackageManagerShellCommand(this)).exec(
18168                 this, in, out, err, args, resultReceiver);
18169     }
18170
18171     @Override
18172     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18173         if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18174                 != PackageManager.PERMISSION_GRANTED) {
18175             pw.println("Permission Denial: can't dump ActivityManager from from pid="
18176                     + Binder.getCallingPid()
18177                     + ", uid=" + Binder.getCallingUid()
18178                     + " without permission "
18179                     + android.Manifest.permission.DUMP);
18180             return;
18181         }
18182
18183         DumpState dumpState = new DumpState();
18184         boolean fullPreferred = false;
18185         boolean checkin = false;
18186
18187         String packageName = null;
18188         ArraySet<String> permissionNames = null;
18189
18190         int opti = 0;
18191         while (opti < args.length) {
18192             String opt = args[opti];
18193             if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18194                 break;
18195             }
18196             opti++;
18197
18198             if ("-a".equals(opt)) {
18199                 // Right now we only know how to print all.
18200             } else if ("-h".equals(opt)) {
18201                 pw.println("Package manager dump options:");
18202                 pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18203                 pw.println("    --checkin: dump for a checkin");
18204                 pw.println("    -f: print details of intent filters");
18205                 pw.println("    -h: print this help");
18206                 pw.println("  cmd may be one of:");
18207                 pw.println("    l[ibraries]: list known shared libraries");
18208                 pw.println("    f[eatures]: list device features");
18209                 pw.println("    k[eysets]: print known keysets");
18210                 pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18211                 pw.println("    perm[issions]: dump permissions");
18212                 pw.println("    permission [name ...]: dump declaration and use of given permission");
18213                 pw.println("    pref[erred]: print preferred package settings");
18214                 pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18215                 pw.println("    prov[iders]: dump content providers");
18216                 pw.println("    p[ackages]: dump installed packages");
18217                 pw.println("    s[hared-users]: dump shared user IDs");
18218                 pw.println("    m[essages]: print collected runtime messages");
18219                 pw.println("    v[erifiers]: print package verifier info");
18220                 pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18221                 pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18222                 pw.println("    version: print database version info");
18223                 pw.println("    write: write current settings now");
18224                 pw.println("    installs: details about install sessions");
18225                 pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18226                 pw.println("    dexopt: dump dexopt state");
18227                 pw.println("    <package.name>: info about given package");
18228                 return;
18229             } else if ("--checkin".equals(opt)) {
18230                 checkin = true;
18231             } else if ("-f".equals(opt)) {
18232                 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18233             } else {
18234                 pw.println("Unknown argument: " + opt + "; use -h for help");
18235             }
18236         }
18237
18238         // Is the caller requesting to dump a particular piece of data?
18239         if (opti < args.length) {
18240             String cmd = args[opti];
18241             opti++;
18242             // Is this a package name?
18243             if ("android".equals(cmd) || cmd.contains(".")) {
18244                 packageName = cmd;
18245                 // When dumping a single package, we always dump all of its
18246                 // filter information since the amount of data will be reasonable.
18247                 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18248             } else if ("check-permission".equals(cmd)) {
18249                 if (opti >= args.length) {
18250                     pw.println("Error: check-permission missing permission argument");
18251                     return;
18252                 }
18253                 String perm = args[opti];
18254                 opti++;
18255                 if (opti >= args.length) {
18256                     pw.println("Error: check-permission missing package argument");
18257                     return;
18258                 }
18259                 String pkg = args[opti];
18260                 opti++;
18261                 int user = UserHandle.getUserId(Binder.getCallingUid());
18262                 if (opti < args.length) {
18263                     try {
18264                         user = Integer.parseInt(args[opti]);
18265                     } catch (NumberFormatException e) {
18266                         pw.println("Error: check-permission user argument is not a number: "
18267                                 + args[opti]);
18268                         return;
18269                     }
18270                 }
18271                 pw.println(checkPermission(perm, pkg, user));
18272                 return;
18273             } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18274                 dumpState.setDump(DumpState.DUMP_LIBS);
18275             } else if ("f".equals(cmd) || "features".equals(cmd)) {
18276                 dumpState.setDump(DumpState.DUMP_FEATURES);
18277             } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18278                 if (opti >= args.length) {
18279                     dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18280                             | DumpState.DUMP_SERVICE_RESOLVERS
18281                             | DumpState.DUMP_RECEIVER_RESOLVERS
18282                             | DumpState.DUMP_CONTENT_RESOLVERS);
18283                 } else {
18284                     while (opti < args.length) {
18285                         String name = args[opti];
18286                         if ("a".equals(name) || "activity".equals(name)) {
18287                             dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18288                         } else if ("s".equals(name) || "service".equals(name)) {
18289                             dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18290                         } else if ("r".equals(name) || "receiver".equals(name)) {
18291                             dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18292                         } else if ("c".equals(name) || "content".equals(name)) {
18293                             dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18294                         } else {
18295                             pw.println("Error: unknown resolver table type: " + name);
18296                             return;
18297                         }
18298                         opti++;
18299                     }
18300                 }
18301             } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18302                 dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18303             } else if ("permission".equals(cmd)) {
18304                 if (opti >= args.length) {
18305                     pw.println("Error: permission requires permission name");
18306                     return;
18307                 }
18308                 permissionNames = new ArraySet<>();
18309                 while (opti < args.length) {
18310                     permissionNames.add(args[opti]);
18311                     opti++;
18312                 }
18313                 dumpState.setDump(DumpState.DUMP_PERMISSIONS
18314                         | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18315             } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18316                 dumpState.setDump(DumpState.DUMP_PREFERRED);
18317             } else if ("preferred-xml".equals(cmd)) {
18318                 dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18319                 if (opti < args.length && "--full".equals(args[opti])) {
18320                     fullPreferred = true;
18321                     opti++;
18322                 }
18323             } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18324                 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18325             } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18326                 dumpState.setDump(DumpState.DUMP_PACKAGES);
18327             } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18328                 dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18329             } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18330                 dumpState.setDump(DumpState.DUMP_PROVIDERS);
18331             } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18332                 dumpState.setDump(DumpState.DUMP_MESSAGES);
18333             } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18334                 dumpState.setDump(DumpState.DUMP_VERIFIERS);
18335             } else if ("i".equals(cmd) || "ifv".equals(cmd)
18336                     || "intent-filter-verifiers".equals(cmd)) {
18337                 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18338             } else if ("version".equals(cmd)) {
18339                 dumpState.setDump(DumpState.DUMP_VERSION);
18340             } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18341                 dumpState.setDump(DumpState.DUMP_KEYSETS);
18342             } else if ("installs".equals(cmd)) {
18343                 dumpState.setDump(DumpState.DUMP_INSTALLS);
18344             } else if ("frozen".equals(cmd)) {
18345                 dumpState.setDump(DumpState.DUMP_FROZEN);
18346             } else if ("dexopt".equals(cmd)) {
18347                 dumpState.setDump(DumpState.DUMP_DEXOPT);
18348             } else if ("write".equals(cmd)) {
18349                 synchronized (mPackages) {
18350                     mSettings.writeLPr();
18351                     pw.println("Settings written.");
18352                     return;
18353                 }
18354             }
18355         }
18356
18357         if (checkin) {
18358             pw.println("vers,1");
18359         }
18360
18361         // reader
18362         synchronized (mPackages) {
18363             if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18364                 if (!checkin) {
18365                     if (dumpState.onTitlePrinted())
18366                         pw.println();
18367                     pw.println("Database versions:");
18368                     mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18369                 }
18370             }
18371
18372             if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18373                 if (!checkin) {
18374                     if (dumpState.onTitlePrinted())
18375                         pw.println();
18376                     pw.println("Verifiers:");
18377                     pw.print("  Required: ");
18378                     pw.print(mRequiredVerifierPackage);
18379                     pw.print(" (uid=");
18380                     pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18381                             UserHandle.USER_SYSTEM));
18382                     pw.println(")");
18383                 } else if (mRequiredVerifierPackage != null) {
18384                     pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18385                     pw.print(",");
18386                     pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18387                             UserHandle.USER_SYSTEM));
18388                 }
18389             }
18390
18391             if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18392                     packageName == null) {
18393                 if (mIntentFilterVerifierComponent != null) {
18394                     String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18395                     if (!checkin) {
18396                         if (dumpState.onTitlePrinted())
18397                             pw.println();
18398                         pw.println("Intent Filter Verifier:");
18399                         pw.print("  Using: ");
18400                         pw.print(verifierPackageName);
18401                         pw.print(" (uid=");
18402                         pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18403                                 UserHandle.USER_SYSTEM));
18404                         pw.println(")");
18405                     } else if (verifierPackageName != null) {
18406                         pw.print("ifv,"); pw.print(verifierPackageName);
18407                         pw.print(",");
18408                         pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18409                                 UserHandle.USER_SYSTEM));
18410                     }
18411                 } else {
18412                     pw.println();
18413                     pw.println("No Intent Filter Verifier available!");
18414                 }
18415             }
18416
18417             if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18418                 boolean printedHeader = false;
18419                 final Iterator<String> it = mSharedLibraries.keySet().iterator();
18420                 while (it.hasNext()) {
18421                     String name = it.next();
18422                     SharedLibraryEntry ent = mSharedLibraries.get(name);
18423                     if (!checkin) {
18424                         if (!printedHeader) {
18425                             if (dumpState.onTitlePrinted())
18426                                 pw.println();
18427                             pw.println("Libraries:");
18428                             printedHeader = true;
18429                         }
18430                         pw.print("  ");
18431                     } else {
18432                         pw.print("lib,");
18433                     }
18434                     pw.print(name);
18435                     if (!checkin) {
18436                         pw.print(" -> ");
18437                     }
18438                     if (ent.path != null) {
18439                         if (!checkin) {
18440                             pw.print("(jar) ");
18441                             pw.print(ent.path);
18442                         } else {
18443                             pw.print(",jar,");
18444                             pw.print(ent.path);
18445                         }
18446                     } else {
18447                         if (!checkin) {
18448                             pw.print("(apk) ");
18449                             pw.print(ent.apk);
18450                         } else {
18451                             pw.print(",apk,");
18452                             pw.print(ent.apk);
18453                         }
18454                     }
18455                     pw.println();
18456                 }
18457             }
18458
18459             if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18460                 if (dumpState.onTitlePrinted())
18461                     pw.println();
18462                 if (!checkin) {
18463                     pw.println("Features:");
18464                 }
18465
18466                 for (FeatureInfo feat : mAvailableFeatures.values()) {
18467                     if (checkin) {
18468                         pw.print("feat,");
18469                         pw.print(feat.name);
18470                         pw.print(",");
18471                         pw.println(feat.version);
18472                     } else {
18473                         pw.print("  ");
18474                         pw.print(feat.name);
18475                         if (feat.version > 0) {
18476                             pw.print(" version=");
18477                             pw.print(feat.version);
18478                         }
18479                         pw.println();
18480                     }
18481                 }
18482             }
18483
18484             if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18485                 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18486                         : "Activity Resolver Table:", "  ", packageName,
18487                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18488                     dumpState.setTitlePrinted(true);
18489                 }
18490             }
18491             if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18492                 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18493                         : "Receiver Resolver Table:", "  ", packageName,
18494                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18495                     dumpState.setTitlePrinted(true);
18496                 }
18497             }
18498             if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18499                 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18500                         : "Service Resolver Table:", "  ", packageName,
18501                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18502                     dumpState.setTitlePrinted(true);
18503                 }
18504             }
18505             if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18506                 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18507                         : "Provider Resolver Table:", "  ", packageName,
18508                         dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18509                     dumpState.setTitlePrinted(true);
18510                 }
18511             }
18512
18513             if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18514                 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18515                     PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18516                     int user = mSettings.mPreferredActivities.keyAt(i);
18517                     if (pir.dump(pw,
18518                             dumpState.getTitlePrinted()
18519                                 ? "\nPreferred Activities User " + user + ":"
18520                                 : "Preferred Activities User " + user + ":", "  ",
18521                             packageName, true, false)) {
18522                         dumpState.setTitlePrinted(true);
18523                     }
18524                 }
18525             }
18526
18527             if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18528                 pw.flush();
18529                 FileOutputStream fout = new FileOutputStream(fd);
18530                 BufferedOutputStream str = new BufferedOutputStream(fout);
18531                 XmlSerializer serializer = new FastXmlSerializer();
18532                 try {
18533                     serializer.setOutput(str, StandardCharsets.UTF_8.name());
18534                     serializer.startDocument(null, true);
18535                     serializer.setFeature(
18536                             "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18537                     mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18538                     serializer.endDocument();
18539                     serializer.flush();
18540                 } catch (IllegalArgumentException e) {
18541                     pw.println("Failed writing: " + e);
18542                 } catch (IllegalStateException e) {
18543                     pw.println("Failed writing: " + e);
18544                 } catch (IOException e) {
18545                     pw.println("Failed writing: " + e);
18546                 }
18547             }
18548
18549             if (!checkin
18550                     && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18551                     && packageName == null) {
18552                 pw.println();
18553                 int count = mSettings.mPackages.size();
18554                 if (count == 0) {
18555                     pw.println("No applications!");
18556                     pw.println();
18557                 } else {
18558                     final String prefix = "  ";
18559                     Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18560                     if (allPackageSettings.size() == 0) {
18561                         pw.println("No domain preferred apps!");
18562                         pw.println();
18563                     } else {
18564                         pw.println("App verification status:");
18565                         pw.println();
18566                         count = 0;
18567                         for (PackageSetting ps : allPackageSettings) {
18568                             IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18569                             if (ivi == null || ivi.getPackageName() == null) continue;
18570                             pw.println(prefix + "Package: " + ivi.getPackageName());
18571                             pw.println(prefix + "Domains: " + ivi.getDomainsString());
18572                             pw.println(prefix + "Status:  " + ivi.getStatusString());
18573                             pw.println();
18574                             count++;
18575                         }
18576                         if (count == 0) {
18577                             pw.println(prefix + "No app verification established.");
18578                             pw.println();
18579                         }
18580                         for (int userId : sUserManager.getUserIds()) {
18581                             pw.println("App linkages for user " + userId + ":");
18582                             pw.println();
18583                             count = 0;
18584                             for (PackageSetting ps : allPackageSettings) {
18585                                 final long status = ps.getDomainVerificationStatusForUser(userId);
18586                                 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18587                                     continue;
18588                                 }
18589                                 pw.println(prefix + "Package: " + ps.name);
18590                                 pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18591                                 String statusStr = IntentFilterVerificationInfo.
18592                                         getStatusStringFromValue(status);
18593                                 pw.println(prefix + "Status:  " + statusStr);
18594                                 pw.println();
18595                                 count++;
18596                             }
18597                             if (count == 0) {
18598                                 pw.println(prefix + "No configured app linkages.");
18599                                 pw.println();
18600                             }
18601                         }
18602                     }
18603                 }
18604             }
18605
18606             if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18607                 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18608                 if (packageName == null && permissionNames == null) {
18609                     for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18610                         if (iperm == 0) {
18611                             if (dumpState.onTitlePrinted())
18612                                 pw.println();
18613                             pw.println("AppOp Permissions:");
18614                         }
18615                         pw.print("  AppOp Permission ");
18616                         pw.print(mAppOpPermissionPackages.keyAt(iperm));
18617                         pw.println(":");
18618                         ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18619                         for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18620                             pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18621                         }
18622                     }
18623                 }
18624             }
18625
18626             if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18627                 boolean printedSomething = false;
18628                 for (PackageParser.Provider p : mProviders.mProviders.values()) {
18629                     if (packageName != null && !packageName.equals(p.info.packageName)) {
18630                         continue;
18631                     }
18632                     if (!printedSomething) {
18633                         if (dumpState.onTitlePrinted())
18634                             pw.println();
18635                         pw.println("Registered ContentProviders:");
18636                         printedSomething = true;
18637                     }
18638                     pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18639                     pw.print("    "); pw.println(p.toString());
18640                 }
18641                 printedSomething = false;
18642                 for (Map.Entry<String, PackageParser.Provider> entry :
18643                         mProvidersByAuthority.entrySet()) {
18644                     PackageParser.Provider p = entry.getValue();
18645                     if (packageName != null && !packageName.equals(p.info.packageName)) {
18646                         continue;
18647                     }
18648                     if (!printedSomething) {
18649                         if (dumpState.onTitlePrinted())
18650                             pw.println();
18651                         pw.println("ContentProvider Authorities:");
18652                         printedSomething = true;
18653                     }
18654                     pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18655                     pw.print("    "); pw.println(p.toString());
18656                     if (p.info != null && p.info.applicationInfo != null) {
18657                         final String appInfo = p.info.applicationInfo.toString();
18658                         pw.print("      applicationInfo="); pw.println(appInfo);
18659                     }
18660                 }
18661             }
18662
18663             if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18664                 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18665             }
18666
18667             if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18668                 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18669             }
18670
18671             if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18672                 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18673             }
18674
18675             if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18676                 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18677             }
18678
18679             if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18680                 // XXX should handle packageName != null by dumping only install data that
18681                 // the given package is involved with.
18682                 if (dumpState.onTitlePrinted()) pw.println();
18683                 mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18684             }
18685
18686             if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18687                 // XXX should handle packageName != null by dumping only install data that
18688                 // the given package is involved with.
18689                 if (dumpState.onTitlePrinted()) pw.println();
18690
18691                 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18692                 ipw.println();
18693                 ipw.println("Frozen packages:");
18694                 ipw.increaseIndent();
18695                 if (mFrozenPackages.size() == 0) {
18696                     ipw.println("(none)");
18697                 } else {
18698                     for (int i = 0; i < mFrozenPackages.size(); i++) {
18699                         ipw.println(mFrozenPackages.valueAt(i));
18700                     }
18701                 }
18702                 ipw.decreaseIndent();
18703             }
18704
18705             if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18706                 if (dumpState.onTitlePrinted()) pw.println();
18707                 dumpDexoptStateLPr(pw, packageName);
18708             }
18709
18710             if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18711                 if (dumpState.onTitlePrinted()) pw.println();
18712                 mSettings.dumpReadMessagesLPr(pw, dumpState);
18713
18714                 pw.println();
18715                 pw.println("Package warning messages:");
18716                 BufferedReader in = null;
18717                 String line = null;
18718                 try {
18719                     in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18720                     while ((line = in.readLine()) != null) {
18721                         if (line.contains("ignored: updated version")) continue;
18722                         pw.println(line);
18723                     }
18724                 } catch (IOException ignored) {
18725                 } finally {
18726                     IoUtils.closeQuietly(in);
18727                 }
18728             }
18729
18730             if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18731                 BufferedReader in = null;
18732                 String line = null;
18733                 try {
18734                     in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18735                     while ((line = in.readLine()) != null) {
18736                         if (line.contains("ignored: updated version")) continue;
18737                         pw.print("msg,");
18738                         pw.println(line);
18739                     }
18740                 } catch (IOException ignored) {
18741                 } finally {
18742                     IoUtils.closeQuietly(in);
18743                 }
18744             }
18745         }
18746     }
18747
18748     private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18749         final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18750         ipw.println();
18751         ipw.println("Dexopt state:");
18752         ipw.increaseIndent();
18753         Collection<PackageParser.Package> packages = null;
18754         if (packageName != null) {
18755             PackageParser.Package targetPackage = mPackages.get(packageName);
18756             if (targetPackage != null) {
18757                 packages = Collections.singletonList(targetPackage);
18758             } else {
18759                 ipw.println("Unable to find package: " + packageName);
18760                 return;
18761             }
18762         } else {
18763             packages = mPackages.values();
18764         }
18765
18766         for (PackageParser.Package pkg : packages) {
18767             ipw.println("[" + pkg.packageName + "]");
18768             ipw.increaseIndent();
18769             mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18770             ipw.decreaseIndent();
18771         }
18772     }
18773
18774     private String dumpDomainString(String packageName) {
18775         List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18776                 .getList();
18777         List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18778
18779         ArraySet<String> result = new ArraySet<>();
18780         if (iviList.size() > 0) {
18781             for (IntentFilterVerificationInfo ivi : iviList) {
18782                 for (String host : ivi.getDomains()) {
18783                     result.add(host);
18784                 }
18785             }
18786         }
18787         if (filters != null && filters.size() > 0) {
18788             for (IntentFilter filter : filters) {
18789                 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18790                         && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18791                                 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18792                     result.addAll(filter.getHostsList());
18793                 }
18794             }
18795         }
18796
18797         StringBuilder sb = new StringBuilder(result.size() * 16);
18798         for (String domain : result) {
18799             if (sb.length() > 0) sb.append(" ");
18800             sb.append(domain);
18801         }
18802         return sb.toString();
18803     }
18804
18805     // ------- apps on sdcard specific code -------
18806     static final boolean DEBUG_SD_INSTALL = false;
18807
18808     private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18809
18810     private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18811
18812     private boolean mMediaMounted = false;
18813
18814     static String getEncryptKey() {
18815         try {
18816             String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18817                     SD_ENCRYPTION_KEYSTORE_NAME);
18818             if (sdEncKey == null) {
18819                 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18820                         SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18821                 if (sdEncKey == null) {
18822                     Slog.e(TAG, "Failed to create encryption keys");
18823                     return null;
18824                 }
18825             }
18826             return sdEncKey;
18827         } catch (NoSuchAlgorithmException nsae) {
18828             Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18829             return null;
18830         } catch (IOException ioe) {
18831             Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18832             return null;
18833         }
18834     }
18835
18836     /*
18837      * Update media status on PackageManager.
18838      */
18839     @Override
18840     public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18841         int callingUid = Binder.getCallingUid();
18842         if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18843             throw new SecurityException("Media status can only be updated by the system");
18844         }
18845         // reader; this apparently protects mMediaMounted, but should probably
18846         // be a different lock in that case.
18847         synchronized (mPackages) {
18848             Log.i(TAG, "Updating external media status from "
18849                     + (mMediaMounted ? "mounted" : "unmounted") + " to "
18850                     + (mediaStatus ? "mounted" : "unmounted"));
18851             if (DEBUG_SD_INSTALL)
18852                 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18853                         + ", mMediaMounted=" + mMediaMounted);
18854             if (mediaStatus == mMediaMounted) {
18855                 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18856                         : 0, -1);
18857                 mHandler.sendMessage(msg);
18858                 return;
18859             }
18860             mMediaMounted = mediaStatus;
18861         }
18862         // Queue up an async operation since the package installation may take a
18863         // little while.
18864         mHandler.post(new Runnable() {
18865             public void run() {
18866                 updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18867             }
18868         });
18869     }
18870
18871     /**
18872      * Called by MountService when the initial ASECs to scan are available.
18873      * Should block until all the ASEC containers are finished being scanned.
18874      */
18875     public void scanAvailableAsecs() {
18876         updateExternalMediaStatusInner(true, false, false);
18877     }
18878
18879     /*
18880      * Collect information of applications on external media, map them against
18881      * existing containers and update information based on current mount status.
18882      * Please note that we always have to report status if reportStatus has been
18883      * set to true especially when unloading packages.
18884      */
18885     private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18886             boolean externalStorage) {
18887         ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18888         int[] uidArr = EmptyArray.INT;
18889
18890         final String[] list = PackageHelper.getSecureContainerList();
18891         if (ArrayUtils.isEmpty(list)) {
18892             Log.i(TAG, "No secure containers found");
18893         } else {
18894             // Process list of secure containers and categorize them
18895             // as active or stale based on their package internal state.
18896
18897             // reader
18898             synchronized (mPackages) {
18899                 for (String cid : list) {
18900                     // Leave stages untouched for now; installer service owns them
18901                     if (PackageInstallerService.isStageName(cid)) continue;
18902
18903                     if (DEBUG_SD_INSTALL)
18904                         Log.i(TAG, "Processing container " + cid);
18905                     String pkgName = getAsecPackageName(cid);
18906                     if (pkgName == null) {
18907                         Slog.i(TAG, "Found stale container " + cid + " with no package name");
18908                         continue;
18909                     }
18910                     if (DEBUG_SD_INSTALL)
18911                         Log.i(TAG, "Looking for pkg : " + pkgName);
18912
18913                     final PackageSetting ps = mSettings.mPackages.get(pkgName);
18914                     if (ps == null) {
18915                         Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18916                         continue;
18917                     }
18918
18919                     /*
18920                      * Skip packages that are not external if we're unmounting
18921                      * external storage.
18922                      */
18923                     if (externalStorage && !isMounted && !isExternal(ps)) {
18924                         continue;
18925                     }
18926
18927                     final AsecInstallArgs args = new AsecInstallArgs(cid,
18928                             getAppDexInstructionSets(ps), ps.isForwardLocked());
18929                     // The package status is changed only if the code path
18930                     // matches between settings and the container id.
18931                     if (ps.codePathString != null
18932                             && ps.codePathString.startsWith(args.getCodePath())) {
18933                         if (DEBUG_SD_INSTALL) {
18934                             Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18935                                     + " at code path: " + ps.codePathString);
18936                         }
18937
18938                         // We do have a valid package installed on sdcard
18939                         processCids.put(args, ps.codePathString);
18940                         final int uid = ps.appId;
18941                         if (uid != -1) {
18942                             uidArr = ArrayUtils.appendInt(uidArr, uid);
18943                         }
18944                     } else {
18945                         Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18946                                 + ps.codePathString);
18947                     }
18948                 }
18949             }
18950
18951             Arrays.sort(uidArr);
18952         }
18953
18954         // Process packages with valid entries.
18955         if (isMounted) {
18956             if (DEBUG_SD_INSTALL)
18957                 Log.i(TAG, "Loading packages");
18958             loadMediaPackages(processCids, uidArr, externalStorage);
18959             startCleaningPackages();
18960             mInstallerService.onSecureContainersAvailable();
18961         } else {
18962             if (DEBUG_SD_INSTALL)
18963                 Log.i(TAG, "Unloading packages");
18964             unloadMediaPackages(processCids, uidArr, reportStatus);
18965         }
18966     }
18967
18968     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18969             ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18970         final int size = infos.size();
18971         final String[] packageNames = new String[size];
18972         final int[] packageUids = new int[size];
18973         for (int i = 0; i < size; i++) {
18974             final ApplicationInfo info = infos.get(i);
18975             packageNames[i] = info.packageName;
18976             packageUids[i] = info.uid;
18977         }
18978         sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18979                 finishedReceiver);
18980     }
18981
18982     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18983             ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18984         sendResourcesChangedBroadcast(mediaStatus, replacing,
18985                 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18986     }
18987
18988     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18989             String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18990         int size = pkgList.length;
18991         if (size > 0) {
18992             // Send broadcasts here
18993             Bundle extras = new Bundle();
18994             extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18995             if (uidArr != null) {
18996                 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18997             }
18998             if (replacing) {
18999                 extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
19000             }
19001             String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
19002                     : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
19003             sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
19004         }
19005     }
19006
19007    /*
19008      * Look at potentially valid container ids from processCids If package
19009      * information doesn't match the one on record or package scanning fails,
19010      * the cid is added to list of removeCids. We currently don't delete stale
19011      * containers.
19012      */
19013     private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19014             boolean externalStorage) {
19015         ArrayList<String> pkgList = new ArrayList<String>();
19016         Set<AsecInstallArgs> keys = processCids.keySet();
19017
19018         for (AsecInstallArgs args : keys) {
19019             String codePath = processCids.get(args);
19020             if (DEBUG_SD_INSTALL)
19021                 Log.i(TAG, "Loading container : " + args.cid);
19022             int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19023             try {
19024                 // Make sure there are no container errors first.
19025                 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19026                     Slog.e(TAG, "Failed to mount cid : " + args.cid
19027                             + " when installing from sdcard");
19028                     continue;
19029                 }
19030                 // Check code path here.
19031                 if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19032                     Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19033                             + " does not match one in settings " + codePath);
19034                     continue;
19035                 }
19036                 // Parse package
19037                 int parseFlags = mDefParseFlags;
19038                 if (args.isExternalAsec()) {
19039                     parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19040                 }
19041                 if (args.isFwdLocked()) {
19042                     parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19043                 }
19044
19045                 synchronized (mInstallLock) {
19046                     PackageParser.Package pkg = null;
19047                     try {
19048                         // Sadly we don't know the package name yet to freeze it
19049                         pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19050                                 SCAN_IGNORE_FROZEN, 0, null);
19051                     } catch (PackageManagerException e) {
19052                         Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19053                     }
19054                     // Scan the package
19055                     if (pkg != null) {
19056                         /*
19057                          * TODO why is the lock being held? doPostInstall is
19058                          * called in other places without the lock. This needs
19059                          * to be straightened out.
19060                          */
19061                         // writer
19062                         synchronized (mPackages) {
19063                             retCode = PackageManager.INSTALL_SUCCEEDED;
19064                             pkgList.add(pkg.packageName);
19065                             // Post process args
19066                             args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19067                                     pkg.applicationInfo.uid);
19068                         }
19069                     } else {
19070                         Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19071                     }
19072                 }
19073
19074             } finally {
19075                 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19076                     Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19077                 }
19078             }
19079         }
19080         // writer
19081         synchronized (mPackages) {
19082             // If the platform SDK has changed since the last time we booted,
19083             // we need to re-grant app permission to catch any new ones that
19084             // appear. This is really a hack, and means that apps can in some
19085             // cases get permissions that the user didn't initially explicitly
19086             // allow... it would be nice to have some better way to handle
19087             // this situation.
19088             final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19089                     : mSettings.getInternalVersion();
19090             final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19091                     : StorageManager.UUID_PRIVATE_INTERNAL;
19092
19093             int updateFlags = UPDATE_PERMISSIONS_ALL;
19094             if (ver.sdkVersion != mSdkVersion) {
19095                 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19096                         + mSdkVersion + "; regranting permissions for external");
19097                 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19098             }
19099             updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19100
19101             // Yay, everything is now upgraded
19102             ver.forceCurrent();
19103
19104             // can downgrade to reader
19105             // Persist settings
19106             mSettings.writeLPr();
19107         }
19108         // Send a broadcast to let everyone know we are done processing
19109         if (pkgList.size() > 0) {
19110             sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19111         }
19112     }
19113
19114    /*
19115      * Utility method to unload a list of specified containers
19116      */
19117     private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19118         // Just unmount all valid containers.
19119         for (AsecInstallArgs arg : cidArgs) {
19120             synchronized (mInstallLock) {
19121                 arg.doPostDeleteLI(false);
19122            }
19123        }
19124    }
19125
19126     /*
19127      * Unload packages mounted on external media. This involves deleting package
19128      * data from internal structures, sending broadcasts about disabled packages,
19129      * gc'ing to free up references, unmounting all secure containers
19130      * corresponding to packages on external media, and posting a
19131      * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19132      * that we always have to post this message if status has been requested no
19133      * matter what.
19134      */
19135     private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19136             final boolean reportStatus) {
19137         if (DEBUG_SD_INSTALL)
19138             Log.i(TAG, "unloading media packages");
19139         ArrayList<String> pkgList = new ArrayList<String>();
19140         ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19141         final Set<AsecInstallArgs> keys = processCids.keySet();
19142         for (AsecInstallArgs args : keys) {
19143             String pkgName = args.getPackageName();
19144             if (DEBUG_SD_INSTALL)
19145                 Log.i(TAG, "Trying to unload pkg : " + pkgName);
19146             // Delete package internally
19147             PackageRemovedInfo outInfo = new PackageRemovedInfo();
19148             synchronized (mInstallLock) {
19149                 final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19150                 final boolean res;
19151                 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19152                         "unloadMediaPackages")) {
19153                     res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19154                             null);
19155                 }
19156                 if (res) {
19157                     pkgList.add(pkgName);
19158                 } else {
19159                     Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19160                     failedList.add(args);
19161                 }
19162             }
19163         }
19164
19165         // reader
19166         synchronized (mPackages) {
19167             // We didn't update the settings after removing each package;
19168             // write them now for all packages.
19169             mSettings.writeLPr();
19170         }
19171
19172         // We have to absolutely send UPDATED_MEDIA_STATUS only
19173         // after confirming that all the receivers processed the ordered
19174         // broadcast when packages get disabled, force a gc to clean things up.
19175         // and unload all the containers.
19176         if (pkgList.size() > 0) {
19177             sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19178                     new IIntentReceiver.Stub() {
19179                 public void performReceive(Intent intent, int resultCode, String data,
19180                         Bundle extras, boolean ordered, boolean sticky,
19181                         int sendingUser) throws RemoteException {
19182                     Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19183                             reportStatus ? 1 : 0, 1, keys);
19184                     mHandler.sendMessage(msg);
19185                 }
19186             });
19187         } else {
19188             Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19189                     keys);
19190             mHandler.sendMessage(msg);
19191         }
19192     }
19193
19194     private void loadPrivatePackages(final VolumeInfo vol) {
19195         mHandler.post(new Runnable() {
19196             @Override
19197             public void run() {
19198                 loadPrivatePackagesInner(vol);
19199             }
19200         });
19201     }
19202
19203     private void loadPrivatePackagesInner(VolumeInfo vol) {
19204         final String volumeUuid = vol.fsUuid;
19205         if (TextUtils.isEmpty(volumeUuid)) {
19206             Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19207             return;
19208         }
19209
19210         final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19211         final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19212         final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19213
19214         final VersionInfo ver;
19215         final List<PackageSetting> packages;
19216         synchronized (mPackages) {
19217             ver = mSettings.findOrCreateVersion(volumeUuid);
19218             packages = mSettings.getVolumePackagesLPr(volumeUuid);
19219         }
19220
19221         for (PackageSetting ps : packages) {
19222             freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19223             synchronized (mInstallLock) {
19224                 final PackageParser.Package pkg;
19225                 try {
19226                     pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19227                     loaded.add(pkg.applicationInfo);
19228
19229                 } catch (PackageManagerException e) {
19230                     Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19231                 }
19232
19233                 if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19234                     clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19235                             StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19236                                     | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19237                 }
19238             }
19239         }
19240
19241         // Reconcile app data for all started/unlocked users
19242         final StorageManager sm = mContext.getSystemService(StorageManager.class);
19243         final UserManager um = mContext.getSystemService(UserManager.class);
19244         UserManagerInternal umInternal = getUserManagerInternal();
19245         for (UserInfo user : um.getUsers()) {
19246             final int flags;
19247             if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19248                 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19249             } else if (umInternal.isUserRunning(user.id)) {
19250                 flags = StorageManager.FLAG_STORAGE_DE;
19251             } else {
19252                 continue;
19253             }
19254
19255             try {
19256                 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19257                 synchronized (mInstallLock) {
19258                     reconcileAppsDataLI(volumeUuid, user.id, flags);
19259                 }
19260             } catch (IllegalStateException e) {
19261                 // Device was probably ejected, and we'll process that event momentarily
19262                 Slog.w(TAG, "Failed to prepare storage: " + e);
19263             }
19264         }
19265
19266         synchronized (mPackages) {
19267             int updateFlags = UPDATE_PERMISSIONS_ALL;
19268             if (ver.sdkVersion != mSdkVersion) {
19269                 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19270                         + mSdkVersion + "; regranting permissions for " + volumeUuid);
19271                 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19272             }
19273             updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19274
19275             // Yay, everything is now upgraded
19276             ver.forceCurrent();
19277
19278             mSettings.writeLPr();
19279         }
19280
19281         for (PackageFreezer freezer : freezers) {
19282             freezer.close();
19283         }
19284
19285         if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19286         sendResourcesChangedBroadcast(true, false, loaded, null);
19287     }
19288
19289     private void unloadPrivatePackages(final VolumeInfo vol) {
19290         mHandler.post(new Runnable() {
19291             @Override
19292             public void run() {
19293                 unloadPrivatePackagesInner(vol);
19294             }
19295         });
19296     }
19297
19298     private void unloadPrivatePackagesInner(VolumeInfo vol) {
19299         final String volumeUuid = vol.fsUuid;
19300         if (TextUtils.isEmpty(volumeUuid)) {
19301             Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19302             return;
19303         }
19304
19305         final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19306         synchronized (mInstallLock) {
19307         synchronized (mPackages) {
19308             final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19309             for (PackageSetting ps : packages) {
19310                 if (ps.pkg == null) continue;
19311
19312                 final ApplicationInfo info = ps.pkg.applicationInfo;
19313                 final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19314                 final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19315
19316                 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19317                         "unloadPrivatePackagesInner")) {
19318                     if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19319                             false, null)) {
19320                         unloaded.add(info);
19321                     } else {
19322                         Slog.w(TAG, "Failed to unload " + ps.codePath);
19323                     }
19324                 }
19325
19326                 // Try very hard to release any references to this package
19327                 // so we don't risk the system server being killed due to
19328                 // open FDs
19329                 AttributeCache.instance().removePackage(ps.name);
19330             }
19331
19332             mSettings.writeLPr();
19333         }
19334         }
19335
19336         if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19337         sendResourcesChangedBroadcast(false, false, unloaded, null);
19338
19339         // Try very hard to release any references to this path so we don't risk
19340         // the system server being killed due to open FDs
19341         ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19342
19343         for (int i = 0; i < 3; i++) {
19344             System.gc();
19345             System.runFinalization();
19346         }
19347     }
19348
19349     /**
19350      * Prepare storage areas for given user on all mounted devices.
19351      */
19352     void prepareUserData(int userId, int userSerial, int flags) {
19353         synchronized (mInstallLock) {
19354             final StorageManager storage = mContext.getSystemService(StorageManager.class);
19355             for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19356                 final String volumeUuid = vol.getFsUuid();
19357                 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19358             }
19359         }
19360     }
19361
19362     private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19363             boolean allowRecover) {
19364         // Prepare storage and verify that serial numbers are consistent; if
19365         // there's a mismatch we need to destroy to avoid leaking data
19366         final StorageManager storage = mContext.getSystemService(StorageManager.class);
19367         try {
19368             storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19369
19370             if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19371                 UserManagerService.enforceSerialNumber(
19372                         Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19373                 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19374                     UserManagerService.enforceSerialNumber(
19375                             Environment.getDataSystemDeDirectory(userId), userSerial);
19376                 }
19377             }
19378             if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19379                 UserManagerService.enforceSerialNumber(
19380                         Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19381                 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19382                     UserManagerService.enforceSerialNumber(
19383                             Environment.getDataSystemCeDirectory(userId), userSerial);
19384                 }
19385             }
19386
19387             synchronized (mInstallLock) {
19388                 mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19389             }
19390         } catch (Exception e) {
19391             logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19392                     + " because we failed to prepare: " + e);
19393             destroyUserDataLI(volumeUuid, userId,
19394                     StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19395
19396             if (allowRecover) {
19397                 // Try one last time; if we fail again we're really in trouble
19398                 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19399             }
19400         }
19401     }
19402
19403     /**
19404      * Destroy storage areas for given user on all mounted devices.
19405      */
19406     void destroyUserData(int userId, int flags) {
19407         synchronized (mInstallLock) {
19408             final StorageManager storage = mContext.getSystemService(StorageManager.class);
19409             for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19410                 final String volumeUuid = vol.getFsUuid();
19411                 destroyUserDataLI(volumeUuid, userId, flags);
19412             }
19413         }
19414     }
19415
19416     private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19417         final StorageManager storage = mContext.getSystemService(StorageManager.class);
19418         try {
19419             // Clean up app data, profile data, and media data
19420             mInstaller.destroyUserData(volumeUuid, userId, flags);
19421
19422             // Clean up system data
19423             if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19424                 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19425                     FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19426                     FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19427                 }
19428                 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19429                     FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19430                 }
19431             }
19432
19433             // Data with special labels is now gone, so finish the job
19434             storage.destroyUserStorage(volumeUuid, userId, flags);
19435
19436         } catch (Exception e) {
19437             logCriticalInfo(Log.WARN,
19438                     "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19439         }
19440     }
19441
19442     /**
19443      * Examine all users present on given mounted volume, and destroy data
19444      * belonging to users that are no longer valid, or whose user ID has been
19445      * recycled.
19446      */
19447     private void reconcileUsers(String volumeUuid) {
19448         final List<File> files = new ArrayList<>();
19449         Collections.addAll(files, FileUtils
19450                 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19451         Collections.addAll(files, FileUtils
19452                 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19453         Collections.addAll(files, FileUtils
19454                 .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19455         Collections.addAll(files, FileUtils
19456                 .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19457         for (File file : files) {
19458             if (!file.isDirectory()) continue;
19459
19460             final int userId;
19461             final UserInfo info;
19462             try {
19463                 userId = Integer.parseInt(file.getName());
19464                 info = sUserManager.getUserInfo(userId);
19465             } catch (NumberFormatException e) {
19466                 Slog.w(TAG, "Invalid user directory " + file);
19467                 continue;
19468             }
19469
19470             boolean destroyUser = false;
19471             if (info == null) {
19472                 logCriticalInfo(Log.WARN, "Destroying user directory " + file
19473                         + " because no matching user was found");
19474                 destroyUser = true;
19475             } else if (!mOnlyCore) {
19476                 try {
19477                     UserManagerService.enforceSerialNumber(file, info.serialNumber);
19478                 } catch (IOException e) {
19479                     logCriticalInfo(Log.WARN, "Destroying user directory " + file
19480                             + " because we failed to enforce serial number: " + e);
19481                     destroyUser = true;
19482                 }
19483             }
19484
19485             if (destroyUser) {
19486                 synchronized (mInstallLock) {
19487                     destroyUserDataLI(volumeUuid, userId,
19488                             StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19489                 }
19490             }
19491         }
19492     }
19493
19494     private void assertPackageKnown(String volumeUuid, String packageName)
19495             throws PackageManagerException {
19496         synchronized (mPackages) {
19497             final PackageSetting ps = mSettings.mPackages.get(packageName);
19498             if (ps == null) {
19499                 throw new PackageManagerException("Package " + packageName + " is unknown");
19500             } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19501                 throw new PackageManagerException(
19502                         "Package " + packageName + " found on unknown volume " + volumeUuid
19503                                 + "; expected volume " + ps.volumeUuid);
19504             }
19505         }
19506     }
19507
19508     private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19509             throws PackageManagerException {
19510         synchronized (mPackages) {
19511             final PackageSetting ps = mSettings.mPackages.get(packageName);
19512             if (ps == null) {
19513                 throw new PackageManagerException("Package " + packageName + " is unknown");
19514             } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19515                 throw new PackageManagerException(
19516                         "Package " + packageName + " found on unknown volume " + volumeUuid
19517                                 + "; expected volume " + ps.volumeUuid);
19518             } else if (!ps.getInstalled(userId)) {
19519                 throw new PackageManagerException(
19520                         "Package " + packageName + " not installed for user " + userId);
19521             }
19522         }
19523     }
19524
19525     /**
19526      * Examine all apps present on given mounted volume, and destroy apps that
19527      * aren't expected, either due to uninstallation or reinstallation on
19528      * another volume.
19529      */
19530     private void reconcileApps(String volumeUuid) {
19531         final File[] files = FileUtils
19532                 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19533         for (File file : files) {
19534             final boolean isPackage = (isApkFile(file) || file.isDirectory())
19535                     && !PackageInstallerService.isStageName(file.getName());
19536             if (!isPackage) {
19537                 // Ignore entries which are not packages
19538                 continue;
19539             }
19540
19541             try {
19542                 final PackageLite pkg = PackageParser.parsePackageLite(file,
19543                         PackageParser.PARSE_MUST_BE_APK);
19544                 assertPackageKnown(volumeUuid, pkg.packageName);
19545
19546             } catch (PackageParserException | PackageManagerException e) {
19547                 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19548                 synchronized (mInstallLock) {
19549                     removeCodePathLI(file);
19550                 }
19551             }
19552         }
19553     }
19554
19555     /**
19556      * Reconcile all app data for the given user.
19557      * <p>
19558      * Verifies that directories exist and that ownership and labeling is
19559      * correct for all installed apps on all mounted volumes.
19560      */
19561     void reconcileAppsData(int userId, int flags) {
19562         final StorageManager storage = mContext.getSystemService(StorageManager.class);
19563         for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19564             final String volumeUuid = vol.getFsUuid();
19565             synchronized (mInstallLock) {
19566                 reconcileAppsDataLI(volumeUuid, userId, flags);
19567             }
19568         }
19569     }
19570
19571     /**
19572      * Reconcile all app data on given mounted volume.
19573      * <p>
19574      * Destroys app data that isn't expected, either due to uninstallation or
19575      * reinstallation on another volume.
19576      * <p>
19577      * Verifies that directories exist and that ownership and labeling is
19578      * correct for all installed apps.
19579      */
19580     private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19581         Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19582                 + Integer.toHexString(flags));
19583
19584         final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19585         final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19586
19587         boolean restoreconNeeded = false;
19588
19589         // First look for stale data that doesn't belong, and check if things
19590         // have changed since we did our last restorecon
19591         if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19592             if (StorageManager.isFileEncryptedNativeOrEmulated()
19593                     && !StorageManager.isUserKeyUnlocked(userId)) {
19594                 throw new RuntimeException(
19595                         "Yikes, someone asked us to reconcile CE storage while " + userId
19596                                 + " was still locked; this would have caused massive data loss!");
19597             }
19598
19599             restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19600
19601             final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19602             for (File file : files) {
19603                 final String packageName = file.getName();
19604                 try {
19605                     assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19606                 } catch (PackageManagerException e) {
19607                     logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19608                     try {
19609                         mInstaller.destroyAppData(volumeUuid, packageName, userId,
19610                                 StorageManager.FLAG_STORAGE_CE, 0);
19611                     } catch (InstallerException e2) {
19612                         logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19613                     }
19614                 }
19615             }
19616         }
19617         if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19618             restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19619
19620             final File[] files = FileUtils.listFilesOrEmpty(deDir);
19621             for (File file : files) {
19622                 final String packageName = file.getName();
19623                 try {
19624                     assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19625                 } catch (PackageManagerException e) {
19626                     logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19627                     try {
19628                         mInstaller.destroyAppData(volumeUuid, packageName, userId,
19629                                 StorageManager.FLAG_STORAGE_DE, 0);
19630                     } catch (InstallerException e2) {
19631                         logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19632                     }
19633                 }
19634             }
19635         }
19636
19637         // Ensure that data directories are ready to roll for all packages
19638         // installed for this volume and user
19639         final List<PackageSetting> packages;
19640         synchronized (mPackages) {
19641             packages = mSettings.getVolumePackagesLPr(volumeUuid);
19642         }
19643         int preparedCount = 0;
19644         for (PackageSetting ps : packages) {
19645             final String packageName = ps.name;
19646             if (ps.pkg == null) {
19647                 Slog.w(TAG, "Odd, missing scanned package " + packageName);
19648                 // TODO: might be due to legacy ASEC apps; we should circle back
19649                 // and reconcile again once they're scanned
19650                 continue;
19651             }
19652
19653             if (ps.getInstalled(userId)) {
19654                 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19655
19656                 if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19657                     // We may have just shuffled around app data directories, so
19658                     // prepare them one more time
19659                     prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19660                 }
19661
19662                 preparedCount++;
19663             }
19664         }
19665
19666         if (restoreconNeeded) {
19667             if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19668                 SELinuxMMAC.setRestoreconDone(ceDir);
19669             }
19670             if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19671                 SELinuxMMAC.setRestoreconDone(deDir);
19672             }
19673         }
19674
19675         Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19676                 + " packages; restoreconNeeded was " + restoreconNeeded);
19677     }
19678
19679     /**
19680      * Prepare app data for the given app just after it was installed or
19681      * upgraded. This method carefully only touches users that it's installed
19682      * for, and it forces a restorecon to handle any seinfo changes.
19683      * <p>
19684      * Verifies that directories exist and that ownership and labeling is
19685      * correct for all installed apps. If there is an ownership mismatch, it
19686      * will try recovering system apps by wiping data; third-party app data is
19687      * left intact.
19688      * <p>
19689      * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19690      */
19691     private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19692         final PackageSetting ps;
19693         synchronized (mPackages) {
19694             ps = mSettings.mPackages.get(pkg.packageName);
19695             mSettings.writeKernelMappingLPr(ps);
19696         }
19697
19698         final UserManager um = mContext.getSystemService(UserManager.class);
19699         UserManagerInternal umInternal = getUserManagerInternal();
19700         for (UserInfo user : um.getUsers()) {
19701             final int flags;
19702             if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19703                 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19704             } else if (umInternal.isUserRunning(user.id)) {
19705                 flags = StorageManager.FLAG_STORAGE_DE;
19706             } else {
19707                 continue;
19708             }
19709
19710             if (ps.getInstalled(user.id)) {
19711                 // Whenever an app changes, force a restorecon of its data
19712                 // TODO: when user data is locked, mark that we're still dirty
19713                 prepareAppDataLIF(pkg, user.id, flags, true);
19714             }
19715         }
19716     }
19717
19718     /**
19719      * Prepare app data for the given app.
19720      * <p>
19721      * Verifies that directories exist and that ownership and labeling is
19722      * correct for all installed apps. If there is an ownership mismatch, this
19723      * will try recovering system apps by wiping data; third-party app data is
19724      * left intact.
19725      */
19726     private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19727             boolean restoreconNeeded) {
19728         if (pkg == null) {
19729             Slog.wtf(TAG, "Package was null!", new Throwable());
19730             return;
19731         }
19732         prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19733         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19734         for (int i = 0; i < childCount; i++) {
19735             prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19736         }
19737     }
19738
19739     private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19740             boolean restoreconNeeded) {
19741         if (DEBUG_APP_DATA) {
19742             Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19743                     + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19744         }
19745
19746         final String volumeUuid = pkg.volumeUuid;
19747         final String packageName = pkg.packageName;
19748         final ApplicationInfo app = pkg.applicationInfo;
19749         final int appId = UserHandle.getAppId(app.uid);
19750
19751         Preconditions.checkNotNull(app.seinfo);
19752
19753         try {
19754             mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19755                     appId, app.seinfo, app.targetSdkVersion);
19756         } catch (InstallerException e) {
19757             if (app.isSystemApp()) {
19758                 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19759                         + ", but trying to recover: " + e);
19760                 destroyAppDataLeafLIF(pkg, userId, flags);
19761                 try {
19762                     mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19763                             appId, app.seinfo, app.targetSdkVersion);
19764                     logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19765                 } catch (InstallerException e2) {
19766                     logCriticalInfo(Log.DEBUG, "Recovery failed!");
19767                 }
19768             } else {
19769                 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19770             }
19771         }
19772
19773         if (restoreconNeeded) {
19774             try {
19775                 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19776                         app.seinfo);
19777             } catch (InstallerException e) {
19778                 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19779             }
19780         }
19781
19782         if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19783             try {
19784                 // CE storage is unlocked right now, so read out the inode and
19785                 // remember for use later when it's locked
19786                 // TODO: mark this structure as dirty so we persist it!
19787                 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19788                         StorageManager.FLAG_STORAGE_CE);
19789                 synchronized (mPackages) {
19790                     final PackageSetting ps = mSettings.mPackages.get(packageName);
19791                     if (ps != null) {
19792                         ps.setCeDataInode(ceDataInode, userId);
19793                     }
19794                 }
19795             } catch (InstallerException e) {
19796                 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19797             }
19798         }
19799
19800         prepareAppDataContentsLeafLIF(pkg, userId, flags);
19801     }
19802
19803     private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19804         if (pkg == null) {
19805             Slog.wtf(TAG, "Package was null!", new Throwable());
19806             return;
19807         }
19808         prepareAppDataContentsLeafLIF(pkg, userId, flags);
19809         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19810         for (int i = 0; i < childCount; i++) {
19811             prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19812         }
19813     }
19814
19815     private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19816         final String volumeUuid = pkg.volumeUuid;
19817         final String packageName = pkg.packageName;
19818         final ApplicationInfo app = pkg.applicationInfo;
19819
19820         if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19821             // Create a native library symlink only if we have native libraries
19822             // and if the native libraries are 32 bit libraries. We do not provide
19823             // this symlink for 64 bit libraries.
19824             if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19825                 final String nativeLibPath = app.nativeLibraryDir;
19826                 try {
19827                     mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19828                             nativeLibPath, userId);
19829                 } catch (InstallerException e) {
19830                     Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19831                 }
19832             }
19833         }
19834     }
19835
19836     /**
19837      * For system apps on non-FBE devices, this method migrates any existing
19838      * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19839      * requested by the app.
19840      */
19841     private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19842         if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19843                 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19844             final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19845                     ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19846             try {
19847                 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19848                         storageTarget);
19849             } catch (InstallerException e) {
19850                 logCriticalInfo(Log.WARN,
19851                         "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19852             }
19853             return true;
19854         } else {
19855             return false;
19856         }
19857     }
19858
19859     public PackageFreezer freezePackage(String packageName, String killReason) {
19860         return freezePackage(packageName, UserHandle.USER_ALL, killReason);
19861     }
19862
19863     public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
19864         return new PackageFreezer(packageName, userId, killReason);
19865     }
19866
19867     public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19868             String killReason) {
19869         return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
19870     }
19871
19872     public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
19873             String killReason) {
19874         if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19875             return new PackageFreezer();
19876         } else {
19877             return freezePackage(packageName, userId, killReason);
19878         }
19879     }
19880
19881     public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19882             String killReason) {
19883         return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
19884     }
19885
19886     public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
19887             String killReason) {
19888         if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19889             return new PackageFreezer();
19890         } else {
19891             return freezePackage(packageName, userId, killReason);
19892         }
19893     }
19894
19895     /**
19896      * Class that freezes and kills the given package upon creation, and
19897      * unfreezes it upon closing. This is typically used when doing surgery on
19898      * app code/data to prevent the app from running while you're working.
19899      */
19900     private class PackageFreezer implements AutoCloseable {
19901         private final String mPackageName;
19902         private final PackageFreezer[] mChildren;
19903
19904         private final boolean mWeFroze;
19905
19906         private final AtomicBoolean mClosed = new AtomicBoolean();
19907         private final CloseGuard mCloseGuard = CloseGuard.get();
19908
19909         /**
19910          * Create and return a stub freezer that doesn't actually do anything,
19911          * typically used when someone requested
19912          * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19913          * {@link PackageManager#DELETE_DONT_KILL_APP}.
19914          */
19915         public PackageFreezer() {
19916             mPackageName = null;
19917             mChildren = null;
19918             mWeFroze = false;
19919             mCloseGuard.open("close");
19920         }
19921
19922         public PackageFreezer(String packageName, int userId, String killReason) {
19923             synchronized (mPackages) {
19924                 mPackageName = packageName;
19925                 mWeFroze = mFrozenPackages.add(mPackageName);
19926
19927                 final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19928                 if (ps != null) {
19929                     killApplication(ps.name, ps.appId, userId, killReason);
19930                 }
19931
19932                 final PackageParser.Package p = mPackages.get(packageName);
19933                 if (p != null && p.childPackages != null) {
19934                     final int N = p.childPackages.size();
19935                     mChildren = new PackageFreezer[N];
19936                     for (int i = 0; i < N; i++) {
19937                         mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19938                                 userId, killReason);
19939                     }
19940                 } else {
19941                     mChildren = null;
19942                 }
19943             }
19944             mCloseGuard.open("close");
19945         }
19946
19947         @Override
19948         protected void finalize() throws Throwable {
19949             try {
19950                 mCloseGuard.warnIfOpen();
19951                 close();
19952             } finally {
19953                 super.finalize();
19954             }
19955         }
19956
19957         @Override
19958         public void close() {
19959             mCloseGuard.close();
19960             if (mClosed.compareAndSet(false, true)) {
19961                 synchronized (mPackages) {
19962                     if (mWeFroze) {
19963                         mFrozenPackages.remove(mPackageName);
19964                     }
19965
19966                     if (mChildren != null) {
19967                         for (PackageFreezer freezer : mChildren) {
19968                             freezer.close();
19969                         }
19970                     }
19971                 }
19972             }
19973         }
19974     }
19975
19976     /**
19977      * Verify that given package is currently frozen.
19978      */
19979     private void checkPackageFrozen(String packageName) {
19980         synchronized (mPackages) {
19981             if (!mFrozenPackages.contains(packageName)) {
19982                 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19983             }
19984         }
19985     }
19986
19987     @Override
19988     public int movePackage(final String packageName, final String volumeUuid) {
19989         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19990
19991         final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19992         final int moveId = mNextMoveId.getAndIncrement();
19993         mHandler.post(new Runnable() {
19994             @Override
19995             public void run() {
19996                 try {
19997                     movePackageInternal(packageName, volumeUuid, moveId, user);
19998                 } catch (PackageManagerException e) {
19999                     Slog.w(TAG, "Failed to move " + packageName, e);
20000                     mMoveCallbacks.notifyStatusChanged(moveId,
20001                             PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20002                 }
20003             }
20004         });
20005         return moveId;
20006     }
20007
20008     private void movePackageInternal(final String packageName, final String volumeUuid,
20009             final int moveId, UserHandle user) throws PackageManagerException {
20010         final StorageManager storage = mContext.getSystemService(StorageManager.class);
20011         final PackageManager pm = mContext.getPackageManager();
20012
20013         final boolean currentAsec;
20014         final String currentVolumeUuid;
20015         final File codeFile;
20016         final String installerPackageName;
20017         final String packageAbiOverride;
20018         final int appId;
20019         final String seinfo;
20020         final String label;
20021         final int targetSdkVersion;
20022         final PackageFreezer freezer;
20023         final int[] installedUserIds;
20024
20025         // reader
20026         synchronized (mPackages) {
20027             final PackageParser.Package pkg = mPackages.get(packageName);
20028             final PackageSetting ps = mSettings.mPackages.get(packageName);
20029             if (pkg == null || ps == null) {
20030                 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20031             }
20032
20033             if (pkg.applicationInfo.isSystemApp()) {
20034                 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20035                         "Cannot move system application");
20036             }
20037
20038             if (pkg.applicationInfo.isExternalAsec()) {
20039                 currentAsec = true;
20040                 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20041             } else if (pkg.applicationInfo.isForwardLocked()) {
20042                 currentAsec = true;
20043                 currentVolumeUuid = "forward_locked";
20044             } else {
20045                 currentAsec = false;
20046                 currentVolumeUuid = ps.volumeUuid;
20047
20048                 final File probe = new File(pkg.codePath);
20049                 final File probeOat = new File(probe, "oat");
20050                 if (!probe.isDirectory() || !probeOat.isDirectory()) {
20051                     throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20052                             "Move only supported for modern cluster style installs");
20053                 }
20054             }
20055
20056             if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20057                 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20058                         "Package already moved to " + volumeUuid);
20059             }
20060             if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20061                 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20062                         "Device admin cannot be moved");
20063             }
20064
20065             if (mFrozenPackages.contains(packageName)) {
20066                 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20067                         "Failed to move already frozen package");
20068             }
20069
20070             codeFile = new File(pkg.codePath);
20071             installerPackageName = ps.installerPackageName;
20072             packageAbiOverride = ps.cpuAbiOverrideString;
20073             appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20074             seinfo = pkg.applicationInfo.seinfo;
20075             label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20076             targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20077             freezer = freezePackage(packageName, "movePackageInternal");
20078             installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20079         }
20080
20081         final Bundle extras = new Bundle();
20082         extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20083         extras.putString(Intent.EXTRA_TITLE, label);
20084         mMoveCallbacks.notifyCreated(moveId, extras);
20085
20086         int installFlags;
20087         final boolean moveCompleteApp;
20088         final File measurePath;
20089
20090         if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20091             installFlags = INSTALL_INTERNAL;
20092             moveCompleteApp = !currentAsec;
20093             measurePath = Environment.getDataAppDirectory(volumeUuid);
20094         } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20095             installFlags = INSTALL_EXTERNAL;
20096             moveCompleteApp = false;
20097             measurePath = storage.getPrimaryPhysicalVolume().getPath();
20098         } else {
20099             final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20100             if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20101                     || !volume.isMountedWritable()) {
20102                 freezer.close();
20103                 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20104                         "Move location not mounted private volume");
20105             }
20106
20107             Preconditions.checkState(!currentAsec);
20108
20109             installFlags = INSTALL_INTERNAL;
20110             moveCompleteApp = true;
20111             measurePath = Environment.getDataAppDirectory(volumeUuid);
20112         }
20113
20114         final PackageStats stats = new PackageStats(null, -1);
20115         synchronized (mInstaller) {
20116             for (int userId : installedUserIds) {
20117                 if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20118                     freezer.close();
20119                     throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20120                             "Failed to measure package size");
20121                 }
20122             }
20123         }
20124
20125         if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20126                 + stats.dataSize);
20127
20128         final long startFreeBytes = measurePath.getFreeSpace();
20129         final long sizeBytes;
20130         if (moveCompleteApp) {
20131             sizeBytes = stats.codeSize + stats.dataSize;
20132         } else {
20133             sizeBytes = stats.codeSize;
20134         }
20135
20136         if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20137             freezer.close();
20138             throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20139                     "Not enough free space to move");
20140         }
20141
20142         mMoveCallbacks.notifyStatusChanged(moveId, 10);
20143
20144         final CountDownLatch installedLatch = new CountDownLatch(1);
20145         final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20146             @Override
20147             public void onUserActionRequired(Intent intent) throws RemoteException {
20148                 throw new IllegalStateException();
20149             }
20150
20151             @Override
20152             public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20153                     Bundle extras) throws RemoteException {
20154                 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20155                         + PackageManager.installStatusToString(returnCode, msg));
20156
20157                 installedLatch.countDown();
20158                 freezer.close();
20159
20160                 final int status = PackageManager.installStatusToPublicStatus(returnCode);
20161                 switch (status) {
20162                     case PackageInstaller.STATUS_SUCCESS:
20163                         mMoveCallbacks.notifyStatusChanged(moveId,
20164                                 PackageManager.MOVE_SUCCEEDED);
20165                         break;
20166                     case PackageInstaller.STATUS_FAILURE_STORAGE:
20167                         mMoveCallbacks.notifyStatusChanged(moveId,
20168                                 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20169                         break;
20170                     default:
20171                         mMoveCallbacks.notifyStatusChanged(moveId,
20172                                 PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20173                         break;
20174                 }
20175             }
20176         };
20177
20178         final MoveInfo move;
20179         if (moveCompleteApp) {
20180             // Kick off a thread to report progress estimates
20181             new Thread() {
20182                 @Override
20183                 public void run() {
20184                     while (true) {
20185                         try {
20186                             if (installedLatch.await(1, TimeUnit.SECONDS)) {
20187                                 break;
20188                             }
20189                         } catch (InterruptedException ignored) {
20190                         }
20191
20192                         final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20193                         final int progress = 10 + (int) MathUtils.constrain(
20194                                 ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20195                         mMoveCallbacks.notifyStatusChanged(moveId, progress);
20196                     }
20197                 }
20198             }.start();
20199
20200             final String dataAppName = codeFile.getName();
20201             move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20202                     dataAppName, appId, seinfo, targetSdkVersion);
20203         } else {
20204             move = null;
20205         }
20206
20207         installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20208
20209         final Message msg = mHandler.obtainMessage(INIT_COPY);
20210         final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20211         final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20212                 installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20213                 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20214         params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20215         msg.obj = params;
20216
20217         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20218                 System.identityHashCode(msg.obj));
20219         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20220                 System.identityHashCode(msg.obj));
20221
20222         mHandler.sendMessage(msg);
20223     }
20224
20225     @Override
20226     public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20227         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20228
20229         final int realMoveId = mNextMoveId.getAndIncrement();
20230         final Bundle extras = new Bundle();
20231         extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20232         mMoveCallbacks.notifyCreated(realMoveId, extras);
20233
20234         final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20235             @Override
20236             public void onCreated(int moveId, Bundle extras) {
20237                 // Ignored
20238             }
20239
20240             @Override
20241             public void onStatusChanged(int moveId, int status, long estMillis) {
20242                 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20243             }
20244         };
20245
20246         final StorageManager storage = mContext.getSystemService(StorageManager.class);
20247         storage.setPrimaryStorageUuid(volumeUuid, callback);
20248         return realMoveId;
20249     }
20250
20251     @Override
20252     public int getMoveStatus(int moveId) {
20253         mContext.enforceCallingOrSelfPermission(
20254                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20255         return mMoveCallbacks.mLastStatus.get(moveId);
20256     }
20257
20258     @Override
20259     public void registerMoveCallback(IPackageMoveObserver callback) {
20260         mContext.enforceCallingOrSelfPermission(
20261                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20262         mMoveCallbacks.register(callback);
20263     }
20264
20265     @Override
20266     public void unregisterMoveCallback(IPackageMoveObserver callback) {
20267         mContext.enforceCallingOrSelfPermission(
20268                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20269         mMoveCallbacks.unregister(callback);
20270     }
20271
20272     @Override
20273     public boolean setInstallLocation(int loc) {
20274         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20275                 null);
20276         if (getInstallLocation() == loc) {
20277             return true;
20278         }
20279         if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20280                 || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20281             android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20282                     android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20283             return true;
20284         }
20285         return false;
20286    }
20287
20288     @Override
20289     public int getInstallLocation() {
20290         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20291                 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20292                 PackageHelper.APP_INSTALL_AUTO);
20293     }
20294
20295     /** Called by UserManagerService */
20296     void cleanUpUser(UserManagerService userManager, int userHandle) {
20297         synchronized (mPackages) {
20298             mDirtyUsers.remove(userHandle);
20299             mUserNeedsBadging.delete(userHandle);
20300             mSettings.removeUserLPw(userHandle);
20301             mPendingBroadcasts.remove(userHandle);
20302             mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20303             removeUnusedPackagesLPw(userManager, userHandle);
20304         }
20305     }
20306
20307     /**
20308      * We're removing userHandle and would like to remove any downloaded packages
20309      * that are no longer in use by any other user.
20310      * @param userHandle the user being removed
20311      */
20312     private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20313         final boolean DEBUG_CLEAN_APKS = false;
20314         int [] users = userManager.getUserIds();
20315         Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20316         while (psit.hasNext()) {
20317             PackageSetting ps = psit.next();
20318             if (ps.pkg == null) {
20319                 continue;
20320             }
20321             final String packageName = ps.pkg.packageName;
20322             // Skip over if system app
20323             if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20324                 continue;
20325             }
20326             if (DEBUG_CLEAN_APKS) {
20327                 Slog.i(TAG, "Checking package " + packageName);
20328             }
20329             boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20330             if (keep) {
20331                 if (DEBUG_CLEAN_APKS) {
20332                     Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20333                 }
20334             } else {
20335                 for (int i = 0; i < users.length; i++) {
20336                     if (users[i] != userHandle && ps.getInstalled(users[i])) {
20337                         keep = true;
20338                         if (DEBUG_CLEAN_APKS) {
20339                             Slog.i(TAG, "  Keeping package " + packageName + " for user "
20340                                     + users[i]);
20341                         }
20342                         break;
20343                     }
20344                 }
20345             }
20346             if (!keep) {
20347                 if (DEBUG_CLEAN_APKS) {
20348                     Slog.i(TAG, "  Removing package " + packageName);
20349                 }
20350                 mHandler.post(new Runnable() {
20351                     public void run() {
20352                         deletePackageX(packageName, userHandle, 0);
20353                     } //end run
20354                 });
20355             }
20356         }
20357     }
20358
20359     /** Called by UserManagerService */
20360     void createNewUser(int userId) {
20361         synchronized (mInstallLock) {
20362             mSettings.createNewUserLI(this, mInstaller, userId);
20363         }
20364         synchronized (mPackages) {
20365             scheduleWritePackageRestrictionsLocked(userId);
20366             scheduleWritePackageListLocked(userId);
20367             applyFactoryDefaultBrowserLPw(userId);
20368             primeDomainVerificationsLPw(userId);
20369         }
20370     }
20371
20372     void onBeforeUserStartUninitialized(final int userId) {
20373         synchronized (mPackages) {
20374             if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20375                 return;
20376             }
20377         }
20378         mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20379         // If permission review for legacy apps is required, we represent
20380         // dagerous permissions for such apps as always granted runtime
20381         // permissions to keep per user flag state whether review is needed.
20382         // Hence, if a new user is added we have to propagate dangerous
20383         // permission grants for these legacy apps.
20384         if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20385             updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20386                     | UPDATE_PERMISSIONS_REPLACE_ALL);
20387         }
20388     }
20389
20390     @Override
20391     public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20392         mContext.enforceCallingOrSelfPermission(
20393                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20394                 "Only package verification agents can read the verifier device identity");
20395
20396         synchronized (mPackages) {
20397             return mSettings.getVerifierDeviceIdentityLPw();
20398         }
20399     }
20400
20401     @Override
20402     public void setPermissionEnforced(String permission, boolean enforced) {
20403         // TODO: Now that we no longer change GID for storage, this should to away.
20404         mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20405                 "setPermissionEnforced");
20406         if (READ_EXTERNAL_STORAGE.equals(permission)) {
20407             synchronized (mPackages) {
20408                 if (mSettings.mReadExternalStorageEnforced == null
20409                         || mSettings.mReadExternalStorageEnforced != enforced) {
20410                     mSettings.mReadExternalStorageEnforced = enforced;
20411                     mSettings.writeLPr();
20412                 }
20413             }
20414             // kill any non-foreground processes so we restart them and
20415             // grant/revoke the GID.
20416             final IActivityManager am = ActivityManagerNative.getDefault();
20417             if (am != null) {
20418                 final long token = Binder.clearCallingIdentity();
20419                 try {
20420                     am.killProcessesBelowForeground("setPermissionEnforcement");
20421                 } catch (RemoteException e) {
20422                 } finally {
20423                     Binder.restoreCallingIdentity(token);
20424                 }
20425             }
20426         } else {
20427             throw new IllegalArgumentException("No selective enforcement for " + permission);
20428         }
20429     }
20430
20431     @Override
20432     @Deprecated
20433     public boolean isPermissionEnforced(String permission) {
20434         return true;
20435     }
20436
20437     @Override
20438     public boolean isStorageLow() {
20439         final long token = Binder.clearCallingIdentity();
20440         try {
20441             final DeviceStorageMonitorInternal
20442                     dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20443             if (dsm != null) {
20444                 return dsm.isMemoryLow();
20445             } else {
20446                 return false;
20447             }
20448         } finally {
20449             Binder.restoreCallingIdentity(token);
20450         }
20451     }
20452
20453     @Override
20454     public IPackageInstaller getPackageInstaller() {
20455         return mInstallerService;
20456     }
20457
20458     private boolean userNeedsBadging(int userId) {
20459         int index = mUserNeedsBadging.indexOfKey(userId);
20460         if (index < 0) {
20461             final UserInfo userInfo;
20462             final long token = Binder.clearCallingIdentity();
20463             try {
20464                 userInfo = sUserManager.getUserInfo(userId);
20465             } finally {
20466                 Binder.restoreCallingIdentity(token);
20467             }
20468             final boolean b;
20469             if (userInfo != null && userInfo.isManagedProfile()) {
20470                 b = true;
20471             } else {
20472                 b = false;
20473             }
20474             mUserNeedsBadging.put(userId, b);
20475             return b;
20476         }
20477         return mUserNeedsBadging.valueAt(index);
20478     }
20479
20480     @Override
20481     public KeySet getKeySetByAlias(String packageName, String alias) {
20482         if (packageName == null || alias == null) {
20483             return null;
20484         }
20485         synchronized(mPackages) {
20486             final PackageParser.Package pkg = mPackages.get(packageName);
20487             if (pkg == null) {
20488                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20489                 throw new IllegalArgumentException("Unknown package: " + packageName);
20490             }
20491             KeySetManagerService ksms = mSettings.mKeySetManagerService;
20492             return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20493         }
20494     }
20495
20496     @Override
20497     public KeySet getSigningKeySet(String packageName) {
20498         if (packageName == null) {
20499             return null;
20500         }
20501         synchronized(mPackages) {
20502             final PackageParser.Package pkg = mPackages.get(packageName);
20503             if (pkg == null) {
20504                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20505                 throw new IllegalArgumentException("Unknown package: " + packageName);
20506             }
20507             if (pkg.applicationInfo.uid != Binder.getCallingUid()
20508                     && Process.SYSTEM_UID != Binder.getCallingUid()) {
20509                 throw new SecurityException("May not access signing KeySet of other apps.");
20510             }
20511             KeySetManagerService ksms = mSettings.mKeySetManagerService;
20512             return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20513         }
20514     }
20515
20516     @Override
20517     public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20518         if (packageName == null || ks == null) {
20519             return false;
20520         }
20521         synchronized(mPackages) {
20522             final PackageParser.Package pkg = mPackages.get(packageName);
20523             if (pkg == null) {
20524                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20525                 throw new IllegalArgumentException("Unknown package: " + packageName);
20526             }
20527             IBinder ksh = ks.getToken();
20528             if (ksh instanceof KeySetHandle) {
20529                 KeySetManagerService ksms = mSettings.mKeySetManagerService;
20530                 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20531             }
20532             return false;
20533         }
20534     }
20535
20536     @Override
20537     public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20538         if (packageName == null || ks == null) {
20539             return false;
20540         }
20541         synchronized(mPackages) {
20542             final PackageParser.Package pkg = mPackages.get(packageName);
20543             if (pkg == null) {
20544                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20545                 throw new IllegalArgumentException("Unknown package: " + packageName);
20546             }
20547             IBinder ksh = ks.getToken();
20548             if (ksh instanceof KeySetHandle) {
20549                 KeySetManagerService ksms = mSettings.mKeySetManagerService;
20550                 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20551             }
20552             return false;
20553         }
20554     }
20555
20556     private void deletePackageIfUnusedLPr(final String packageName) {
20557         PackageSetting ps = mSettings.mPackages.get(packageName);
20558         if (ps == null) {
20559             return;
20560         }
20561         if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20562             // TODO Implement atomic delete if package is unused
20563             // It is currently possible that the package will be deleted even if it is installed
20564             // after this method returns.
20565             mHandler.post(new Runnable() {
20566                 public void run() {
20567                     deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20568                 }
20569             });
20570         }
20571     }
20572
20573     /**
20574      * Check and throw if the given before/after packages would be considered a
20575      * downgrade.
20576      */
20577     private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20578             throws PackageManagerException {
20579         if (after.versionCode < before.mVersionCode) {
20580             throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20581                     "Update version code " + after.versionCode + " is older than current "
20582                     + before.mVersionCode);
20583         } else if (after.versionCode == before.mVersionCode) {
20584             if (after.baseRevisionCode < before.baseRevisionCode) {
20585                 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20586                         "Update base revision code " + after.baseRevisionCode
20587                         + " is older than current " + before.baseRevisionCode);
20588             }
20589
20590             if (!ArrayUtils.isEmpty(after.splitNames)) {
20591                 for (int i = 0; i < after.splitNames.length; i++) {
20592                     final String splitName = after.splitNames[i];
20593                     final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20594                     if (j != -1) {
20595                         if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20596                             throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20597                                     "Update split " + splitName + " revision code "
20598                                     + after.splitRevisionCodes[i] + " is older than current "
20599                                     + before.splitRevisionCodes[j]);
20600                         }
20601                     }
20602                 }
20603             }
20604         }
20605     }
20606
20607     private static class MoveCallbacks extends Handler {
20608         private static final int MSG_CREATED = 1;
20609         private static final int MSG_STATUS_CHANGED = 2;
20610
20611         private final RemoteCallbackList<IPackageMoveObserver>
20612                 mCallbacks = new RemoteCallbackList<>();
20613
20614         private final SparseIntArray mLastStatus = new SparseIntArray();
20615
20616         public MoveCallbacks(Looper looper) {
20617             super(looper);
20618         }
20619
20620         public void register(IPackageMoveObserver callback) {
20621             mCallbacks.register(callback);
20622         }
20623
20624         public void unregister(IPackageMoveObserver callback) {
20625             mCallbacks.unregister(callback);
20626         }
20627
20628         @Override
20629         public void handleMessage(Message msg) {
20630             final SomeArgs args = (SomeArgs) msg.obj;
20631             final int n = mCallbacks.beginBroadcast();
20632             for (int i = 0; i < n; i++) {
20633                 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20634                 try {
20635                     invokeCallback(callback, msg.what, args);
20636                 } catch (RemoteException ignored) {
20637                 }
20638             }
20639             mCallbacks.finishBroadcast();
20640             args.recycle();
20641         }
20642
20643         private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20644                 throws RemoteException {
20645             switch (what) {
20646                 case MSG_CREATED: {
20647                     callback.onCreated(args.argi1, (Bundle) args.arg2);
20648                     break;
20649                 }
20650                 case MSG_STATUS_CHANGED: {
20651                     callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20652                     break;
20653                 }
20654             }
20655         }
20656
20657         private void notifyCreated(int moveId, Bundle extras) {
20658             Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20659
20660             final SomeArgs args = SomeArgs.obtain();
20661             args.argi1 = moveId;
20662             args.arg2 = extras;
20663             obtainMessage(MSG_CREATED, args).sendToTarget();
20664         }
20665
20666         private void notifyStatusChanged(int moveId, int status) {
20667             notifyStatusChanged(moveId, status, -1);
20668         }
20669
20670         private void notifyStatusChanged(int moveId, int status, long estMillis) {
20671             Slog.v(TAG, "Move " + moveId + " status " + status);
20672
20673             final SomeArgs args = SomeArgs.obtain();
20674             args.argi1 = moveId;
20675             args.argi2 = status;
20676             args.arg3 = estMillis;
20677             obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20678
20679             synchronized (mLastStatus) {
20680                 mLastStatus.put(moveId, status);
20681             }
20682         }
20683     }
20684
20685     private final static class OnPermissionChangeListeners extends Handler {
20686         private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20687
20688         private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20689                 new RemoteCallbackList<>();
20690
20691         public OnPermissionChangeListeners(Looper looper) {
20692             super(looper);
20693         }
20694
20695         @Override
20696         public void handleMessage(Message msg) {
20697             switch (msg.what) {
20698                 case MSG_ON_PERMISSIONS_CHANGED: {
20699                     final int uid = msg.arg1;
20700                     handleOnPermissionsChanged(uid);
20701                 } break;
20702             }
20703         }
20704
20705         public void addListenerLocked(IOnPermissionsChangeListener listener) {
20706             mPermissionListeners.register(listener);
20707
20708         }
20709
20710         public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20711             mPermissionListeners.unregister(listener);
20712         }
20713
20714         public void onPermissionsChanged(int uid) {
20715             if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20716                 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20717             }
20718         }
20719
20720         private void handleOnPermissionsChanged(int uid) {
20721             final int count = mPermissionListeners.beginBroadcast();
20722             try {
20723                 for (int i = 0; i < count; i++) {
20724                     IOnPermissionsChangeListener callback = mPermissionListeners
20725                             .getBroadcastItem(i);
20726                     try {
20727                         callback.onPermissionsChanged(uid);
20728                     } catch (RemoteException e) {
20729                         Log.e(TAG, "Permission listener is dead", e);
20730                     }
20731                 }
20732             } finally {
20733                 mPermissionListeners.finishBroadcast();
20734             }
20735         }
20736     }
20737
20738     private class PackageManagerInternalImpl extends PackageManagerInternal {
20739         @Override
20740         public void setLocationPackagesProvider(PackagesProvider provider) {
20741             synchronized (mPackages) {
20742                 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20743             }
20744         }
20745
20746         @Override
20747         public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20748             synchronized (mPackages) {
20749                 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20750             }
20751         }
20752
20753         @Override
20754         public void setSmsAppPackagesProvider(PackagesProvider provider) {
20755             synchronized (mPackages) {
20756                 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20757             }
20758         }
20759
20760         @Override
20761         public void setDialerAppPackagesProvider(PackagesProvider provider) {
20762             synchronized (mPackages) {
20763                 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20764             }
20765         }
20766
20767         @Override
20768         public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20769             synchronized (mPackages) {
20770                 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20771             }
20772         }
20773
20774         @Override
20775         public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20776             synchronized (mPackages) {
20777                 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20778             }
20779         }
20780
20781         @Override
20782         public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20783             synchronized (mPackages) {
20784                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20785                         packageName, userId);
20786             }
20787         }
20788
20789         @Override
20790         public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20791             synchronized (mPackages) {
20792                 mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20793                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20794                         packageName, userId);
20795             }
20796         }
20797
20798         @Override
20799         public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20800             synchronized (mPackages) {
20801                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20802                         packageName, userId);
20803             }
20804         }
20805
20806         @Override
20807         public void setKeepUninstalledPackages(final List<String> packageList) {
20808             Preconditions.checkNotNull(packageList);
20809             List<String> removedFromList = null;
20810             synchronized (mPackages) {
20811                 if (mKeepUninstalledPackages != null) {
20812                     final int packagesCount = mKeepUninstalledPackages.size();
20813                     for (int i = 0; i < packagesCount; i++) {
20814                         String oldPackage = mKeepUninstalledPackages.get(i);
20815                         if (packageList != null && packageList.contains(oldPackage)) {
20816                             continue;
20817                         }
20818                         if (removedFromList == null) {
20819                             removedFromList = new ArrayList<>();
20820                         }
20821                         removedFromList.add(oldPackage);
20822                     }
20823                 }
20824                 mKeepUninstalledPackages = new ArrayList<>(packageList);
20825                 if (removedFromList != null) {
20826                     final int removedCount = removedFromList.size();
20827                     for (int i = 0; i < removedCount; i++) {
20828                         deletePackageIfUnusedLPr(removedFromList.get(i));
20829                     }
20830                 }
20831             }
20832         }
20833
20834         @Override
20835         public boolean isPermissionsReviewRequired(String packageName, int userId) {
20836             synchronized (mPackages) {
20837                 // If we do not support permission review, done.
20838                 if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20839                     return false;
20840                 }
20841
20842                 PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20843                 if (packageSetting == null) {
20844                     return false;
20845                 }
20846
20847                 // Permission review applies only to apps not supporting the new permission model.
20848                 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20849                     return false;
20850                 }
20851
20852                 // Legacy apps have the permission and get user consent on launch.
20853                 PermissionsState permissionsState = packageSetting.getPermissionsState();
20854                 return permissionsState.isPermissionReviewRequired(userId);
20855             }
20856         }
20857
20858         @Override
20859         public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20860             return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20861         }
20862
20863         @Override
20864         public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20865                 int userId) {
20866             return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20867         }
20868
20869         @Override
20870         public void setDeviceAndProfileOwnerPackages(
20871                 int deviceOwnerUserId, String deviceOwnerPackage,
20872                 SparseArray<String> profileOwnerPackages) {
20873             mProtectedPackages.setDeviceAndProfileOwnerPackages(
20874                     deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
20875         }
20876
20877         @Override
20878         public boolean canPackageBeWiped(int userId, String packageName) {
20879             return mProtectedPackages.canPackageBeWiped(userId,
20880                     packageName);
20881         }
20882     }
20883
20884     @Override
20885     public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20886         enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20887         synchronized (mPackages) {
20888             final long identity = Binder.clearCallingIdentity();
20889             try {
20890                 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20891                         packageNames, userId);
20892             } finally {
20893                 Binder.restoreCallingIdentity(identity);
20894             }
20895         }
20896     }
20897
20898     private static void enforceSystemOrPhoneCaller(String tag) {
20899         int callingUid = Binder.getCallingUid();
20900         if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20901             throw new SecurityException(
20902                     "Cannot call " + tag + " from UID " + callingUid);
20903         }
20904     }
20905
20906     boolean isHistoricalPackageUsageAvailable() {
20907         return mPackageUsage.isHistoricalPackageUsageAvailable();
20908     }
20909
20910     /**
20911      * Return a <b>copy</b> of the collection of packages known to the package manager.
20912      * @return A copy of the values of mPackages.
20913      */
20914     Collection<PackageParser.Package> getPackages() {
20915         synchronized (mPackages) {
20916             return new ArrayList<>(mPackages.values());
20917         }
20918     }
20919
20920     /**
20921      * Logs process start information (including base APK hash) to the security log.
20922      * @hide
20923      */
20924     public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20925             String apkFile, int pid) {
20926         if (!SecurityLog.isLoggingEnabled()) {
20927             return;
20928         }
20929         Bundle data = new Bundle();
20930         data.putLong("startTimestamp", System.currentTimeMillis());
20931         data.putString("processName", processName);
20932         data.putInt("uid", uid);
20933         data.putString("seinfo", seinfo);
20934         data.putString("apkFile", apkFile);
20935         data.putInt("pid", pid);
20936         Message msg = mProcessLoggingHandler.obtainMessage(
20937                 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20938         msg.setData(data);
20939         mProcessLoggingHandler.sendMessage(msg);
20940     }
20941 }