2 * Copyright (C) 2006 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.server.pm;
19 import static android.Manifest.permission.DELETE_PACKAGES;
20 import static android.Manifest.permission.INSTALL_PACKAGES;
21 import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
22 import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
23 import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
24 import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
25 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
26 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
27 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
28 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
29 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
30 import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
31 import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
32 import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
33 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
34 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
35 import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
36 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
37 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
38 import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
39 import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
40 import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
41 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
42 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
43 import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
44 import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
45 import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
46 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
47 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
48 import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
49 import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
50 import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
51 import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
52 import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
53 import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
54 import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
55 import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
56 import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
57 import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
58 import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59 import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60 import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
61 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66 import static android.content.pm.PackageManager.MATCH_ALL;
67 import static android.content.pm.PackageManager.MATCH_ANY_USER;
68 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71 import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72 import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73 import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76 import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77 import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78 import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79 import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80 import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
81 import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
82 import static android.content.pm.PackageManager.PERMISSION_DENIED;
83 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
84 import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
85 import static android.content.pm.PackageParser.isApkFile;
86 import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
87 import static android.system.OsConstants.O_CREAT;
88 import static android.system.OsConstants.O_RDWR;
89 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
90 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
91 import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
92 import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
93 import static com.android.internal.util.ArrayUtils.appendInt;
94 import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
95 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
96 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
97 import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
98 import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
99 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
100 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
101 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
102 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
103 import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
104 import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
106 import android.Manifest;
107 import android.annotation.IntDef;
108 import android.annotation.NonNull;
109 import android.annotation.Nullable;
110 import android.app.ActivityManager;
111 import android.app.AppOpsManager;
112 import android.app.IActivityManager;
113 import android.app.ResourcesManager;
114 import android.app.admin.IDevicePolicyManager;
115 import android.app.admin.SecurityLog;
116 import android.app.backup.IBackupManager;
117 import android.content.BroadcastReceiver;
118 import android.content.ComponentName;
119 import android.content.ContentResolver;
120 import android.content.Context;
121 import android.content.IIntentReceiver;
122 import android.content.Intent;
123 import android.content.IntentFilter;
124 import android.content.IntentSender;
125 import android.content.IntentSender.SendIntentException;
126 import android.content.ServiceConnection;
127 import android.content.pm.ActivityInfo;
128 import android.content.pm.ApplicationInfo;
129 import android.content.pm.AppsQueryHelper;
130 import android.content.pm.AuxiliaryResolveInfo;
131 import android.content.pm.ChangedPackages;
132 import android.content.pm.FallbackCategoryProvider;
133 import android.content.pm.FeatureInfo;
134 import android.content.pm.IOnPermissionsChangeListener;
135 import android.content.pm.IPackageDataObserver;
136 import android.content.pm.IPackageDeleteObserver;
137 import android.content.pm.IPackageDeleteObserver2;
138 import android.content.pm.IPackageInstallObserver2;
139 import android.content.pm.IPackageInstaller;
140 import android.content.pm.IPackageManager;
141 import android.content.pm.IPackageMoveObserver;
142 import android.content.pm.IPackageStatsObserver;
143 import android.content.pm.InstantAppInfo;
144 import android.content.pm.InstantAppRequest;
145 import android.content.pm.InstantAppResolveInfo;
146 import android.content.pm.InstrumentationInfo;
147 import android.content.pm.IntentFilterVerificationInfo;
148 import android.content.pm.KeySet;
149 import android.content.pm.PackageCleanItem;
150 import android.content.pm.PackageInfo;
151 import android.content.pm.PackageInfoLite;
152 import android.content.pm.PackageInstaller;
153 import android.content.pm.PackageManager;
154 import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
155 import android.content.pm.PackageManagerInternal;
156 import android.content.pm.PackageParser;
157 import android.content.pm.PackageParser.ActivityIntentInfo;
158 import android.content.pm.PackageParser.PackageLite;
159 import android.content.pm.PackageParser.PackageParserException;
160 import android.content.pm.PackageStats;
161 import android.content.pm.PackageUserState;
162 import android.content.pm.ParceledListSlice;
163 import android.content.pm.PermissionGroupInfo;
164 import android.content.pm.PermissionInfo;
165 import android.content.pm.ProviderInfo;
166 import android.content.pm.ResolveInfo;
167 import android.content.pm.ServiceInfo;
168 import android.content.pm.SharedLibraryInfo;
169 import android.content.pm.Signature;
170 import android.content.pm.UserInfo;
171 import android.content.pm.VerifierDeviceIdentity;
172 import android.content.pm.VerifierInfo;
173 import android.content.pm.VersionedPackage;
174 import android.content.res.Resources;
175 import android.database.ContentObserver;
176 import android.graphics.Bitmap;
177 import android.hardware.display.DisplayManager;
178 import android.net.Uri;
179 import android.os.Binder;
180 import android.os.Build;
181 import android.os.Bundle;
182 import android.os.Debug;
183 import android.os.Environment;
184 import android.os.Environment.UserEnvironment;
185 import android.os.FileUtils;
186 import android.os.Handler;
187 import android.os.IBinder;
188 import android.os.Looper;
189 import android.os.Message;
190 import android.os.Parcel;
191 import android.os.ParcelFileDescriptor;
192 import android.os.PatternMatcher;
193 import android.os.Process;
194 import android.os.RemoteCallbackList;
195 import android.os.RemoteException;
196 import android.os.ResultReceiver;
197 import android.os.SELinux;
198 import android.os.ServiceManager;
199 import android.os.ShellCallback;
200 import android.os.SystemClock;
201 import android.os.SystemProperties;
202 import android.os.Trace;
203 import android.os.UserHandle;
204 import android.os.UserManager;
205 import android.os.UserManagerInternal;
206 import android.os.storage.IStorageManager;
207 import android.os.storage.StorageEventListener;
208 import android.os.storage.StorageManager;
209 import android.os.storage.StorageManagerInternal;
210 import android.os.storage.VolumeInfo;
211 import android.os.storage.VolumeRecord;
212 import android.provider.Settings.Global;
213 import android.provider.Settings.Secure;
214 import android.security.KeyStore;
215 import android.security.SystemKeyStore;
216 import android.service.pm.PackageServiceDumpProto;
217 import android.system.ErrnoException;
218 import android.system.Os;
219 import android.text.TextUtils;
220 import android.text.format.DateUtils;
221 import android.util.ArrayMap;
222 import android.util.ArraySet;
223 import android.util.Base64;
224 import android.util.BootTimingsTraceLog;
225 import android.util.DisplayMetrics;
226 import android.util.EventLog;
227 import android.util.ExceptionUtils;
228 import android.util.Log;
229 import android.util.LogPrinter;
230 import android.util.MathUtils;
231 import android.util.PackageUtils;
232 import android.util.Pair;
233 import android.util.PrintStreamPrinter;
234 import android.util.Slog;
235 import android.util.SparseArray;
236 import android.util.SparseBooleanArray;
237 import android.util.SparseIntArray;
238 import android.util.Xml;
239 import android.util.jar.StrictJarFile;
240 import android.util.proto.ProtoOutputStream;
241 import android.view.Display;
243 import com.android.internal.R;
244 import com.android.internal.annotations.GuardedBy;
245 import com.android.internal.app.IMediaContainerService;
246 import com.android.internal.app.ResolverActivity;
247 import com.android.internal.content.NativeLibraryHelper;
248 import com.android.internal.content.PackageHelper;
249 import com.android.internal.logging.MetricsLogger;
250 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
251 import com.android.internal.os.IParcelFileDescriptorFactory;
252 import com.android.internal.os.RoSystemProperties;
253 import com.android.internal.os.SomeArgs;
254 import com.android.internal.os.Zygote;
255 import com.android.internal.telephony.CarrierAppUtils;
256 import com.android.internal.util.ArrayUtils;
257 import com.android.internal.util.ConcurrentUtils;
258 import com.android.internal.util.DumpUtils;
259 import com.android.internal.util.FastPrintWriter;
260 import com.android.internal.util.FastXmlSerializer;
261 import com.android.internal.util.IndentingPrintWriter;
262 import com.android.internal.util.Preconditions;
263 import com.android.internal.util.XmlUtils;
264 import com.android.server.AttributeCache;
265 import com.android.server.DeviceIdleController;
266 import com.android.server.EventLogTags;
267 import com.android.server.FgThread;
268 import com.android.server.IntentResolver;
269 import com.android.server.LocalServices;
270 import com.android.server.LockGuard;
271 import com.android.server.ServiceThread;
272 import com.android.server.SystemConfig;
273 import com.android.server.SystemServerInitThreadPool;
274 import com.android.server.Watchdog;
275 import com.android.server.net.NetworkPolicyManagerInternal;
276 import com.android.server.pm.Installer.InstallerException;
277 import com.android.server.pm.PermissionsState.PermissionState;
278 import com.android.server.pm.Settings.DatabaseVersion;
279 import com.android.server.pm.Settings.VersionInfo;
280 import com.android.server.pm.dex.DexManager;
281 import com.android.server.storage.DeviceStorageMonitorInternal;
283 import dalvik.system.CloseGuard;
284 import dalvik.system.DexFile;
285 import dalvik.system.VMRuntime;
287 import libcore.io.IoUtils;
288 import libcore.util.EmptyArray;
290 import org.xmlpull.v1.XmlPullParser;
291 import org.xmlpull.v1.XmlPullParserException;
292 import org.xmlpull.v1.XmlSerializer;
294 import java.io.BufferedOutputStream;
295 import java.io.BufferedReader;
296 import java.io.ByteArrayInputStream;
297 import java.io.ByteArrayOutputStream;
299 import java.io.FileDescriptor;
300 import java.io.FileInputStream;
301 import java.io.FileOutputStream;
302 import java.io.FileReader;
303 import java.io.FilenameFilter;
304 import java.io.IOException;
305 import java.io.PrintWriter;
306 import java.lang.annotation.Retention;
307 import java.lang.annotation.RetentionPolicy;
308 import java.nio.charset.StandardCharsets;
309 import java.security.DigestInputStream;
310 import java.security.MessageDigest;
311 import java.security.NoSuchAlgorithmException;
312 import java.security.PublicKey;
313 import java.security.SecureRandom;
314 import java.security.cert.Certificate;
315 import java.security.cert.CertificateEncodingException;
316 import java.security.cert.CertificateException;
317 import java.text.SimpleDateFormat;
318 import java.util.ArrayList;
319 import java.util.Arrays;
320 import java.util.Collection;
321 import java.util.Collections;
322 import java.util.Comparator;
323 import java.util.Date;
324 import java.util.HashMap;
325 import java.util.HashSet;
326 import java.util.Iterator;
327 import java.util.List;
328 import java.util.Map;
329 import java.util.Objects;
330 import java.util.Set;
331 import java.util.concurrent.CountDownLatch;
332 import java.util.concurrent.Future;
333 import java.util.concurrent.TimeUnit;
334 import java.util.concurrent.atomic.AtomicBoolean;
335 import java.util.concurrent.atomic.AtomicInteger;
338 * Keep track of all those APKs everywhere.
340 * Internally there are two important locks:
342 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
343 * and other related state. It is a fine-grained lock that should only be held
344 * momentarily, as it's one of the most contended locks in the system.
345 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
346 * operations typically involve heavy lifting of application data on disk. Since
347 * {@code installd} is single-threaded, and it's operations can often be slow,
348 * this lock should never be acquired while already holding {@link #mPackages}.
349 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
350 * holding {@link #mInstallLock}.
352 * Many internal methods rely on the caller to hold the appropriate locks, and
353 * this contract is expressed through method name suffixes:
355 * <li>fooLI(): the caller must hold {@link #mInstallLock}
356 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
357 * being modified must be frozen
358 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
359 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
362 * Because this class is very central to the platform's security; please run all
363 * CTS and unit tests whenever making modifications:
366 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
367 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
370 public class PackageManagerService extends IPackageManager.Stub
371 implements PackageSender {
372 static final String TAG = "PackageManager";
373 static final boolean DEBUG_SETTINGS = false;
374 static final boolean DEBUG_PREFERRED = false;
375 static final boolean DEBUG_UPGRADE = false;
376 static final boolean DEBUG_DOMAIN_VERIFICATION = false;
377 private static final boolean DEBUG_BACKUP = false;
378 private static final boolean DEBUG_INSTALL = false;
379 private static final boolean DEBUG_REMOVE = false;
380 private static final boolean DEBUG_BROADCASTS = false;
381 private static final boolean DEBUG_SHOW_INFO = false;
382 private static final boolean DEBUG_PACKAGE_INFO = false;
383 private static final boolean DEBUG_INTENT_MATCHING = false;
384 private static final boolean DEBUG_PACKAGE_SCANNING = false;
385 private static final boolean DEBUG_VERIFY = false;
386 private static final boolean DEBUG_FILTERS = false;
387 private static final boolean DEBUG_PERMISSIONS = false;
388 private static final boolean DEBUG_SHARED_LIBRARIES = false;
390 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
391 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
392 // user, but by default initialize to this.
393 public static final boolean DEBUG_DEXOPT = false;
395 private static final boolean DEBUG_ABI_SELECTION = false;
396 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
397 private static final boolean DEBUG_TRIAGED_MISSING = false;
398 private static final boolean DEBUG_APP_DATA = false;
400 /** REMOVE. According to Svet, this was only used to reset permissions during development. */
401 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
403 private static final boolean HIDE_EPHEMERAL_APIS = false;
405 private static final boolean ENABLE_FREE_CACHE_V2 =
406 SystemProperties.getBoolean("fw.free_cache_v2", true);
408 private static final int RADIO_UID = Process.PHONE_UID;
409 private static final int LOG_UID = Process.LOG_UID;
410 private static final int NFC_UID = Process.NFC_UID;
411 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
412 private static final int SHELL_UID = Process.SHELL_UID;
414 // Cap the size of permission trees that 3rd party apps can define
415 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text
417 // Suffix used during package installation when copying/moving
418 // package apks to install directory.
419 private static final String INSTALL_PACKAGE_SUFFIX = "-";
421 static final int SCAN_NO_DEX = 1<<1;
422 static final int SCAN_FORCE_DEX = 1<<2;
423 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
424 static final int SCAN_NEW_INSTALL = 1<<4;
425 static final int SCAN_UPDATE_TIME = 1<<5;
426 static final int SCAN_BOOTING = 1<<6;
427 static final int SCAN_TRUSTED_OVERLAY = 1<<7;
428 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
429 static final int SCAN_REPLACING = 1<<9;
430 static final int SCAN_REQUIRE_KNOWN = 1<<10;
431 static final int SCAN_MOVE = 1<<11;
432 static final int SCAN_INITIAL = 1<<12;
433 static final int SCAN_CHECK_ONLY = 1<<13;
434 static final int SCAN_DONT_KILL_APP = 1<<14;
435 static final int SCAN_IGNORE_FROZEN = 1<<15;
436 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
437 static final int SCAN_AS_INSTANT_APP = 1<<17;
438 static final int SCAN_AS_FULL_APP = 1<<18;
439 /** Should not be with the scan flags */
440 static final int FLAGS_REMOVE_CHATTY = 1<<31;
442 private static final String STATIC_SHARED_LIB_DELIMITER = "_";
444 private static final int[] EMPTY_INT_ARRAY = new int[0];
446 private static final int TYPE_UNKNOWN = 0;
447 private static final int TYPE_ACTIVITY = 1;
448 private static final int TYPE_RECEIVER = 2;
449 private static final int TYPE_SERVICE = 3;
450 private static final int TYPE_PROVIDER = 4;
451 @IntDef(prefix = { "TYPE_" }, value = {
458 @Retention(RetentionPolicy.SOURCE)
459 public @interface ComponentType {}
462 * Timeout (in milliseconds) after which the watchdog should declare that
463 * our handler thread is wedged. The usual default for such things is one
464 * minute but we sometimes do very lengthy I/O operations on this thread,
465 * such as installing multi-gigabyte applications, so ours needs to be longer.
467 static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes
470 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
471 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
472 * settings entry if available, otherwise we use the hardcoded default. If it's been
473 * more than this long since the last fstrim, we force one during the boot sequence.
475 * This backstops other fstrim scheduling: if the device is alive at midnight+idle,
476 * one gets run at the next available charging+idle time. This final mandatory
477 * no-fstrim check kicks in only of the other scheduling criteria is never met.
479 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
482 * Whether verification is enabled by default.
484 private static final boolean DEFAULT_VERIFY_ENABLE = true;
487 * The default maximum time to wait for the verification agent to return in
490 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
493 * The default response for package verification timeout.
495 * This can be either PackageManager.VERIFICATION_ALLOW or
496 * PackageManager.VERIFICATION_REJECT.
498 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
500 static final String PLATFORM_PACKAGE_NAME = "android";
502 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
504 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
505 DEFAULT_CONTAINER_PACKAGE,
506 "com.android.defcontainer.DefaultContainerService");
508 private static final String KILL_APP_REASON_GIDS_CHANGED =
509 "permission grant or revoke changed gids";
511 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
512 "permissions revoked";
514 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
516 private static final String PACKAGE_SCHEME = "package";
518 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
520 /** Permission grant: not grant the permission. */
521 private static final int GRANT_DENIED = 1;
523 /** Permission grant: grant the permission as an install permission. */
524 private static final int GRANT_INSTALL = 2;
526 /** Permission grant: grant the permission as a runtime one. */
527 private static final int GRANT_RUNTIME = 3;
529 /** Permission grant: grant as runtime a permission that was granted as an install time one. */
530 private static final int GRANT_UPGRADE = 4;
532 /** Canonical intent used to identify what counts as a "web browser" app */
533 private static final Intent sBrowserIntent;
535 sBrowserIntent = new Intent();
536 sBrowserIntent.setAction(Intent.ACTION_VIEW);
537 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
538 sBrowserIntent.setData(Uri.parse("http:"));
542 * The set of all protected actions [i.e. those actions for which a high priority
543 * intent filter is disallowed].
545 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
547 PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
548 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
549 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
550 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
553 // Compilation reasons.
554 public static final int REASON_FIRST_BOOT = 0;
555 public static final int REASON_BOOT = 1;
556 public static final int REASON_INSTALL = 2;
557 public static final int REASON_BACKGROUND_DEXOPT = 3;
558 public static final int REASON_AB_OTA = 4;
560 public static final int REASON_LAST = REASON_AB_OTA;
562 /** All dangerous permission names in the same order as the events in MetricsEvent */
563 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
564 Manifest.permission.READ_CALENDAR,
565 Manifest.permission.WRITE_CALENDAR,
566 Manifest.permission.CAMERA,
567 Manifest.permission.READ_CONTACTS,
568 Manifest.permission.WRITE_CONTACTS,
569 Manifest.permission.GET_ACCOUNTS,
570 Manifest.permission.ACCESS_FINE_LOCATION,
571 Manifest.permission.ACCESS_COARSE_LOCATION,
572 Manifest.permission.RECORD_AUDIO,
573 Manifest.permission.READ_PHONE_STATE,
574 Manifest.permission.CALL_PHONE,
575 Manifest.permission.READ_CALL_LOG,
576 Manifest.permission.WRITE_CALL_LOG,
577 Manifest.permission.ADD_VOICEMAIL,
578 Manifest.permission.USE_SIP,
579 Manifest.permission.PROCESS_OUTGOING_CALLS,
580 Manifest.permission.READ_CELL_BROADCASTS,
581 Manifest.permission.BODY_SENSORS,
582 Manifest.permission.SEND_SMS,
583 Manifest.permission.RECEIVE_SMS,
584 Manifest.permission.READ_SMS,
585 Manifest.permission.RECEIVE_WAP_PUSH,
586 Manifest.permission.RECEIVE_MMS,
587 Manifest.permission.READ_EXTERNAL_STORAGE,
588 Manifest.permission.WRITE_EXTERNAL_STORAGE,
589 Manifest.permission.READ_PHONE_NUMBERS,
590 Manifest.permission.ANSWER_PHONE_CALLS);
594 * Version number for the package parser cache. Increment this whenever the format or
595 * extent of cached data changes. See {@code PackageParser#setCacheDir}.
597 private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
600 * Whether the package parser cache is enabled.
602 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
604 final ServiceThread mHandlerThread;
606 final PackageHandler mHandler;
608 private final ProcessLoggingHandler mProcessLoggingHandler;
611 * Messages for {@link #mHandler} that need to wait for system ready before
614 private ArrayList<Message> mPostSystemReadyMessages;
616 final int mSdkVersion = Build.VERSION.SDK_INT;
618 final Context mContext;
619 final boolean mFactoryTest;
620 final boolean mOnlyCore;
621 final DisplayMetrics mMetrics;
622 final int mDefParseFlags;
623 final String[] mSeparateProcesses;
624 final boolean mIsUpgrade;
625 final boolean mIsPreNUpgrade;
626 final boolean mIsPreNMR1Upgrade;
628 // Have we told the Activity Manager to whitelist the default container service by uid yet?
629 @GuardedBy("mPackages")
630 boolean mDefaultContainerWhitelisted = false;
632 @GuardedBy("mPackages")
633 private boolean mDexOptDialogShown;
635 /** The location for ASEC container files on internal storage. */
636 final String mAsecInternalPath;
638 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
639 // LOCK HELD. Can be called with mInstallLock held.
640 @GuardedBy("mInstallLock")
641 final Installer mInstaller;
643 /** Directory where installed third-party apps stored */
644 final File mAppInstallDir;
647 * Directory to which applications installed internally have their
648 * 32 bit native libraries copied.
650 private File mAppLib32InstallDir;
652 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
654 final File mDrmAppPrivateInstallDir;
656 // ----------------------------------------------------------------
658 // Lock for state used when installing and doing other long running
659 // operations. Methods that must be called with this lock held have
661 final Object mInstallLock = new Object();
663 // ----------------------------------------------------------------
665 // Keys are String (package name), values are Package. This also serves
666 // as the lock for the global state. Methods that must be called with
667 // this lock held have the prefix "LP".
668 @GuardedBy("mPackages")
669 final ArrayMap<String, PackageParser.Package> mPackages =
670 new ArrayMap<String, PackageParser.Package>();
672 final ArrayMap<String, Set<String>> mKnownCodebase =
673 new ArrayMap<String, Set<String>>();
675 // Keys are isolated uids and values are the uid of the application
676 // that created the isolated proccess.
677 @GuardedBy("mPackages")
678 final SparseIntArray mIsolatedOwners = new SparseIntArray();
681 * Tracks new system packages [received in an OTA] that we expect to
682 * find updated user-installed versions. Keys are package name, values
683 * are package location.
685 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
687 * Tracks high priority intent filters for protected actions. During boot, certain
688 * filter actions are protected and should never be allowed to have a high priority
689 * intent filter for them. However, there is one, and only one exception -- the
690 * setup wizard. It must be able to define a high priority intent filter for these
691 * actions to ensure there are no escapes from the wizard. We need to delay processing
692 * of these during boot as we need to look at all of the system packages in order
693 * to know which component is the setup wizard.
695 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
697 * Whether or not processing protected filters should be deferred.
699 private boolean mDeferProtectedFilters = true;
702 * Tracks existing system packages prior to receiving an OTA. Keys are package name.
704 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
706 * Whether or not system app permissions should be promoted from install to runtime.
708 boolean mPromoteSystemApps;
710 @GuardedBy("mPackages")
711 final Settings mSettings;
714 * Set of package names that are currently "frozen", which means active
715 * surgery is being done on the code/data for that package. The platform
716 * will refuse to launch frozen packages to avoid race conditions.
718 * @see PackageFreezer
720 @GuardedBy("mPackages")
721 final ArraySet<String> mFrozenPackages = new ArraySet<>();
723 final ProtectedPackages mProtectedPackages;
727 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
729 // System configuration read by SystemConfig.
730 final int[] mGlobalGids;
731 final SparseArray<ArraySet<String>> mSystemPermissions;
732 @GuardedBy("mAvailableFeatures")
733 final ArrayMap<String, FeatureInfo> mAvailableFeatures;
735 // If mac_permissions.xml was found for seinfo labeling.
736 boolean mFoundPolicyFile;
738 private final InstantAppRegistry mInstantAppRegistry;
740 @GuardedBy("mPackages")
741 int mChangedPackagesSequenceNumber;
743 * List of changed [installed, removed or updated] packages.
744 * mapping from user id -> sequence number -> package name
746 @GuardedBy("mPackages")
747 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
749 * The sequence number of the last change to a package.
750 * mapping from user id -> package name -> sequence number
752 @GuardedBy("mPackages")
753 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
755 class PackageParserCallback implements PackageParser.Callback {
756 @Override public final boolean hasFeature(String feature) {
757 return PackageManagerService.this.hasSystemFeature(feature, 0);
760 final List<PackageParser.Package> getStaticOverlayPackagesLocked(
761 Collection<PackageParser.Package> allPackages, String targetPackageName) {
762 List<PackageParser.Package> overlayPackages = null;
763 for (PackageParser.Package p : allPackages) {
764 if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
765 if (overlayPackages == null) {
766 overlayPackages = new ArrayList<PackageParser.Package>();
768 overlayPackages.add(p);
771 if (overlayPackages != null) {
772 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
773 public int compare(PackageParser.Package p1, PackageParser.Package p2) {
774 return p1.mOverlayPriority - p2.mOverlayPriority;
777 Collections.sort(overlayPackages, cmp);
779 return overlayPackages;
782 final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
783 String targetPackageName, String targetPath) {
784 if ("android".equals(targetPackageName)) {
785 // Static RROs targeting to "android", ie framework-res.apk, are already applied by
786 // native AssetManager.
789 List<PackageParser.Package> overlayPackages =
790 getStaticOverlayPackagesLocked(allPackages, targetPackageName);
791 if (overlayPackages == null || overlayPackages.isEmpty()) {
794 List<String> overlayPathList = null;
795 for (PackageParser.Package overlayPackage : overlayPackages) {
796 if (targetPath == null) {
797 if (overlayPathList == null) {
798 overlayPathList = new ArrayList<String>();
800 overlayPathList.add(overlayPackage.baseCodePath);
805 // Creates idmaps for system to parse correctly the Android manifest of the
808 // OverlayManagerService will update each of them with a correct gid from its
809 // target package app id.
810 mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
811 UserHandle.getSharedAppGid(
812 UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
813 if (overlayPathList == null) {
814 overlayPathList = new ArrayList<String>();
816 overlayPathList.add(overlayPackage.baseCodePath);
817 } catch (InstallerException e) {
818 Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
819 overlayPackage.baseCodePath);
822 return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
825 String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
826 synchronized (mPackages) {
827 return getStaticOverlayPathsLocked(
828 mPackages.values(), targetPackageName, targetPath);
832 @Override public final String[] getOverlayApks(String targetPackageName) {
833 return getStaticOverlayPaths(targetPackageName, null);
836 @Override public final String[] getOverlayPaths(String targetPackageName,
838 return getStaticOverlayPaths(targetPackageName, targetPath);
842 class ParallelPackageParserCallback extends PackageParserCallback {
843 List<PackageParser.Package> mOverlayPackages = null;
845 void findStaticOverlayPackages() {
846 synchronized (mPackages) {
847 for (PackageParser.Package p : mPackages.values()) {
848 if (p.mIsStaticOverlay) {
849 if (mOverlayPackages == null) {
850 mOverlayPackages = new ArrayList<PackageParser.Package>();
852 mOverlayPackages.add(p);
859 synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
860 // We can trust mOverlayPackages without holding mPackages because package uninstall
861 // can't happen while running parallel parsing.
862 // Moreover holding mPackages on each parsing thread causes dead-lock.
863 return mOverlayPackages == null ? null :
864 getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
868 final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
869 final ParallelPackageParserCallback mParallelPackageParserCallback =
870 new ParallelPackageParserCallback();
872 public static final class SharedLibraryEntry {
873 public final @Nullable String path;
874 public final @Nullable String apk;
875 public final @NonNull SharedLibraryInfo info;
877 SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
878 String declaringPackageName, int declaringPackageVersionCode) {
881 info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
882 declaringPackageName, declaringPackageVersionCode), null);
886 // Currently known shared libraries.
887 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
888 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
891 // All available activities, for your resolving pleasure.
892 final ActivityIntentResolver mActivities =
893 new ActivityIntentResolver();
895 // All available receivers, for your resolving pleasure.
896 final ActivityIntentResolver mReceivers =
897 new ActivityIntentResolver();
899 // All available services, for your resolving pleasure.
900 final ServiceIntentResolver mServices = new ServiceIntentResolver();
902 // All available providers, for your resolving pleasure.
903 final ProviderIntentResolver mProviders = new ProviderIntentResolver();
905 // Mapping from provider base names (first directory in content URI codePath)
906 // to the provider information.
907 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
908 new ArrayMap<String, PackageParser.Provider>();
910 // Mapping from instrumentation class names to info about them.
911 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
912 new ArrayMap<ComponentName, PackageParser.Instrumentation>();
914 // Mapping from permission names to info about them.
915 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
916 new ArrayMap<String, PackageParser.PermissionGroup>();
918 // Packages whose data we have transfered into another package, thus
919 // should no longer exist.
920 final ArraySet<String> mTransferedPackages = new ArraySet<String>();
922 // Broadcast actions that are only available to the system.
923 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
925 /** List of packages waiting for verification. */
926 final SparseArray<PackageVerificationState> mPendingVerification
927 = new SparseArray<PackageVerificationState>();
929 /** Set of packages associated with each app op permission. */
930 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
932 final PackageInstallerService mInstallerService;
934 private final PackageDexOptimizer mPackageDexOptimizer;
935 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
936 // is used by other apps).
937 private final DexManager mDexManager;
939 private AtomicInteger mNextMoveId = new AtomicInteger();
940 private final MoveCallbacks mMoveCallbacks;
942 private final OnPermissionChangeListeners mOnPermissionChangeListeners;
944 // Cache of users who need badging.
945 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
947 /** Token for keys in mPendingVerification. */
948 private int mPendingVerificationToken = 0;
950 volatile boolean mSystemReady;
951 volatile boolean mSafeMode;
952 volatile boolean mHasSystemUidErrors;
953 private volatile boolean mEphemeralAppsDisabled;
955 ApplicationInfo mAndroidApplication;
956 final ActivityInfo mResolveActivity = new ActivityInfo();
957 final ResolveInfo mResolveInfo = new ResolveInfo();
958 ComponentName mResolveComponentName;
959 PackageParser.Package mPlatformPackage;
960 ComponentName mCustomResolverComponentName;
962 boolean mResolverReplaced = false;
964 private final @Nullable ComponentName mIntentFilterVerifierComponent;
965 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
967 private int mIntentFilterVerificationToken = 0;
969 /** The service connection to the ephemeral resolver */
970 final EphemeralResolverConnection mInstantAppResolverConnection;
971 /** Component used to show resolver settings for Instant Apps */
972 final ComponentName mInstantAppResolverSettingsComponent;
974 /** Activity used to install instant applications */
975 ActivityInfo mInstantAppInstallerActivity;
976 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
978 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
979 = new SparseArray<IntentFilterVerificationState>();
981 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
983 // List of packages names to keep cached, even if they are uninstalled for all users
984 private List<String> mKeepUninstalledPackages;
986 private UserManagerInternal mUserManagerInternal;
988 private DeviceIdleController.LocalService mDeviceIdleController;
990 private File mCacheDir;
992 private ArraySet<String> mPrivappPermissionsViolations;
994 private Future<?> mPrepareAppDataFuture;
996 private static class IFVerificationParams {
997 PackageParser.Package pkg;
1002 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1003 int _userId, int _verifierUid) {
1005 replacing = _replacing;
1007 replacing = _replacing;
1008 verifierUid = _verifierUid;
1012 private interface IntentFilterVerifier<T extends IntentFilter> {
1013 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1014 T filter, String packageName);
1015 void startVerifications(int userId);
1016 void receiveVerificationResponse(int verificationId);
1019 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1020 private Context mContext;
1021 private ComponentName mIntentFilterVerifierComponent;
1022 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1024 public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1026 mIntentFilterVerifierComponent = verifierComponent;
1029 private String getDefaultScheme() {
1030 return IntentFilter.SCHEME_HTTPS;
1034 public void startVerifications(int userId) {
1035 // Launch verifications requests
1036 int count = mCurrentIntentFilterVerifications.size();
1037 for (int n=0; n<count; n++) {
1038 int verificationId = mCurrentIntentFilterVerifications.get(n);
1039 final IntentFilterVerificationState ivs =
1040 mIntentFilterVerificationStates.get(verificationId);
1042 String packageName = ivs.getPackageName();
1044 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1045 final int filterCount = filters.size();
1046 ArraySet<String> domainsSet = new ArraySet<>();
1047 for (int m=0; m<filterCount; m++) {
1048 PackageParser.ActivityIntentInfo filter = filters.get(m);
1049 domainsSet.addAll(filter.getHostsList());
1051 synchronized (mPackages) {
1052 if (mSettings.createIntentFilterVerificationIfNeededLPw(
1053 packageName, domainsSet) != null) {
1054 scheduleWriteSettingsLocked();
1057 sendVerificationRequest(userId, verificationId, ivs);
1059 mCurrentIntentFilterVerifications.clear();
1062 private void sendVerificationRequest(int userId, int verificationId,
1063 IntentFilterVerificationState ivs) {
1065 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1066 verificationIntent.putExtra(
1067 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1069 verificationIntent.putExtra(
1070 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1071 getDefaultScheme());
1072 verificationIntent.putExtra(
1073 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1074 ivs.getHostsString());
1075 verificationIntent.putExtra(
1076 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1077 ivs.getPackageName());
1078 verificationIntent.setComponent(mIntentFilterVerifierComponent);
1079 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1081 DeviceIdleController.LocalService idleController = getDeviceIdleController();
1082 idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1083 mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1084 userId, false, "intent filter verifier");
1086 UserHandle user = new UserHandle(userId);
1087 mContext.sendBroadcastAsUser(verificationIntent, user);
1088 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1089 "Sending IntentFilter verification broadcast");
1092 public void receiveVerificationResponse(int verificationId) {
1093 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1095 final boolean verified = ivs.isVerified();
1097 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1098 final int count = filters.size();
1099 if (DEBUG_DOMAIN_VERIFICATION) {
1100 Slog.i(TAG, "Received verification response " + verificationId
1101 + " for " + count + " filters, verified=" + verified);
1103 for (int n=0; n<count; n++) {
1104 PackageParser.ActivityIntentInfo filter = filters.get(n);
1105 filter.setVerified(verified);
1107 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1108 + " verified with result:" + verified + " and hosts:"
1109 + ivs.getHostsString());
1112 mIntentFilterVerificationStates.remove(verificationId);
1114 final String packageName = ivs.getPackageName();
1115 IntentFilterVerificationInfo ivi = null;
1117 synchronized (mPackages) {
1118 ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1121 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1122 + verificationId + " packageName:" + packageName);
1125 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1126 "Updating IntentFilterVerificationInfo for package " + packageName
1127 +" verificationId:" + verificationId);
1129 synchronized (mPackages) {
1131 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1133 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1135 scheduleWriteSettingsLocked();
1137 final int userId = ivs.getUserId();
1138 if (userId != UserHandle.USER_ALL) {
1139 final int userStatus =
1140 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1142 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1143 boolean needUpdate = false;
1145 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1146 // already been set by the User thru the Disambiguation dialog
1147 switch (userStatus) {
1148 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1150 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1152 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1157 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1159 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1169 mSettings.updateIntentFilterVerificationStatusLPw(
1170 packageName, updatedStatus, userId);
1171 scheduleWritePackageRestrictionsLocked(userId);
1178 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1179 ActivityIntentInfo filter, String packageName) {
1180 if (!hasValidDomains(filter)) {
1183 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1185 ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1188 if (DEBUG_DOMAIN_VERIFICATION) {
1189 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1191 ivs.addFilter(filter);
1195 private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1196 int userId, int verificationId, String packageName) {
1197 IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1198 verifierUid, userId, packageName);
1199 ivs.setPendingState();
1200 synchronized (mPackages) {
1201 mIntentFilterVerificationStates.append(verificationId, ivs);
1202 mCurrentIntentFilterVerifications.add(verificationId);
1208 private static boolean hasValidDomains(ActivityIntentInfo filter) {
1209 return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1210 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1211 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1214 // Set of pending broadcasts for aggregating enable/disable of components.
1215 static class PendingPackageBroadcasts {
1216 // for each user id, a map of <package name -> components within that package>
1217 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1219 public PendingPackageBroadcasts() {
1220 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1223 public ArrayList<String> get(int userId, String packageName) {
1224 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1225 return packages.get(packageName);
1228 public void put(int userId, String packageName, ArrayList<String> components) {
1229 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1230 packages.put(packageName, components);
1233 public void remove(int userId, String packageName) {
1234 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1235 if (packages != null) {
1236 packages.remove(packageName);
1240 public void remove(int userId) {
1241 mUidMap.remove(userId);
1244 public int userIdCount() {
1245 return mUidMap.size();
1248 public int userIdAt(int n) {
1249 return mUidMap.keyAt(n);
1252 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1253 return mUidMap.get(userId);
1257 // total number of pending broadcast entries across all userIds
1259 for (int i = 0; i< mUidMap.size(); i++) {
1260 num += mUidMap.valueAt(i).size();
1265 public void clear() {
1269 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1270 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1272 map = new ArrayMap<String, ArrayList<String>>();
1273 mUidMap.put(userId, map);
1278 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1280 // Service Connection to remote media container service to copy
1281 // package uri's from external media onto secure containers
1282 // or internal storage.
1283 private IMediaContainerService mContainerService = null;
1285 static final int SEND_PENDING_BROADCAST = 1;
1286 static final int MCS_BOUND = 3;
1287 static final int END_COPY = 4;
1288 static final int INIT_COPY = 5;
1289 static final int MCS_UNBIND = 6;
1290 static final int START_CLEANING_PACKAGE = 7;
1291 static final int FIND_INSTALL_LOC = 8;
1292 static final int POST_INSTALL = 9;
1293 static final int MCS_RECONNECT = 10;
1294 static final int MCS_GIVE_UP = 11;
1295 static final int UPDATED_MEDIA_STATUS = 12;
1296 static final int WRITE_SETTINGS = 13;
1297 static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1298 static final int PACKAGE_VERIFIED = 15;
1299 static final int CHECK_PENDING_VERIFICATION = 16;
1300 static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1301 static final int INTENT_FILTER_VERIFIED = 18;
1302 static final int WRITE_PACKAGE_LIST = 19;
1303 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1305 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
1307 // Delay time in millisecs
1308 static final int BROADCAST_DELAY = 10 * 1000;
1310 private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1311 2 * 60 * 60 * 1000L; /* two hours */
1313 static UserManagerService sUserManager;
1315 // Stores a list of users whose package restrictions file needs to be updated
1316 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1318 final private DefaultContainerConnection mDefContainerConn =
1319 new DefaultContainerConnection();
1320 class DefaultContainerConnection implements ServiceConnection {
1321 public void onServiceConnected(ComponentName name, IBinder service) {
1322 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1323 final IMediaContainerService imcs = IMediaContainerService.Stub
1324 .asInterface(Binder.allowBlocking(service));
1325 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1328 public void onServiceDisconnected(ComponentName name) {
1329 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1333 // Recordkeeping of restore-after-install operations that are currently in flight
1334 // between the Package Manager and the Backup Manager
1335 static class PostInstallData {
1336 public InstallArgs args;
1337 public PackageInstalledInfo res;
1339 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1345 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1346 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
1348 // XML tags for backup/restore of various bits of state
1349 private static final String TAG_PREFERRED_BACKUP = "pa";
1350 private static final String TAG_DEFAULT_APPS = "da";
1351 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1353 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1354 private static final String TAG_ALL_GRANTS = "rt-grants";
1355 private static final String TAG_GRANT = "grant";
1356 private static final String ATTR_PACKAGE_NAME = "pkg";
1358 private static final String TAG_PERMISSION = "perm";
1359 private static final String ATTR_PERMISSION_NAME = "name";
1360 private static final String ATTR_IS_GRANTED = "g";
1361 private static final String ATTR_USER_SET = "set";
1362 private static final String ATTR_USER_FIXED = "fixed";
1363 private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1365 // System/policy permission grants are not backed up
1366 private static final int SYSTEM_RUNTIME_GRANT_MASK =
1367 FLAG_PERMISSION_POLICY_FIXED
1368 | FLAG_PERMISSION_SYSTEM_FIXED
1369 | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1371 // And we back up these user-adjusted states
1372 private static final int USER_RUNTIME_GRANT_MASK =
1373 FLAG_PERMISSION_USER_SET
1374 | FLAG_PERMISSION_USER_FIXED
1375 | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1377 final @Nullable String mRequiredVerifierPackage;
1378 final @NonNull String mRequiredInstallerPackage;
1379 final @NonNull String mRequiredUninstallerPackage;
1380 final @Nullable String mSetupWizardPackage;
1381 final @Nullable String mStorageManagerPackage;
1382 final @NonNull String mServicesSystemSharedLibraryPackageName;
1383 final @NonNull String mSharedSystemSharedLibraryPackageName;
1385 final boolean mPermissionReviewRequired;
1387 private final PackageUsage mPackageUsage = new PackageUsage();
1388 private final CompilerStats mCompilerStats = new CompilerStats();
1390 class PackageHandler extends Handler {
1391 private boolean mBound = false;
1392 final ArrayList<HandlerParams> mPendingInstalls =
1393 new ArrayList<HandlerParams>();
1395 private boolean connectToService() {
1396 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1397 " DefaultContainerService");
1398 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1399 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1400 if (mContext.bindServiceAsUser(service, mDefContainerConn,
1401 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1402 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1406 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1410 private void disconnectService() {
1411 mContainerService = null;
1413 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1414 mContext.unbindService(mDefContainerConn);
1415 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1418 PackageHandler(Looper looper) {
1422 public void handleMessage(Message msg) {
1424 doHandleMessage(msg);
1426 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1430 void doHandleMessage(Message msg) {
1433 HandlerParams params = (HandlerParams) msg.obj;
1434 int idx = mPendingInstalls.size();
1435 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1436 // If a bind was already initiated we dont really
1437 // need to do anything. The pending install
1438 // will be processed later on.
1440 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1441 System.identityHashCode(mHandler));
1442 // If this is the only one pending we might
1443 // have to bind to the service again.
1444 if (!connectToService()) {
1445 Slog.e(TAG, "Failed to bind to media container service");
1446 params.serviceError();
1447 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1448 System.identityHashCode(mHandler));
1449 if (params.traceMethod != null) {
1450 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1451 params.traceCookie);
1455 // Once we bind to the service, the first
1456 // pending request will be processed.
1457 mPendingInstalls.add(idx, params);
1460 mPendingInstalls.add(idx, params);
1461 // Already bound to the service. Just make
1462 // sure we trigger off processing the first request.
1464 mHandler.sendEmptyMessage(MCS_BOUND);
1470 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1471 if (msg.obj != null) {
1472 mContainerService = (IMediaContainerService) msg.obj;
1473 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1474 System.identityHashCode(mHandler));
1476 if (mContainerService == null) {
1478 // Something seriously wrong since we are not bound and we are not
1479 // waiting for connection. Bail out.
1480 Slog.e(TAG, "Cannot bind to media container service");
1481 for (HandlerParams params : mPendingInstalls) {
1482 // Indicate service bind error
1483 params.serviceError();
1484 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1485 System.identityHashCode(params));
1486 if (params.traceMethod != null) {
1487 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1488 params.traceMethod, params.traceCookie);
1492 mPendingInstalls.clear();
1494 Slog.w(TAG, "Waiting to connect to media container service");
1496 } else if (mPendingInstalls.size() > 0) {
1497 HandlerParams params = mPendingInstalls.get(0);
1498 if (params != null) {
1499 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1500 System.identityHashCode(params));
1501 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1502 if (params.startCopy()) {
1503 // We are done... look for more work or to
1505 if (DEBUG_SD_INSTALL) Log.i(TAG,
1506 "Checking for more work or unbind...");
1507 // Delete pending install
1508 if (mPendingInstalls.size() > 0) {
1509 mPendingInstalls.remove(0);
1511 if (mPendingInstalls.size() == 0) {
1513 if (DEBUG_SD_INSTALL) Log.i(TAG,
1514 "Posting delayed MCS_UNBIND");
1515 removeMessages(MCS_UNBIND);
1516 Message ubmsg = obtainMessage(MCS_UNBIND);
1517 // Unbind after a little delay, to avoid
1518 // continual thrashing.
1519 sendMessageDelayed(ubmsg, 10000);
1522 // There are more pending requests in queue.
1523 // Just post MCS_BOUND message to trigger processing
1524 // of next pending install.
1525 if (DEBUG_SD_INSTALL) Log.i(TAG,
1526 "Posting MCS_BOUND for next work");
1527 mHandler.sendEmptyMessage(MCS_BOUND);
1530 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1533 // Should never happen ideally.
1534 Slog.w(TAG, "Empty queue");
1538 case MCS_RECONNECT: {
1539 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1540 if (mPendingInstalls.size() > 0) {
1542 disconnectService();
1544 if (!connectToService()) {
1545 Slog.e(TAG, "Failed to bind to media container service");
1546 for (HandlerParams params : mPendingInstalls) {
1547 // Indicate service bind error
1548 params.serviceError();
1549 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1550 System.identityHashCode(params));
1552 mPendingInstalls.clear();
1558 // If there is no actual work left, then time to unbind.
1559 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1561 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1563 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1565 disconnectService();
1567 } else if (mPendingInstalls.size() > 0) {
1568 // There are more pending requests in queue.
1569 // Just post MCS_BOUND message to trigger processing
1570 // of next pending install.
1571 mHandler.sendEmptyMessage(MCS_BOUND);
1577 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1578 HandlerParams params = mPendingInstalls.remove(0);
1579 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1580 System.identityHashCode(params));
1583 case SEND_PENDING_BROADCAST: {
1585 ArrayList<String> components[];
1588 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1589 synchronized (mPackages) {
1590 if (mPendingBroadcasts == null) {
1593 size = mPendingBroadcasts.size();
1595 // Nothing to be done. Just return
1598 packages = new String[size];
1599 components = new ArrayList[size];
1600 uids = new int[size];
1601 int i = 0; // filling out the above arrays
1603 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1604 int packageUserId = mPendingBroadcasts.userIdAt(n);
1605 Iterator<Map.Entry<String, ArrayList<String>>> it
1606 = mPendingBroadcasts.packagesForUserId(packageUserId)
1607 .entrySet().iterator();
1608 while (it.hasNext() && i < size) {
1609 Map.Entry<String, ArrayList<String>> ent = it.next();
1610 packages[i] = ent.getKey();
1611 components[i] = ent.getValue();
1612 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1613 uids[i] = (ps != null)
1614 ? UserHandle.getUid(packageUserId, ps.appId)
1620 mPendingBroadcasts.clear();
1623 for (int i = 0; i < size; i++) {
1624 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1626 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1629 case START_CLEANING_PACKAGE: {
1630 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1631 final String packageName = (String)msg.obj;
1632 final int userId = msg.arg1;
1633 final boolean andCode = msg.arg2 != 0;
1634 synchronized (mPackages) {
1635 if (userId == UserHandle.USER_ALL) {
1636 int[] users = sUserManager.getUserIds();
1637 for (int user : users) {
1638 mSettings.addPackageToCleanLPw(
1639 new PackageCleanItem(user, packageName, andCode));
1642 mSettings.addPackageToCleanLPw(
1643 new PackageCleanItem(userId, packageName, andCode));
1646 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1647 startCleaningPackages();
1649 case POST_INSTALL: {
1650 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1652 PostInstallData data = mRunningInstalls.get(msg.arg1);
1653 final boolean didRestore = (msg.arg2 != 0);
1654 mRunningInstalls.delete(msg.arg1);
1657 InstallArgs args = data.args;
1658 PackageInstalledInfo parentRes = data.res;
1660 final boolean grantPermissions = (args.installFlags
1661 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1662 final boolean killApp = (args.installFlags
1663 & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1664 final String[] grantedPermissions = args.installGrantPermissions;
1666 // Handle the parent package
1667 handlePackagePostInstall(parentRes, grantPermissions, killApp,
1668 grantedPermissions, didRestore, args.installerPackageName,
1671 // Handle the child packages
1672 final int childCount = (parentRes.addedChildPackages != null)
1673 ? parentRes.addedChildPackages.size() : 0;
1674 for (int i = 0; i < childCount; i++) {
1675 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1676 handlePackagePostInstall(childRes, grantPermissions, killApp,
1677 grantedPermissions, false, args.installerPackageName,
1681 // Log tracing if needed
1682 if (args.traceMethod != null) {
1683 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1687 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1690 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1692 case UPDATED_MEDIA_STATUS: {
1693 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1694 boolean reportStatus = msg.arg1 == 1;
1695 boolean doGc = msg.arg2 == 1;
1696 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1698 // Force a gc to clear up stale containers.
1699 Runtime.getRuntime().gc();
1701 if (msg.obj != null) {
1702 @SuppressWarnings("unchecked")
1703 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1704 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1705 // Unload containers
1706 unloadAllContainers(args);
1710 if (DEBUG_SD_INSTALL) Log.i(TAG,
1711 "Invoking StorageManagerService call back");
1712 PackageHelper.getStorageManager().finishMediaUpdate();
1713 } catch (RemoteException e) {
1714 Log.e(TAG, "StorageManagerService not running?");
1718 case WRITE_SETTINGS: {
1719 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1720 synchronized (mPackages) {
1721 removeMessages(WRITE_SETTINGS);
1722 removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1723 mSettings.writeLPr();
1724 mDirtyUsers.clear();
1726 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1728 case WRITE_PACKAGE_RESTRICTIONS: {
1729 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1730 synchronized (mPackages) {
1731 removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1732 for (int userId : mDirtyUsers) {
1733 mSettings.writePackageRestrictionsLPr(userId);
1735 mDirtyUsers.clear();
1737 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1739 case WRITE_PACKAGE_LIST: {
1740 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1741 synchronized (mPackages) {
1742 removeMessages(WRITE_PACKAGE_LIST);
1743 mSettings.writePackageListLPr(msg.arg1);
1745 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1747 case CHECK_PENDING_VERIFICATION: {
1748 final int verificationId = msg.arg1;
1749 final PackageVerificationState state = mPendingVerification.get(verificationId);
1751 if ((state != null) && !state.timeoutExtended()) {
1752 final InstallArgs args = state.getInstallArgs();
1753 final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1755 Slog.i(TAG, "Verification timed out for " + originUri);
1756 mPendingVerification.remove(verificationId);
1758 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1760 final UserHandle user = args.getUser();
1761 if (getDefaultVerificationResponse(user)
1762 == PackageManager.VERIFICATION_ALLOW) {
1763 Slog.i(TAG, "Continuing with installation of " + originUri);
1764 state.setVerifierResponse(Binder.getCallingUid(),
1765 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1766 broadcastPackageVerified(verificationId, originUri,
1767 PackageManager.VERIFICATION_ALLOW, user);
1769 ret = args.copyApk(mContainerService, true);
1770 } catch (RemoteException e) {
1771 Slog.e(TAG, "Could not contact the ContainerService");
1774 broadcastPackageVerified(verificationId, originUri,
1775 PackageManager.VERIFICATION_REJECT, user);
1778 Trace.asyncTraceEnd(
1779 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1781 processPendingInstall(args, ret);
1782 mHandler.sendEmptyMessage(MCS_UNBIND);
1786 case PACKAGE_VERIFIED: {
1787 final int verificationId = msg.arg1;
1789 final PackageVerificationState state = mPendingVerification.get(verificationId);
1790 if (state == null) {
1791 Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1795 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1797 state.setVerifierResponse(response.callerUid, response.code);
1799 if (state.isVerificationComplete()) {
1800 mPendingVerification.remove(verificationId);
1802 final InstallArgs args = state.getInstallArgs();
1803 final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1806 if (state.isInstallAllowed()) {
1807 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1808 broadcastPackageVerified(verificationId, originUri,
1809 response.code, state.getInstallArgs().getUser());
1811 ret = args.copyApk(mContainerService, true);
1812 } catch (RemoteException e) {
1813 Slog.e(TAG, "Could not contact the ContainerService");
1816 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1819 Trace.asyncTraceEnd(
1820 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1822 processPendingInstall(args, ret);
1823 mHandler.sendEmptyMessage(MCS_UNBIND);
1828 case START_INTENT_FILTER_VERIFICATIONS: {
1829 IFVerificationParams params = (IFVerificationParams) msg.obj;
1830 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1831 params.replacing, params.pkg);
1834 case INTENT_FILTER_VERIFIED: {
1835 final int verificationId = msg.arg1;
1837 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1839 if (state == null) {
1840 Slog.w(TAG, "Invalid IntentFilter verification token "
1841 + verificationId + " received");
1845 final int userId = state.getUserId();
1847 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1848 "Processing IntentFilter verification with token:"
1849 + verificationId + " and userId:" + userId);
1851 final IntentFilterVerificationResponse response =
1852 (IntentFilterVerificationResponse) msg.obj;
1854 state.setVerifierResponse(response.callerUid, response.code);
1856 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1857 "IntentFilter verification with token:" + verificationId
1858 + " and userId:" + userId
1859 + " is settings verifier response with response code:"
1862 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1863 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1864 + response.getFailedDomainsString());
1867 if (state.isVerificationComplete()) {
1868 mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1870 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1871 "IntentFilter verification with token:" + verificationId
1872 + " was not said to be complete");
1877 case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1878 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1879 mInstantAppResolverConnection,
1880 (InstantAppRequest) msg.obj,
1881 mInstantAppInstallerActivity,
1888 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1889 boolean killApp, String[] grantedPermissions,
1890 boolean launchedForRestore, String installerPackage,
1891 IPackageInstallObserver2 installObserver) {
1892 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1893 // Send the removed broadcasts
1894 if (res.removedInfo != null) {
1895 res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1898 // Now that we successfully installed the package, grant runtime
1899 // permissions if requested before broadcasting the install. Also
1900 // for legacy apps in permission review mode we clear the permission
1901 // review flag which is used to emulate runtime permissions for
1903 if (grantPermissions) {
1904 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1907 final boolean update = res.removedInfo != null
1908 && res.removedInfo.removedPackage != null;
1909 final String origInstallerPackageName = res.removedInfo != null
1910 ? res.removedInfo.installerPackageName : null;
1912 // If this is the first time we have child packages for a disabled privileged
1913 // app that had no children, we grant requested runtime permissions to the new
1914 // children if the parent on the system image had them already granted.
1915 if (res.pkg.parentPackage != null) {
1916 synchronized (mPackages) {
1917 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1921 synchronized (mPackages) {
1922 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1925 final String packageName = res.pkg.applicationInfo.packageName;
1927 // Determine the set of users who are adding this package for
1928 // the first time vs. those who are seeing an update.
1929 int[] firstUsers = EMPTY_INT_ARRAY;
1930 int[] updateUsers = EMPTY_INT_ARRAY;
1931 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1932 final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1933 for (int newUser : res.newUsers) {
1934 if (ps.getInstantApp(newUser)) {
1938 firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1941 boolean isNew = true;
1942 for (int origUser : res.origUsers) {
1943 if (origUser == newUser) {
1949 firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1951 updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1955 // Send installed broadcasts if the package is not a static shared lib.
1956 if (res.pkg.staticSharedLibName == null) {
1957 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1959 // Send added for users that see the package for the first time
1960 // sendPackageAddedForNewUsers also deals with system apps
1961 int appId = UserHandle.getAppId(res.uid);
1962 boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1963 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1965 // Send added for users that don't see the package for the first time
1966 Bundle extras = new Bundle(1);
1967 extras.putInt(Intent.EXTRA_UID, res.uid);
1969 extras.putBoolean(Intent.EXTRA_REPLACING, true);
1971 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1972 extras, 0 /*flags*/,
1973 null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1974 if (origInstallerPackageName != null) {
1975 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1976 extras, 0 /*flags*/,
1977 origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1980 // Send replaced for users that don't see the package for the first time
1982 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1983 packageName, extras, 0 /*flags*/,
1984 null /*targetPackage*/, null /*finishedReceiver*/,
1986 if (origInstallerPackageName != null) {
1987 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1988 extras, 0 /*flags*/,
1989 origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1991 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1992 null /*package*/, null /*extras*/, 0 /*flags*/,
1993 packageName /*targetPackage*/,
1994 null /*finishedReceiver*/, updateUsers);
1995 } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1996 // First-install and we did a restore, so we're responsible for the
1997 // first-launch broadcast.
1999 Slog.i(TAG, "Post-restore of " + packageName
2000 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2002 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2005 // Send broadcast package appeared if forward locked/external for all users
2006 // treat asec-hosted packages like removable media on upgrade
2007 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2008 if (DEBUG_INSTALL) {
2009 Slog.i(TAG, "upgrading pkg " + res.pkg
2010 + " is ASEC-hosted -> AVAILABLE");
2012 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2013 ArrayList<String> pkgList = new ArrayList<>(1);
2014 pkgList.add(packageName);
2015 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2019 // Work that needs to happen on first install within each user
2020 if (firstUsers != null && firstUsers.length > 0) {
2021 synchronized (mPackages) {
2022 for (int userId : firstUsers) {
2023 // If this app is a browser and it's newly-installed for some
2024 // users, clear any default-browser state in those users. The
2025 // app's nature doesn't depend on the user, so we can just check
2026 // its browser nature in any user and generalize.
2027 if (packageIsBrowser(packageName, userId)) {
2028 mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2031 // We may also need to apply pending (restored) runtime
2032 // permission grants within these users.
2033 mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2038 // Log current value of "unknown sources" setting
2039 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2040 getUnknownSourcesSettings());
2042 // Remove the replaced package's older resources safely now
2043 // We delete after a gc for applications on sdcard.
2044 if (res.removedInfo != null && res.removedInfo.args != null) {
2045 Runtime.getRuntime().gc();
2046 synchronized (mInstallLock) {
2047 res.removedInfo.args.doPostDeleteLI(true);
2050 // Force a gc to clear up things. Ask for a background one, it's fine to go on
2051 // and not block here.
2052 VMRuntime.getRuntime().requestConcurrentGC();
2055 // Notify DexManager that the package was installed for new users.
2056 // The updated users should already be indexed and the package code paths
2057 // should not change.
2058 // Don't notify the manager for ephemeral apps as they are not expected to
2059 // survive long enough to benefit of background optimizations.
2060 for (int userId : firstUsers) {
2061 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2062 // There's a race currently where some install events may interleave with an uninstall.
2063 // This can lead to package info being null (b/36642664).
2065 mDexManager.notifyPackageInstalled(info, userId);
2070 // If someone is watching installs - notify them
2071 if (installObserver != null) {
2073 Bundle extras = extrasForInstallResult(res);
2074 installObserver.onPackageInstalled(res.name, res.returnCode,
2075 res.returnMsg, extras);
2076 } catch (RemoteException e) {
2077 Slog.i(TAG, "Observer no longer exists.");
2082 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2083 PackageParser.Package pkg) {
2084 if (pkg.parentPackage == null) {
2087 if (pkg.requestedPermissions == null) {
2090 final PackageSetting disabledSysParentPs = mSettings
2091 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2092 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2093 || !disabledSysParentPs.isPrivileged()
2094 || (disabledSysParentPs.childPackageNames != null
2095 && !disabledSysParentPs.childPackageNames.isEmpty())) {
2098 final int[] allUserIds = sUserManager.getUserIds();
2099 final int permCount = pkg.requestedPermissions.size();
2100 for (int i = 0; i < permCount; i++) {
2101 String permission = pkg.requestedPermissions.get(i);
2102 BasePermission bp = mSettings.mPermissions.get(permission);
2103 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2106 for (int userId : allUserIds) {
2107 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2108 permission, userId)) {
2109 grantRuntimePermission(pkg.packageName, permission, userId);
2115 private StorageEventListener mStorageListener = new StorageEventListener() {
2117 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2118 if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2119 if (vol.state == VolumeInfo.STATE_MOUNTED) {
2120 final String volumeUuid = vol.getFsUuid();
2122 // Clean up any users or apps that were removed or recreated
2123 // while this volume was missing
2124 sUserManager.reconcileUsers(volumeUuid);
2125 reconcileApps(volumeUuid);
2127 // Clean up any install sessions that expired or were
2128 // cancelled while this volume was missing
2129 mInstallerService.onPrivateVolumeMounted(volumeUuid);
2131 loadPrivatePackages(vol);
2133 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2134 unloadPrivatePackages(vol);
2138 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2139 if (vol.state == VolumeInfo.STATE_MOUNTED) {
2140 updateExternalMediaStatus(true, false);
2141 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2142 updateExternalMediaStatus(false, false);
2148 public void onVolumeForgotten(String fsUuid) {
2149 if (TextUtils.isEmpty(fsUuid)) {
2150 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2154 // Remove any apps installed on the forgotten volume
2155 synchronized (mPackages) {
2156 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2157 for (PackageSetting ps : packages) {
2158 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2159 deletePackageVersioned(new VersionedPackage(ps.name,
2160 PackageManager.VERSION_CODE_HIGHEST),
2161 new LegacyPackageDeleteObserver(null).getBinder(),
2162 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2163 // Try very hard to release any references to this package
2164 // so we don't risk the system server being killed due to
2166 AttributeCache.instance().removePackage(ps.name);
2169 mSettings.onVolumeForgotten(fsUuid);
2170 mSettings.writeLPr();
2175 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2176 String[] grantedPermissions) {
2177 for (int userId : userIds) {
2178 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2182 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2183 String[] grantedPermissions) {
2184 PackageSetting ps = (PackageSetting) pkg.mExtras;
2189 PermissionsState permissionsState = ps.getPermissionsState();
2191 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2192 | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2194 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2195 >= Build.VERSION_CODES.M;
2197 final boolean instantApp = isInstantApp(pkg.packageName, userId);
2199 for (String permission : pkg.requestedPermissions) {
2200 final BasePermission bp;
2201 synchronized (mPackages) {
2202 bp = mSettings.mPermissions.get(permission);
2204 if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2205 && (!instantApp || bp.isInstant())
2206 && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2207 && (grantedPermissions == null
2208 || ArrayUtils.contains(grantedPermissions, permission))) {
2209 final int flags = permissionsState.getPermissionFlags(permission, userId);
2210 if (supportsRuntimePermissions) {
2211 // Installer cannot change immutable permissions.
2212 if ((flags & immutableFlags) == 0) {
2213 grantRuntimePermission(pkg.packageName, permission, userId);
2215 } else if (mPermissionReviewRequired) {
2216 // In permission review mode we clear the review flag when we
2217 // are asked to install the app with all permissions granted.
2218 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2219 updatePermissionFlags(permission, pkg.packageName,
2220 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2227 Bundle extrasForInstallResult(PackageInstalledInfo res) {
2228 Bundle extras = null;
2229 switch (res.returnCode) {
2230 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2231 extras = new Bundle();
2232 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2233 res.origPermission);
2234 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2238 case PackageManager.INSTALL_SUCCEEDED: {
2239 extras = new Bundle();
2240 extras.putBoolean(Intent.EXTRA_REPLACING,
2241 res.removedInfo != null && res.removedInfo.removedPackage != null);
2248 void scheduleWriteSettingsLocked() {
2249 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2250 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2254 void scheduleWritePackageListLocked(int userId) {
2255 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2256 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2258 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2262 void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2263 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2264 scheduleWritePackageRestrictionsLocked(userId);
2267 void scheduleWritePackageRestrictionsLocked(int userId) {
2268 final int[] userIds = (userId == UserHandle.USER_ALL)
2269 ? sUserManager.getUserIds() : new int[]{userId};
2270 for (int nextUserId : userIds) {
2271 if (!sUserManager.exists(nextUserId)) return;
2272 mDirtyUsers.add(nextUserId);
2273 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2274 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2279 public static PackageManagerService main(Context context, Installer installer,
2280 boolean factoryTest, boolean onlyCore) {
2281 // Self-check for initial settings.
2282 PackageManagerServiceCompilerMapping.checkProperties();
2284 PackageManagerService m = new PackageManagerService(context, installer,
2285 factoryTest, onlyCore);
2286 m.enableSystemUserPackages();
2287 ServiceManager.addService("package", m);
2291 private void enableSystemUserPackages() {
2292 if (!UserManager.isSplitSystemUser()) {
2295 // For system user, enable apps based on the following conditions:
2296 // - app is whitelisted or belong to one of these groups:
2297 // -- system app which has no launcher icons
2298 // -- system app which has INTERACT_ACROSS_USERS permission
2299 // -- system IME app
2300 // - app is not in the blacklist
2301 AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2302 Set<String> enableApps = new ArraySet<>();
2303 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2304 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2305 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2306 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2307 enableApps.addAll(wlApps);
2308 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2309 /* systemAppsOnly */ false, UserHandle.SYSTEM));
2310 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2311 enableApps.removeAll(blApps);
2312 Log.i(TAG, "Applications installed for system user: " + enableApps);
2313 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2315 final int allAppsSize = allAps.size();
2316 synchronized (mPackages) {
2317 for (int i = 0; i < allAppsSize; i++) {
2318 String pName = allAps.get(i);
2319 PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2320 // Should not happen, but we shouldn't be failing if it does
2321 if (pkgSetting == null) {
2324 boolean install = enableApps.contains(pName);
2325 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2326 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2327 + " for system user");
2328 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2331 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2335 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2336 DisplayManager displayManager = (DisplayManager) context.getSystemService(
2337 Context.DISPLAY_SERVICE);
2338 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2342 * Requests that files preopted on a secondary system partition be copied to the data partition
2343 * if possible. Note that the actual copying of the files is accomplished by init for security
2344 * reasons. This simply requests that the copy takes place and awaits confirmation of its
2345 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2347 private static void requestCopyPreoptedFiles() {
2348 final int WAIT_TIME_MS = 100;
2349 final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2350 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2351 SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2352 // We will wait for up to 100 seconds.
2353 final long timeStart = SystemClock.uptimeMillis();
2354 final long timeEnd = timeStart + 100 * 1000;
2355 long timeNow = timeStart;
2356 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2358 Thread.sleep(WAIT_TIME_MS);
2359 } catch (InterruptedException e) {
2362 timeNow = SystemClock.uptimeMillis();
2363 if (timeNow > timeEnd) {
2364 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2365 Slog.wtf(TAG, "cppreopt did not finish!");
2370 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2374 public PackageManagerService(Context context, Installer installer,
2375 boolean factoryTest, boolean onlyCore) {
2376 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2377 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2378 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2379 SystemClock.uptimeMillis());
2381 if (mSdkVersion <= 0) {
2382 Slog.w(TAG, "**** ro.build.version.sdk not set!");
2387 mPermissionReviewRequired = context.getResources().getBoolean(
2388 R.bool.config_permissionReviewRequired);
2390 mFactoryTest = factoryTest;
2391 mOnlyCore = onlyCore;
2392 mMetrics = new DisplayMetrics();
2393 mSettings = new Settings(mPackages);
2394 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2395 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2396 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2397 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2398 mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2399 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2400 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2401 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2402 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2403 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2404 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2405 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2407 String separateProcesses = SystemProperties.get("debug.separate_processes");
2408 if (separateProcesses != null && separateProcesses.length() > 0) {
2409 if ("*".equals(separateProcesses)) {
2410 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2411 mSeparateProcesses = null;
2412 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2415 mSeparateProcesses = separateProcesses.split(",");
2416 Slog.w(TAG, "Running with debug.separate_processes: "
2417 + separateProcesses);
2421 mSeparateProcesses = null;
2424 mInstaller = installer;
2425 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2427 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2428 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2430 mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2431 FgThread.get().getLooper());
2433 getDefaultDisplayMetrics(context, mMetrics);
2435 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2436 SystemConfig systemConfig = SystemConfig.getInstance();
2437 mGlobalGids = systemConfig.getGlobalGids();
2438 mSystemPermissions = systemConfig.getSystemPermissions();
2439 mAvailableFeatures = systemConfig.getAvailableFeatures();
2440 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2442 mProtectedPackages = new ProtectedPackages(mContext);
2444 synchronized (mInstallLock) {
2446 synchronized (mPackages) {
2447 mHandlerThread = new ServiceThread(TAG,
2448 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2449 mHandlerThread.start();
2450 mHandler = new PackageHandler(mHandlerThread.getLooper());
2451 mProcessLoggingHandler = new ProcessLoggingHandler();
2452 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2454 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2455 mInstantAppRegistry = new InstantAppRegistry(this);
2457 File dataDir = Environment.getDataDirectory();
2458 mAppInstallDir = new File(dataDir, "app");
2459 mAppLib32InstallDir = new File(dataDir, "app-lib");
2460 mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2461 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2462 sUserManager = new UserManagerService(context, this,
2463 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2465 // Propagate permission configuration in to package manager.
2466 ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2467 = systemConfig.getPermissions();
2468 for (int i=0; i<permConfig.size(); i++) {
2469 SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2470 BasePermission bp = mSettings.mPermissions.get(perm.name);
2472 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2473 mSettings.mPermissions.put(perm.name, bp);
2475 if (perm.gids != null) {
2476 bp.setGids(perm.gids, perm.perUser);
2480 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2481 final int builtInLibCount = libConfig.size();
2482 for (int i = 0; i < builtInLibCount; i++) {
2483 String name = libConfig.keyAt(i);
2484 String path = libConfig.valueAt(i);
2485 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2486 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2489 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2491 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2492 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2493 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2495 // Clean up orphaned packages for which the code path doesn't exist
2496 // and they are an update to a system app - caused by bug/32321269
2497 final int packageSettingCount = mSettings.mPackages.size();
2498 for (int i = packageSettingCount - 1; i >= 0; i--) {
2499 PackageSetting ps = mSettings.mPackages.valueAt(i);
2500 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2501 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2502 mSettings.mPackages.removeAt(i);
2503 mSettings.enableSystemPackageLPw(ps.name);
2508 requestCopyPreoptedFiles();
2511 String customResolverActivity = Resources.getSystem().getString(
2512 R.string.config_customResolverActivity);
2513 if (TextUtils.isEmpty(customResolverActivity)) {
2514 customResolverActivity = null;
2516 mCustomResolverComponentName = ComponentName.unflattenFromString(
2517 customResolverActivity);
2520 long startTime = SystemClock.uptimeMillis();
2522 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2525 final String bootClassPath = System.getenv("BOOTCLASSPATH");
2526 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2528 if (bootClassPath == null) {
2529 Slog.w(TAG, "No BOOTCLASSPATH found!");
2532 if (systemServerClassPath == null) {
2533 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2536 File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2538 final VersionInfo ver = mSettings.getInternalVersion();
2539 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2541 logCriticalInfo(Log.INFO,
2542 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2545 // when upgrading from pre-M, promote system app permissions from install to runtime
2546 mPromoteSystemApps =
2547 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2549 // When upgrading from pre-N, we need to handle package extraction like first boot,
2550 // as there is no profiling data available.
2551 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2553 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2555 // save off the names of pre-existing system packages prior to scanning; we don't
2556 // want to automatically grant runtime permissions for new system apps
2557 if (mPromoteSystemApps) {
2558 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2559 while (pkgSettingIter.hasNext()) {
2560 PackageSetting ps = pkgSettingIter.next();
2561 if (isSystemApp(ps)) {
2562 mExistingSystemPackages.add(ps.name);
2567 mCacheDir = preparePackageParserCache(mIsUpgrade);
2569 // Set flag to monitor and not change apk file paths when
2570 // scanning install directories.
2571 int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2573 if (mIsUpgrade || mFirstBoot) {
2574 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2577 // Collect vendor overlay packages. (Do this before scanning any apps.)
2578 // For security and version matching reason, only consider
2579 // overlay packages if they reside in the right directory.
2580 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2581 | PackageParser.PARSE_IS_SYSTEM
2582 | PackageParser.PARSE_IS_SYSTEM_DIR
2583 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2585 mParallelPackageParserCallback.findStaticOverlayPackages();
2587 // Find base frameworks (resource packages without code).
2588 scanDirTracedLI(frameworkDir, mDefParseFlags
2589 | PackageParser.PARSE_IS_SYSTEM
2590 | PackageParser.PARSE_IS_SYSTEM_DIR
2591 | PackageParser.PARSE_IS_PRIVILEGED,
2592 scanFlags | SCAN_NO_DEX, 0);
2594 // Collected privileged system packages.
2595 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2596 scanDirTracedLI(privilegedAppDir, mDefParseFlags
2597 | PackageParser.PARSE_IS_SYSTEM
2598 | PackageParser.PARSE_IS_SYSTEM_DIR
2599 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2601 // Collect ordinary system packages.
2602 final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2603 scanDirTracedLI(systemAppDir, mDefParseFlags
2604 | PackageParser.PARSE_IS_SYSTEM
2605 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2607 // Collect all vendor packages.
2608 File vendorAppDir = new File("/vendor/app");
2610 vendorAppDir = vendorAppDir.getCanonicalFile();
2611 } catch (IOException e) {
2612 // failed to look up canonical path, continue with original one
2614 scanDirTracedLI(vendorAppDir, mDefParseFlags
2615 | PackageParser.PARSE_IS_SYSTEM
2616 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2618 // Collect all OEM packages.
2619 final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2620 scanDirTracedLI(oemAppDir, mDefParseFlags
2621 | PackageParser.PARSE_IS_SYSTEM
2622 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2624 // Prune any system packages that no longer exist.
2625 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2627 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2628 while (psit.hasNext()) {
2629 PackageSetting ps = psit.next();
2632 * If this is not a system app, it can't be a
2633 * disable system app.
2635 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2640 * If the package is scanned, it's not erased.
2642 final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2643 if (scannedPkg != null) {
2645 * If the system app is both scanned and in the
2646 * disabled packages list, then it must have been
2647 * added via OTA. Remove it from the currently
2648 * scanned package so the previously user-installed
2649 * application can be scanned.
2651 if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2652 logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2653 + ps.name + "; removing system app. Last known codePath="
2654 + ps.codePathString + ", installStatus=" + ps.installStatus
2655 + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2656 + scannedPkg.mVersionCode);
2657 removePackageLI(scannedPkg, true);
2658 mExpectingBetter.put(ps.name, ps.codePath);
2664 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2666 logCriticalInfo(Log.WARN, "System package " + ps.name
2667 + " no longer exists; it's data will be wiped");
2668 // Actual deletion of code and data will be handled by later
2669 // reconciliation step
2671 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2672 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2673 possiblyDeletedUpdatedSystemApps.add(ps.name);
2679 //look for any incomplete package installations
2680 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2681 for (int i = 0; i < deletePkgsList.size(); i++) {
2682 // Actual deletion of code and data will be handled by later
2683 // reconciliation step
2684 final String packageName = deletePkgsList.get(i).name;
2685 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2686 synchronized (mPackages) {
2687 mSettings.removePackageLPw(packageName);
2692 deleteTempPackageFiles();
2694 // Remove any shared userIDs that have no associated packages
2695 mSettings.pruneSharedUsersLPw();
2698 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2699 SystemClock.uptimeMillis());
2700 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2702 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2703 | PackageParser.PARSE_FORWARD_LOCK,
2704 scanFlags | SCAN_REQUIRE_KNOWN, 0);
2707 * Remove disable package settings for any updated system
2708 * apps that were removed via an OTA. If they're not a
2709 * previously-updated app, remove them completely.
2710 * Otherwise, just revoke their system-level permissions.
2712 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2713 PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2714 mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2717 if (deletedPkg == null) {
2718 msg = "Updated system package " + deletedAppName
2719 + " no longer exists; it's data will be wiped";
2720 // Actual deletion of code and data will be handled by later
2721 // reconciliation step
2723 msg = "Updated system app + " + deletedAppName
2724 + " no longer present; removing system privileges for "
2727 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2729 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2730 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2732 logCriticalInfo(Log.WARN, msg);
2736 * Make sure all system apps that we expected to appear on
2737 * the userdata partition actually showed up. If they never
2738 * appeared, crawl back and revive the system version.
2740 for (int i = 0; i < mExpectingBetter.size(); i++) {
2741 final String packageName = mExpectingBetter.keyAt(i);
2742 if (!mPackages.containsKey(packageName)) {
2743 final File scanFile = mExpectingBetter.valueAt(i);
2745 logCriticalInfo(Log.WARN, "Expected better " + packageName
2746 + " but never showed up; reverting to system");
2748 int reparseFlags = mDefParseFlags;
2749 if (FileUtils.contains(privilegedAppDir, scanFile)) {
2750 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2751 | PackageParser.PARSE_IS_SYSTEM_DIR
2752 | PackageParser.PARSE_IS_PRIVILEGED;
2753 } else if (FileUtils.contains(systemAppDir, scanFile)) {
2754 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2755 | PackageParser.PARSE_IS_SYSTEM_DIR;
2756 } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2757 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2758 | PackageParser.PARSE_IS_SYSTEM_DIR;
2759 } else if (FileUtils.contains(oemAppDir, scanFile)) {
2760 reparseFlags = PackageParser.PARSE_IS_SYSTEM
2761 | PackageParser.PARSE_IS_SYSTEM_DIR;
2763 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2767 mSettings.enableSystemPackageLPw(packageName);
2770 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2771 } catch (PackageManagerException e) {
2772 Slog.e(TAG, "Failed to parse original system package: "
2778 mExpectingBetter.clear();
2780 // Resolve the storage manager.
2781 mStorageManagerPackage = getStorageManagerPackageName();
2783 // Resolve protected action filters. Only the setup wizard is allowed to
2784 // have a high priority filter for these actions.
2785 mSetupWizardPackage = getSetupWizardPackageName();
2786 if (mProtectedFilters.size() > 0) {
2787 if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2788 Slog.i(TAG, "No setup wizard;"
2789 + " All protected intents capped to priority 0");
2791 for (ActivityIntentInfo filter : mProtectedFilters) {
2792 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2793 if (DEBUG_FILTERS) {
2794 Slog.i(TAG, "Found setup wizard;"
2795 + " allow priority " + filter.getPriority() + ";"
2796 + " package: " + filter.activity.info.packageName
2797 + " activity: " + filter.activity.className
2798 + " priority: " + filter.getPriority());
2800 // skip setup wizard; allow it to keep the high priority filter
2803 if (DEBUG_FILTERS) {
2804 Slog.i(TAG, "Protected action; cap priority to 0;"
2805 + " package: " + filter.activity.info.packageName
2806 + " activity: " + filter.activity.className
2807 + " origPrio: " + filter.getPriority());
2809 filter.setPriority(0);
2812 mDeferProtectedFilters = false;
2813 mProtectedFilters.clear();
2815 // Now that we know all of the shared libraries, update all clients to have
2816 // the correct library paths.
2817 updateAllSharedLibrariesLPw(null);
2819 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2820 // NOTE: We ignore potential failures here during a system scan (like
2821 // the rest of the commands above) because there's precious little we
2822 // can do about it. A settings error is reported, though.
2823 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2826 // Now that we know all the packages we are keeping,
2827 // read and update their last usage times.
2828 mPackageUsage.read(mPackages);
2829 mCompilerStats.read();
2831 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2832 SystemClock.uptimeMillis());
2833 Slog.i(TAG, "Time to scan packages: "
2834 + ((SystemClock.uptimeMillis()-startTime)/1000f)
2837 // If the platform SDK has changed since the last time we booted,
2838 // we need to re-grant app permission to catch any new ones that
2839 // appear. This is really a hack, and means that apps can in some
2840 // cases get permissions that the user didn't initially explicitly
2841 // allow... it would be nice to have some better way to handle
2843 int updateFlags = UPDATE_PERMISSIONS_ALL;
2844 if (ver.sdkVersion != mSdkVersion) {
2845 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2846 + mSdkVersion + "; regranting permissions for internal storage");
2847 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2849 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2850 ver.sdkVersion = mSdkVersion;
2852 // If this is the first boot or an update from pre-M, and it is a normal
2853 // boot, then we need to initialize the default preferred apps across
2854 // all defined users.
2855 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2856 for (UserInfo user : sUserManager.getUsers(true)) {
2857 mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2858 applyFactoryDefaultBrowserLPw(user.id);
2859 primeDomainVerificationsLPw(user.id);
2863 // Prepare storage for system user really early during boot,
2864 // since core system apps like SettingsProvider and SystemUI
2865 // can't wait for user to start
2866 final int storageFlags;
2867 if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2868 storageFlags = StorageManager.FLAG_STORAGE_DE;
2870 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2872 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2873 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2874 true /* onlyCoreApps */);
2875 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2876 BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2877 Trace.TRACE_TAG_PACKAGE_MANAGER);
2878 traceLog.traceBegin("AppDataFixup");
2880 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2881 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2882 } catch (InstallerException e) {
2883 Slog.w(TAG, "Trouble fixing GIDs", e);
2885 traceLog.traceEnd();
2887 traceLog.traceBegin("AppDataPrepare");
2888 if (deferPackages == null || deferPackages.isEmpty()) {
2892 for (String pkgName : deferPackages) {
2893 PackageParser.Package pkg = null;
2894 synchronized (mPackages) {
2895 PackageSetting ps = mSettings.getPackageLPr(pkgName);
2896 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2901 synchronized (mInstallLock) {
2902 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2903 true /* maybeMigrateAppData */);
2908 traceLog.traceEnd();
2909 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2910 }, "prepareAppData");
2912 // If this is first boot after an OTA, and a normal boot, then
2913 // we need to clear code cache directories.
2914 // Note that we do *not* clear the application profiles. These remain valid
2915 // across OTAs and are used to drive profile verification (post OTA) and
2916 // profile compilation (without waiting to collect a fresh set of profiles).
2917 if (mIsUpgrade && !onlyCore) {
2918 Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2919 for (int i = 0; i < mSettings.mPackages.size(); i++) {
2920 final PackageSetting ps = mSettings.mPackages.valueAt(i);
2921 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2922 // No apps are running this early, so no need to freeze
2923 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2924 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2925 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2928 ver.fingerprint = Build.FINGERPRINT;
2931 checkDefaultBrowser();
2933 // clear only after permissions and other defaults have been updated
2934 mExistingSystemPackages.clear();
2935 mPromoteSystemApps = false;
2937 // All the changes are done during package scanning.
2938 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2940 // can downgrade to reader
2941 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2942 mSettings.writeLPr();
2943 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2945 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2946 SystemClock.uptimeMillis());
2949 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2950 mRequiredInstallerPackage = getRequiredInstallerLPr();
2951 mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2952 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2953 if (mIntentFilterVerifierComponent != null) {
2954 mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2955 mIntentFilterVerifierComponent);
2957 mIntentFilterVerifier = null;
2959 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2960 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2961 SharedLibraryInfo.VERSION_UNDEFINED);
2962 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2963 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2964 SharedLibraryInfo.VERSION_UNDEFINED);
2966 mRequiredVerifierPackage = null;
2967 mRequiredInstallerPackage = null;
2968 mRequiredUninstallerPackage = null;
2969 mIntentFilterVerifierComponent = null;
2970 mIntentFilterVerifier = null;
2971 mServicesSystemSharedLibraryPackageName = null;
2972 mSharedSystemSharedLibraryPackageName = null;
2975 mInstallerService = new PackageInstallerService(context, this);
2976 final Pair<ComponentName, String> instantAppResolverComponent =
2977 getInstantAppResolverLPr();
2978 if (instantAppResolverComponent != null) {
2979 if (DEBUG_EPHEMERAL) {
2980 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2982 mInstantAppResolverConnection = new EphemeralResolverConnection(
2983 mContext, instantAppResolverComponent.first,
2984 instantAppResolverComponent.second);
2985 mInstantAppResolverSettingsComponent =
2986 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2988 mInstantAppResolverConnection = null;
2989 mInstantAppResolverSettingsComponent = null;
2991 updateInstantAppInstallerLocked(null);
2993 // Read and update the usage of dex files.
2994 // Do this at the end of PM init so that all the packages have their
2995 // data directory reconciled.
2996 // At this point we know the code paths of the packages, so we can validate
2997 // the disk file and build the internal cache.
2998 // The usage file is expected to be small so loading and verifying it
2999 // should take a fairly small time compare to the other activities (e.g. package
3001 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3002 final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3003 for (int userId : currentUserIds) {
3004 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3006 mDexManager.load(userPackages);
3007 } // synchronized (mPackages)
3008 } // synchronized (mInstallLock)
3010 // Now after opening every single application zip, make sure they
3011 // are all flushed. Not really needed, but keeps things nice and
3013 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3014 Runtime.getRuntime().gc();
3015 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3017 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3018 FallbackCategoryProvider.loadFallbacks();
3019 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3021 // The initial scanning above does many calls into installd while
3022 // holding the mPackages lock, but we're mostly interested in yelling
3023 // once we have a booted system.
3024 mInstaller.setWarnIfHeld(mPackages);
3026 // Expose private service for system components to use.
3027 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3028 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3031 private void updateInstantAppInstallerLocked(String modifiedPackage) {
3032 // we're only interested in updating the installer appliction when 1) it's not
3033 // already set or 2) the modified package is the installer
3034 if (mInstantAppInstallerActivity != null
3035 && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3036 .equals(modifiedPackage)) {
3039 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3042 private static File preparePackageParserCache(boolean isUpgrade) {
3043 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3047 // Disable package parsing on eng builds to allow for faster incremental development.
3048 if ("eng".equals(Build.TYPE)) {
3052 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3053 Slog.i(TAG, "Disabling package parser cache due to system property.");
3057 // The base directory for the package parser cache lives under /data/system/.
3058 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3060 if (cacheBaseDir == null) {
3064 // If this is a system upgrade scenario, delete the contents of the package cache dir.
3065 // This also serves to "GC" unused entries when the package cache version changes (which
3066 // can only happen during upgrades).
3068 FileUtils.deleteContents(cacheBaseDir);
3072 // Return the versioned package cache directory. This is something like
3073 // "/data/system/package_cache/1"
3074 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3076 // The following is a workaround to aid development on non-numbered userdebug
3077 // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3078 // the system partition is newer.
3080 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3081 // that starts with "eng." to signify that this is an engineering build and not
3082 // destined for release.
3083 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3084 Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3086 // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3087 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3088 // in general and should not be used for production changes. In this specific case,
3089 // we know that they will work.
3090 File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3091 if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3092 FileUtils.deleteContents(cacheBaseDir);
3093 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3101 public boolean isFirstBoot() {
3102 // allow instant applications
3107 public boolean isOnlyCoreApps() {
3108 // allow instant applications
3113 public boolean isUpgrade() {
3114 // allow instant applications
3118 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3119 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3121 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3122 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3123 UserHandle.USER_SYSTEM);
3124 if (matches.size() == 1) {
3125 return matches.get(0).getComponentInfo().packageName;
3126 } else if (matches.size() == 0) {
3127 Log.e(TAG, "There should probably be a verifier, but, none were found");
3130 throw new RuntimeException("There must be exactly one verifier; found " + matches);
3133 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3134 synchronized (mPackages) {
3135 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3136 if (libraryEntry == null) {
3137 throw new IllegalStateException("Missing required shared library:" + name);
3139 return libraryEntry.apk;
3143 private @NonNull String getRequiredInstallerLPr() {
3144 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3145 intent.addCategory(Intent.CATEGORY_DEFAULT);
3146 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3148 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3149 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3150 UserHandle.USER_SYSTEM);
3151 if (matches.size() == 1) {
3152 ResolveInfo resolveInfo = matches.get(0);
3153 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3154 throw new RuntimeException("The installer must be a privileged app");
3156 return matches.get(0).getComponentInfo().packageName;
3158 throw new RuntimeException("There must be exactly one installer; found " + matches);
3162 private @NonNull String getRequiredUninstallerLPr() {
3163 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3164 intent.addCategory(Intent.CATEGORY_DEFAULT);
3165 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3167 final ResolveInfo resolveInfo = resolveIntent(intent, null,
3168 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3169 UserHandle.USER_SYSTEM);
3170 if (resolveInfo == null ||
3171 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3172 throw new RuntimeException("There must be exactly one uninstaller; found "
3175 return resolveInfo.getComponentInfo().packageName;
3178 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3179 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3181 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3182 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3183 UserHandle.USER_SYSTEM);
3184 ResolveInfo best = null;
3185 final int N = matches.size();
3186 for (int i = 0; i < N; i++) {
3187 final ResolveInfo cur = matches.get(i);
3188 final String packageName = cur.getComponentInfo().packageName;
3189 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3190 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3194 if (best == null || cur.priority > best.priority) {
3200 return best.getComponentInfo().getComponentName();
3202 Slog.w(TAG, "Intent filter verifier not found");
3207 public @Nullable ComponentName getInstantAppResolverComponent() {
3208 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3211 synchronized (mPackages) {
3212 final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3213 if (instantAppResolver == null) {
3216 return instantAppResolver.first;
3220 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3221 final String[] packageArray =
3222 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3223 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3224 if (DEBUG_EPHEMERAL) {
3225 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3230 final int callingUid = Binder.getCallingUid();
3231 final int resolveFlags =
3232 MATCH_DIRECT_BOOT_AWARE
3233 | MATCH_DIRECT_BOOT_UNAWARE
3234 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3235 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3236 final Intent resolverIntent = new Intent(actionName);
3237 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3238 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3239 // temporarily look for the old action
3240 if (resolvers.size() == 0) {
3241 if (DEBUG_EPHEMERAL) {
3242 Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3244 actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3245 resolverIntent.setAction(actionName);
3246 resolvers = queryIntentServicesInternal(resolverIntent, null,
3247 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3249 final int N = resolvers.size();
3251 if (DEBUG_EPHEMERAL) {
3252 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3257 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3258 for (int i = 0; i < N; i++) {
3259 final ResolveInfo info = resolvers.get(i);
3261 if (info.serviceInfo == null) {
3265 final String packageName = info.serviceInfo.packageName;
3266 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3267 if (DEBUG_EPHEMERAL) {
3268 Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3269 + " pkg: " + packageName + ", info:" + info);
3274 if (DEBUG_EPHEMERAL) {
3275 Slog.v(TAG, "Ephemeral resolver found;"
3276 + " pkg: " + packageName + ", info:" + info);
3278 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3280 if (DEBUG_EPHEMERAL) {
3281 Slog.v(TAG, "Ephemeral resolver NOT found");
3286 private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3287 final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3288 intent.addCategory(Intent.CATEGORY_DEFAULT);
3289 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3291 final int resolveFlags =
3292 MATCH_DIRECT_BOOT_AWARE
3293 | MATCH_DIRECT_BOOT_UNAWARE
3294 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3295 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3296 resolveFlags, UserHandle.USER_SYSTEM);
3297 // temporarily look for the old action
3298 if (matches.isEmpty()) {
3299 if (DEBUG_EPHEMERAL) {
3300 Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3302 intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3303 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3304 resolveFlags, UserHandle.USER_SYSTEM);
3306 Iterator<ResolveInfo> iter = matches.iterator();
3307 while (iter.hasNext()) {
3308 final ResolveInfo rInfo = iter.next();
3309 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3311 final PermissionsState permissionsState = ps.getPermissionsState();
3312 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3318 if (matches.size() == 0) {
3320 } else if (matches.size() == 1) {
3321 return (ActivityInfo) matches.get(0).getComponentInfo();
3323 throw new RuntimeException(
3324 "There must be at most one ephemeral installer; found " + matches);
3328 private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3329 @NonNull ComponentName resolver) {
3330 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3331 .addCategory(Intent.CATEGORY_DEFAULT)
3332 .setPackage(resolver.getPackageName());
3333 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3334 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3335 UserHandle.USER_SYSTEM);
3336 // temporarily look for the old action
3337 if (matches.isEmpty()) {
3338 if (DEBUG_EPHEMERAL) {
3339 Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3341 intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3342 matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3343 UserHandle.USER_SYSTEM);
3345 if (matches.isEmpty()) {
3348 return matches.get(0).getComponentInfo().getComponentName();
3351 private void primeDomainVerificationsLPw(int userId) {
3352 if (DEBUG_DOMAIN_VERIFICATION) {
3353 Slog.d(TAG, "Priming domain verifications in user " + userId);
3356 SystemConfig systemConfig = SystemConfig.getInstance();
3357 ArraySet<String> packages = systemConfig.getLinkedApps();
3359 for (String packageName : packages) {
3360 PackageParser.Package pkg = mPackages.get(packageName);
3362 if (!pkg.isSystemApp()) {
3363 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3367 ArraySet<String> domains = null;
3368 for (PackageParser.Activity a : pkg.activities) {
3369 for (ActivityIntentInfo filter : a.intents) {
3370 if (hasValidDomains(filter)) {
3371 if (domains == null) {
3372 domains = new ArraySet<String>();
3374 domains.addAll(filter.getHostsList());
3379 if (domains != null && domains.size() > 0) {
3380 if (DEBUG_DOMAIN_VERIFICATION) {
3381 Slog.v(TAG, " + " + packageName);
3383 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3384 // state w.r.t. the formal app-linkage "no verification attempted" state;
3385 // and then 'always' in the per-user state actually used for intent resolution.
3386 final IntentFilterVerificationInfo ivi;
3387 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3388 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3389 mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3390 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3392 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3393 + "' does not handle web links");
3396 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3400 scheduleWritePackageRestrictionsLocked(userId);
3401 scheduleWriteSettingsLocked();
3404 private void applyFactoryDefaultBrowserLPw(int userId) {
3405 // The default browser app's package name is stored in a string resource,
3406 // with a product-specific overlay used for vendor customization.
3407 String browserPkg = mContext.getResources().getString(
3408 com.android.internal.R.string.default_browser);
3409 if (!TextUtils.isEmpty(browserPkg)) {
3410 // non-empty string => required to be a known package
3411 PackageSetting ps = mSettings.mPackages.get(browserPkg);
3413 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3416 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3420 // Nothing valid explicitly set? Make the factory-installed browser the explicit
3421 // default. If there's more than one, just leave everything alone.
3422 if (browserPkg == null) {
3423 calculateDefaultBrowserLPw(userId);
3427 private void calculateDefaultBrowserLPw(int userId) {
3428 List<String> allBrowsers = resolveAllBrowserApps(userId);
3429 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3430 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3433 private List<String> resolveAllBrowserApps(int userId) {
3434 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3435 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3436 PackageManager.MATCH_ALL, userId);
3438 final int count = list.size();
3439 List<String> result = new ArrayList<String>(count);
3440 for (int i=0; i<count; i++) {
3441 ResolveInfo info = list.get(i);
3442 if (info.activityInfo == null
3443 || !info.handleAllWebDataURI
3444 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3445 || result.contains(info.activityInfo.packageName)) {
3448 result.add(info.activityInfo.packageName);
3454 private boolean packageIsBrowser(String packageName, int userId) {
3455 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3456 PackageManager.MATCH_ALL, userId);
3457 final int N = list.size();
3458 for (int i = 0; i < N; i++) {
3459 ResolveInfo info = list.get(i);
3460 if (packageName.equals(info.activityInfo.packageName)) {
3467 private void checkDefaultBrowser() {
3468 final int myUserId = UserHandle.myUserId();
3469 final String packageName = getDefaultBrowserPackageName(myUserId);
3470 if (packageName != null) {
3471 PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3473 Slog.w(TAG, "Default browser no longer installed: " + packageName);
3474 synchronized (mPackages) {
3475 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1
3482 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3483 throws RemoteException {
3485 return super.onTransact(code, data, reply, flags);
3486 } catch (RuntimeException e) {
3487 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3488 Slog.wtf(TAG, "Package Manager Crash", e);
3494 static int[] appendInts(int[] cur, int[] add) {
3495 if (add == null) return cur;
3496 if (cur == null) return add;
3497 final int N = add.length;
3498 for (int i=0; i<N; i++) {
3499 cur = appendInt(cur, add[i]);
3505 * Returns whether or not a full application can see an instant application.
3507 * Currently, there are three cases in which this can occur:
3509 * <li>The calling application is a "special" process. The special
3510 * processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3511 * and {@code 0}</li>
3512 * <li>The calling application has the permission
3513 * {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3514 * <li>The calling application is the default launcher on the
3515 * system partition.</li>
3518 private boolean canViewInstantApps(int callingUid, int userId) {
3519 if (callingUid == Process.SYSTEM_UID
3520 || callingUid == Process.SHELL_UID
3521 || callingUid == Process.ROOT_UID) {
3524 if (mContext.checkCallingOrSelfPermission(
3525 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3528 if (mContext.checkCallingOrSelfPermission(
3529 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3530 final ComponentName homeComponent = getDefaultHomeActivity(userId);
3531 if (homeComponent != null
3532 && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3539 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3540 if (!sUserManager.exists(userId)) return null;
3544 PackageParser.Package p = ps.pkg;
3548 final int callingUid = Binder.getCallingUid();
3549 // Filter out ephemeral app metadata:
3550 // * The system/shell/root can see metadata for any app
3551 // * An installed app can see metadata for 1) other installed apps
3552 // and 2) ephemeral apps that have explicitly interacted with it
3553 // * Ephemeral apps can only see their own data and exposed installed apps
3554 // * Holding a signature permission allows seeing instant apps
3555 if (filterAppAccessLPr(ps, callingUid, userId)) {
3559 final PermissionsState permissionsState = ps.getPermissionsState();
3561 // Compute GIDs only if requested
3562 final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3563 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3564 // Compute granted permissions only if package has requested permissions
3565 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3566 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3567 final PackageUserState state = ps.readUserState(userId);
3569 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3571 flags |= MATCH_ANY_USER;
3574 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3575 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3577 if (packageInfo == null) {
3581 packageInfo.packageName = packageInfo.applicationInfo.packageName =
3582 resolveExternalPackageNameLPr(p);
3588 public void checkPackageStartable(String packageName, int userId) {
3589 final int callingUid = Binder.getCallingUid();
3590 if (getInstantAppPackageName(callingUid) != null) {
3591 throw new SecurityException("Instant applications don't have access to this method");
3593 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3594 synchronized (mPackages) {
3595 final PackageSetting ps = mSettings.mPackages.get(packageName);
3596 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3597 throw new SecurityException("Package " + packageName + " was not found!");
3600 if (!ps.getInstalled(userId)) {
3601 throw new SecurityException(
3602 "Package " + packageName + " was not installed for user " + userId + "!");
3605 if (mSafeMode && !ps.isSystem()) {
3606 throw new SecurityException("Package " + packageName + " not a system app!");
3609 if (mFrozenPackages.contains(packageName)) {
3610 throw new SecurityException("Package " + packageName + " is currently frozen!");
3613 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3614 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3615 throw new SecurityException("Package " + packageName + " is not encryption aware!");
3621 public boolean isPackageAvailable(String packageName, int userId) {
3622 if (!sUserManager.exists(userId)) return false;
3623 final int callingUid = Binder.getCallingUid();
3624 enforceCrossUserPermission(callingUid, userId,
3625 false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3626 synchronized (mPackages) {
3627 PackageParser.Package p = mPackages.get(packageName);
3629 final PackageSetting ps = (PackageSetting) p.mExtras;
3630 if (filterAppAccessLPr(ps, callingUid, userId)) {
3634 final PackageUserState state = ps.readUserState(userId);
3635 if (state != null) {
3636 return PackageParser.isAvailable(state);
3645 public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3646 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3647 flags, Binder.getCallingUid(), userId);
3651 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3652 int flags, int userId) {
3653 return getPackageInfoInternal(versionedPackage.getPackageName(),
3654 versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3658 * Important: The provided filterCallingUid is used exclusively to filter out packages
3659 * that can be seen based on user state. It's typically the original caller uid prior
3660 * to clearing. Because it can only be provided by trusted code, it's value can be
3661 * trusted and will be used as-is; unlike userId which will be validated by this method.
3663 private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3664 int flags, int filterCallingUid, int userId) {
3665 if (!sUserManager.exists(userId)) return null;
3666 flags = updateFlagsForPackage(flags, userId, packageName);
3667 enforceCrossUserPermission(Binder.getCallingUid(), userId,
3668 false /* requireFullPermission */, false /* checkShell */, "get package info");
3671 synchronized (mPackages) {
3672 // Normalize package name to handle renamed packages and static libs
3673 packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3675 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3676 if (matchFactoryOnly) {
3677 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3679 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3682 if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3685 return generatePackageInfo(ps, flags, userId);
3689 PackageParser.Package p = mPackages.get(packageName);
3690 if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3693 if (DEBUG_PACKAGE_INFO)
3694 Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3696 final PackageSetting ps = (PackageSetting) p.mExtras;
3697 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3700 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3703 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3705 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3706 final PackageSetting ps = mSettings.mPackages.get(packageName);
3707 if (ps == null) return null;
3708 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3711 if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3714 return generatePackageInfo(ps, flags, userId);
3720 private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3721 if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3724 if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3727 if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3733 private boolean isComponentVisibleToInstantApp(
3734 @Nullable ComponentName component, @ComponentType int type) {
3735 if (type == TYPE_ACTIVITY) {
3736 final PackageParser.Activity activity = mActivities.mActivities.get(component);
3737 return activity != null
3738 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3740 } else if (type == TYPE_RECEIVER) {
3741 final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3742 return activity != null
3743 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3745 } else if (type == TYPE_SERVICE) {
3746 final PackageParser.Service service = mServices.mServices.get(component);
3747 return service != null
3748 ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3750 } else if (type == TYPE_PROVIDER) {
3751 final PackageParser.Provider provider = mProviders.mProviders.get(component);
3752 return provider != null
3753 ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3755 } else if (type == TYPE_UNKNOWN) {
3756 return isComponentVisibleToInstantApp(component);
3762 * Returns whether or not access to the application should be filtered.
3764 * Access may be limited based upon whether the calling or target applications
3765 * are instant applications.
3767 * @see #canAccessInstantApps(int)
3769 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3770 @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3771 // if we're in an isolated process, get the real calling UID
3772 if (Process.isIsolated(callingUid)) {
3773 callingUid = mIsolatedOwners.get(callingUid);
3775 final String instantAppPkgName = getInstantAppPackageName(callingUid);
3776 final boolean callerIsInstantApp = instantAppPkgName != null;
3778 if (callerIsInstantApp) {
3779 // pretend the application exists, but, needs to be filtered
3784 // if the target and caller are the same application, don't filter
3785 if (isCallerSameApp(ps.name, callingUid)) {
3788 if (callerIsInstantApp) {
3789 // request for a specific component; if it hasn't been explicitly exposed, filter
3790 if (component != null) {
3791 return !isComponentVisibleToInstantApp(component, componentType);
3793 // request for application; if no components have been explicitly exposed, filter
3794 return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3796 if (ps.getInstantApp(userId)) {
3797 // caller can see all components of all instant applications, don't filter
3798 if (canViewInstantApps(callingUid, userId)) {
3801 // request for a specific instant application component, filter
3802 if (component != null) {
3805 // request for an instant application; if the caller hasn't been granted access, filter
3806 return !mInstantAppRegistry.isInstantAccessGranted(
3807 userId, UserHandle.getAppId(callingUid), ps.appId);
3813 * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3815 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3816 return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3819 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3821 // Callers can access only the libs they depend on, otherwise they need to explicitly
3822 // ask for the shared libraries given the caller is allowed to access all static libs.
3823 if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3824 // System/shell/root get to see all static libs
3825 final int appId = UserHandle.getAppId(uid);
3826 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3827 || appId == Process.ROOT_UID) {
3832 // No package means no static lib as it is always on internal storage
3833 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3837 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3838 ps.pkg.staticSharedLibVersion);
3839 if (libEntry == null) {
3843 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3844 final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3845 if (uidPackageNames == null) {
3849 for (String uidPackageName : uidPackageNames) {
3850 if (ps.name.equals(uidPackageName)) {
3853 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3854 if (uidPs != null) {
3855 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3856 libEntry.info.getName());
3860 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3869 public String[] currentToCanonicalPackageNames(String[] names) {
3870 final int callingUid = Binder.getCallingUid();
3871 if (getInstantAppPackageName(callingUid) != null) {
3874 final String[] out = new String[names.length];
3876 synchronized (mPackages) {
3877 final int callingUserId = UserHandle.getUserId(callingUid);
3878 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3879 for (int i=names.length-1; i>=0; i--) {
3880 final PackageSetting ps = mSettings.mPackages.get(names[i]);
3881 boolean translateName = false;
3882 if (ps != null && ps.realName != null) {
3883 final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3884 translateName = !targetIsInstantApp
3885 || canViewInstantApps
3886 || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3887 UserHandle.getAppId(callingUid), ps.appId);
3889 out[i] = translateName ? ps.realName : names[i];
3896 public String[] canonicalToCurrentPackageNames(String[] names) {
3897 final int callingUid = Binder.getCallingUid();
3898 if (getInstantAppPackageName(callingUid) != null) {
3901 final String[] out = new String[names.length];
3903 synchronized (mPackages) {
3904 final int callingUserId = UserHandle.getUserId(callingUid);
3905 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3906 for (int i=names.length-1; i>=0; i--) {
3907 final String cur = mSettings.getRenamedPackageLPr(names[i]);
3908 boolean translateName = false;
3910 final PackageSetting ps = mSettings.mPackages.get(names[i]);
3911 final boolean targetIsInstantApp =
3912 ps != null && ps.getInstantApp(callingUserId);
3913 translateName = !targetIsInstantApp
3914 || canViewInstantApps
3915 || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3916 UserHandle.getAppId(callingUid), ps.appId);
3918 out[i] = translateName ? cur : names[i];
3925 public int getPackageUid(String packageName, int flags, int userId) {
3926 if (!sUserManager.exists(userId)) return -1;
3927 final int callingUid = Binder.getCallingUid();
3928 flags = updateFlagsForPackage(flags, userId, packageName);
3929 enforceCrossUserPermission(callingUid, userId,
3930 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3933 synchronized (mPackages) {
3934 final PackageParser.Package p = mPackages.get(packageName);
3935 if (p != null && p.isMatch(flags)) {
3936 PackageSetting ps = (PackageSetting) p.mExtras;
3937 if (filterAppAccessLPr(ps, callingUid, userId)) {
3940 return UserHandle.getUid(userId, p.applicationInfo.uid);
3942 if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3943 final PackageSetting ps = mSettings.mPackages.get(packageName);
3944 if (ps != null && ps.isMatch(flags)
3945 && !filterAppAccessLPr(ps, callingUid, userId)) {
3946 return UserHandle.getUid(userId, ps.appId);
3955 public int[] getPackageGids(String packageName, int flags, int userId) {
3956 if (!sUserManager.exists(userId)) return null;
3957 final int callingUid = Binder.getCallingUid();
3958 flags = updateFlagsForPackage(flags, userId, packageName);
3959 enforceCrossUserPermission(callingUid, userId,
3960 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3963 synchronized (mPackages) {
3964 final PackageParser.Package p = mPackages.get(packageName);
3965 if (p != null && p.isMatch(flags)) {
3966 PackageSetting ps = (PackageSetting) p.mExtras;
3967 if (filterAppAccessLPr(ps, callingUid, userId)) {
3970 // TODO: Shouldn't this be checking for package installed state for userId and
3972 return ps.getPermissionsState().computeGids(userId);
3974 if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3975 final PackageSetting ps = mSettings.mPackages.get(packageName);
3976 if (ps != null && ps.isMatch(flags)
3977 && !filterAppAccessLPr(ps, callingUid, userId)) {
3978 return ps.getPermissionsState().computeGids(userId);
3986 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3987 if (bp.perm != null) {
3988 return PackageParser.generatePermissionInfo(bp.perm, flags);
3990 PermissionInfo pi = new PermissionInfo();
3992 pi.packageName = bp.sourcePackage;
3993 pi.nonLocalizedLabel = bp.name;
3994 pi.protectionLevel = bp.protectionLevel;
3999 public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4000 final int callingUid = Binder.getCallingUid();
4001 if (getInstantAppPackageName(callingUid) != null) {
4005 synchronized (mPackages) {
4006 final BasePermission p = mSettings.mPermissions.get(name);
4010 // If the caller is an app that targets pre 26 SDK drop protection flags.
4011 final PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4012 if (permissionInfo != null) {
4013 permissionInfo.protectionLevel = adjustPermissionProtectionFlagsLPr(
4014 permissionInfo.protectionLevel, packageName, callingUid);
4016 return permissionInfo;
4020 private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4021 String packageName, int uid) {
4022 // Signature permission flags area always reported
4023 final int protectionLevelMasked = protectionLevel
4024 & (PermissionInfo.PROTECTION_NORMAL
4025 | PermissionInfo.PROTECTION_DANGEROUS
4026 | PermissionInfo.PROTECTION_SIGNATURE);
4027 if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4028 return protectionLevel;
4031 // System sees all flags.
4032 final int appId = UserHandle.getAppId(uid);
4033 if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4034 || appId == Process.SHELL_UID) {
4035 return protectionLevel;
4038 // Normalize package name to handle renamed packages and static libs
4039 packageName = resolveInternalPackageNameLPr(packageName,
4040 PackageManager.VERSION_CODE_HIGHEST);
4042 // Apps that target O see flags for all protection levels.
4043 final PackageSetting ps = mSettings.mPackages.get(packageName);
4045 return protectionLevel;
4047 if (ps.appId != appId) {
4048 return protectionLevel;
4051 final PackageParser.Package pkg = mPackages.get(packageName);
4053 return protectionLevel;
4055 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4056 return protectionLevelMasked;
4059 return protectionLevel;
4063 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4065 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4069 synchronized (mPackages) {
4070 if (group != null && !mPermissionGroups.containsKey(group)) {
4071 // This is thrown as NameNotFoundException
4075 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4076 for (BasePermission p : mSettings.mPermissions.values()) {
4077 if (group == null) {
4078 if (p.perm == null || p.perm.info.group == null) {
4079 out.add(generatePermissionInfo(p, flags));
4082 if (p.perm != null && group.equals(p.perm.info.group)) {
4083 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4087 return new ParceledListSlice<>(out);
4092 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4093 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4097 synchronized (mPackages) {
4098 return PackageParser.generatePermissionGroupInfo(
4099 mPermissionGroups.get(name), flags);
4104 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4105 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4106 return ParceledListSlice.emptyList();
4109 synchronized (mPackages) {
4110 final int N = mPermissionGroups.size();
4111 ArrayList<PermissionGroupInfo> out
4112 = new ArrayList<PermissionGroupInfo>(N);
4113 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4114 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4116 return new ParceledListSlice<>(out);
4120 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4121 int filterCallingUid, int userId) {
4122 if (!sUserManager.exists(userId)) return null;
4123 PackageSetting ps = mSettings.mPackages.get(packageName);
4125 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4128 if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4131 if (ps.pkg == null) {
4132 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4133 if (pInfo != null) {
4134 return pInfo.applicationInfo;
4138 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4139 ps.readUserState(userId), userId);
4141 ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4149 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4150 return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4154 * Important: The provided filterCallingUid is used exclusively to filter out applications
4155 * that can be seen based on user state. It's typically the original caller uid prior
4156 * to clearing. Because it can only be provided by trusted code, it's value can be
4157 * trusted and will be used as-is; unlike userId which will be validated by this method.
4159 private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4160 int filterCallingUid, int userId) {
4161 if (!sUserManager.exists(userId)) return null;
4162 flags = updateFlagsForApplication(flags, userId, packageName);
4163 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4164 false /* requireFullPermission */, false /* checkShell */, "get application info");
4167 synchronized (mPackages) {
4168 // Normalize package name to handle renamed packages and static libs
4169 packageName = resolveInternalPackageNameLPr(packageName,
4170 PackageManager.VERSION_CODE_HIGHEST);
4172 PackageParser.Package p = mPackages.get(packageName);
4173 if (DEBUG_PACKAGE_INFO) Log.v(
4174 TAG, "getApplicationInfo " + packageName
4177 PackageSetting ps = mSettings.mPackages.get(packageName);
4178 if (ps == null) return null;
4179 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4182 if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4185 // Note: isEnabledLP() does not apply here - always return info
4186 ApplicationInfo ai = PackageParser.generateApplicationInfo(
4187 p, flags, ps.readUserState(userId), userId);
4189 ai.packageName = resolveExternalPackageNameLPr(p);
4193 if ("android".equals(packageName)||"system".equals(packageName)) {
4194 return mAndroidApplication;
4196 if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4197 // Already generates the external package name
4198 return generateApplicationInfoFromSettingsLPw(packageName,
4199 flags, filterCallingUid, userId);
4205 private String normalizePackageNameLPr(String packageName) {
4206 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4207 return normalizedPackageName != null ? normalizedPackageName : packageName;
4211 public void deletePreloadsFileCache() {
4212 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4213 throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4215 File dir = Environment.getDataPreloadsFileCacheDirectory();
4216 Slog.i(TAG, "Deleting preloaded file cache " + dir);
4217 FileUtils.deleteContents(dir);
4221 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4222 final int storageFlags, final IPackageDataObserver observer) {
4223 mContext.enforceCallingOrSelfPermission(
4224 android.Manifest.permission.CLEAR_APP_CACHE, null);
4225 mHandler.post(() -> {
4226 boolean success = false;
4228 freeStorage(volumeUuid, freeStorageSize, storageFlags);
4230 } catch (IOException e) {
4233 if (observer != null) {
4235 observer.onRemoveCompleted(null, success);
4236 } catch (RemoteException e) {
4244 public void freeStorage(final String volumeUuid, final long freeStorageSize,
4245 final int storageFlags, final IntentSender pi) {
4246 mContext.enforceCallingOrSelfPermission(
4247 android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4248 mHandler.post(() -> {
4249 boolean success = false;
4251 freeStorage(volumeUuid, freeStorageSize, storageFlags);
4253 } catch (IOException e) {
4258 pi.sendIntent(null, success ? 1 : 0, null, null, null);
4259 } catch (SendIntentException e) {
4267 * Blocking call to clear various types of cached data across the system
4268 * until the requested bytes are available.
4270 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4271 final StorageManager storage = mContext.getSystemService(StorageManager.class);
4272 final File file = storage.findPathForUuid(volumeUuid);
4273 if (file.getUsableSpace() >= bytes) return;
4275 if (ENABLE_FREE_CACHE_V2) {
4276 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4278 final boolean aggressive = (storageFlags
4279 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4280 final boolean defyReserved = (storageFlags
4281 & StorageManager.FLAG_ALLOCATE_DEFY_RESERVED) != 0;
4282 final long reservedBytes = (aggressive || defyReserved) ? 0
4283 : storage.getStorageCacheBytes(file);
4285 // 1. Pre-flight to determine if we have any chance to succeed
4286 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4287 if (internalVolume && (aggressive || SystemProperties
4288 .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4289 deletePreloadsFileCache();
4290 if (file.getUsableSpace() >= bytes) return;
4293 // 3. Consider parsed APK data (aggressive only)
4294 if (internalVolume && aggressive) {
4295 FileUtils.deleteContents(mCacheDir);
4296 if (file.getUsableSpace() >= bytes) return;
4299 // 4. Consider cached app data (above quotas)
4301 mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4302 Installer.FLAG_FREE_CACHE_V2);
4303 } catch (InstallerException ignored) {
4305 if (file.getUsableSpace() >= bytes) return;
4307 // 5. Consider shared libraries with refcount=0 and age>min cache period
4308 if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4309 android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4310 Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4311 DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4315 // 6. Consider dexopt output (aggressive only)
4318 // 7. Consider installed instant apps unused longer than min cache period
4319 if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4320 android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4321 Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4322 InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4326 // 8. Consider cached app data (below quotas)
4328 mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4329 Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4330 } catch (InstallerException ignored) {
4332 if (file.getUsableSpace() >= bytes) return;
4334 // 9. Consider DropBox entries
4337 // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4338 if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4339 android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4340 Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4341 InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4346 mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4347 } catch (InstallerException ignored) {
4349 if (file.getUsableSpace() >= bytes) return;
4352 throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4355 private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4356 throws IOException {
4357 final StorageManager storage = mContext.getSystemService(StorageManager.class);
4358 final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4360 List<VersionedPackage> packagesToDelete = null;
4361 final long now = System.currentTimeMillis();
4363 synchronized (mPackages) {
4364 final int[] allUsers = sUserManager.getUserIds();
4365 final int libCount = mSharedLibraries.size();
4366 for (int i = 0; i < libCount; i++) {
4367 final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4368 if (versionedLib == null) {
4371 final int versionCount = versionedLib.size();
4372 for (int j = 0; j < versionCount; j++) {
4373 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4374 // Skip packages that are not static shared libs.
4375 if (!libInfo.isStatic()) {
4378 // Important: We skip static shared libs used for some user since
4379 // in such a case we need to keep the APK on the device. The check for
4380 // a lib being used for any user is performed by the uninstall call.
4381 final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4382 // Resolve the package name - we use synthetic package names internally
4383 final String internalPackageName = resolveInternalPackageNameLPr(
4384 declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4385 final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4386 // Skip unused static shared libs cached less than the min period
4387 // to prevent pruning a lib needed by a subsequently installed package.
4388 if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4391 if (packagesToDelete == null) {
4392 packagesToDelete = new ArrayList<>();
4394 packagesToDelete.add(new VersionedPackage(internalPackageName,
4395 declaringPackage.getVersionCode()));
4400 if (packagesToDelete != null) {
4401 final int packageCount = packagesToDelete.size();
4402 for (int i = 0; i < packageCount; i++) {
4403 final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4404 // Delete the package synchronously (will fail of the lib used for any user).
4405 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4406 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4407 == PackageManager.DELETE_SUCCEEDED) {
4408 if (volume.getUsableSpace() >= neededSpace) {
4419 * Update given flags based on encryption status of current user.
4421 private int updateFlags(int flags, int userId) {
4422 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4423 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4424 // Caller expressed an explicit opinion about what encryption
4425 // aware/unaware components they want to see, so fall through and
4426 // give them what they want
4428 // Caller expressed no opinion, so match based on user state
4429 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4430 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4432 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4438 private UserManagerInternal getUserManagerInternal() {
4439 if (mUserManagerInternal == null) {
4440 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4442 return mUserManagerInternal;
4445 private DeviceIdleController.LocalService getDeviceIdleController() {
4446 if (mDeviceIdleController == null) {
4447 mDeviceIdleController =
4448 LocalServices.getService(DeviceIdleController.LocalService.class);
4450 return mDeviceIdleController;
4454 * Update given flags when being used to request {@link PackageInfo}.
4456 private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4457 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4458 boolean triaged = true;
4459 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4460 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4461 // Caller is asking for component details, so they'd better be
4462 // asking for specific encryption matching behavior, or be triaged
4463 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4464 | PackageManager.MATCH_DIRECT_BOOT_AWARE
4465 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4469 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4470 | PackageManager.MATCH_SYSTEM_ONLY
4471 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4474 if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4475 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4476 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4477 + Debug.getCallers(5));
4478 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4479 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4480 // If the caller wants all packages and has a restricted profile associated with it,
4481 // then match all users. This is to make sure that launchers that need to access work
4482 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4483 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4484 flags |= PackageManager.MATCH_ANY_USER;
4486 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4487 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4488 + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4490 return updateFlags(flags, userId);
4494 * Update given flags when being used to request {@link ApplicationInfo}.
4496 private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4497 return updateFlagsForPackage(flags, userId, cookie);
4501 * Update given flags when being used to request {@link ComponentInfo}.
4503 private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4504 if (cookie instanceof Intent) {
4505 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4506 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4510 boolean triaged = true;
4511 // Caller is asking for component details, so they'd better be
4512 // asking for specific encryption matching behavior, or be triaged
4513 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4514 | PackageManager.MATCH_DIRECT_BOOT_AWARE
4515 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4518 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4519 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4520 + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4523 return updateFlags(flags, userId);
4527 * Update given intent when being used to request {@link ResolveInfo}.
4529 private Intent updateIntentForResolve(Intent intent) {
4530 if (intent.getSelector() != null) {
4531 intent = intent.getSelector();
4533 if (DEBUG_PREFERRED) {
4534 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4540 * Update given flags when being used to request {@link ResolveInfo}.
4541 * <p>Instant apps are resolved specially, depending upon context. Minimally,
4542 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4543 * flag set. However, this flag is only honoured in three circumstances:
4545 * <li>when called from a system process</li>
4546 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4547 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4548 * action and a {@code android.intent.category.BROWSABLE} category</li>
4551 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4552 return updateFlagsForResolve(flags, userId, intent, callingUid,
4553 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4555 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4556 boolean wantInstantApps) {
4557 return updateFlagsForResolve(flags, userId, intent, callingUid,
4558 wantInstantApps, false /*onlyExposedExplicitly*/);
4560 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4561 boolean wantInstantApps, boolean onlyExposedExplicitly) {
4562 // Safe mode means we shouldn't match any third-party components
4564 flags |= PackageManager.MATCH_SYSTEM_ONLY;
4566 if (getInstantAppPackageName(callingUid) != null) {
4567 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4568 if (onlyExposedExplicitly) {
4569 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4571 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4572 flags |= PackageManager.MATCH_INSTANT;
4574 final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4575 final boolean allowMatchInstant =
4577 && Intent.ACTION_VIEW.equals(intent.getAction())
4578 && hasWebURI(intent))
4579 || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4580 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4581 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4582 if (!allowMatchInstant) {
4583 flags &= ~PackageManager.MATCH_INSTANT;
4586 return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4590 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4591 return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4595 * Important: The provided filterCallingUid is used exclusively to filter out activities
4596 * that can be seen based on user state. It's typically the original caller uid prior
4597 * to clearing. Because it can only be provided by trusted code, it's value can be
4598 * trusted and will be used as-is; unlike userId which will be validated by this method.
4600 private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4601 int filterCallingUid, int userId) {
4602 if (!sUserManager.exists(userId)) return null;
4603 flags = updateFlagsForComponent(flags, userId, component);
4604 enforceCrossUserPermission(Binder.getCallingUid(), userId,
4605 false /* requireFullPermission */, false /* checkShell */, "get activity info");
4606 synchronized (mPackages) {
4607 PackageParser.Activity a = mActivities.mActivities.get(component);
4609 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4610 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4611 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4612 if (ps == null) return null;
4613 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4616 return PackageParser.generateActivityInfo(
4617 a, flags, ps.readUserState(userId), userId);
4619 if (mResolveComponentName.equals(component)) {
4620 return PackageParser.generateActivityInfo(
4621 mResolveActivity, flags, new PackageUserState(), userId);
4628 public boolean activitySupportsIntent(ComponentName component, Intent intent,
4629 String resolvedType) {
4630 synchronized (mPackages) {
4631 if (component.equals(mResolveComponentName)) {
4632 // The resolver supports EVERYTHING!
4635 final int callingUid = Binder.getCallingUid();
4636 final int callingUserId = UserHandle.getUserId(callingUid);
4637 PackageParser.Activity a = mActivities.mActivities.get(component);
4641 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4645 if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4648 for (int i=0; i<a.intents.size(); i++) {
4649 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4650 intent.getData(), intent.getCategories(), TAG) >= 0) {
4659 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4660 if (!sUserManager.exists(userId)) return null;
4661 final int callingUid = Binder.getCallingUid();
4662 flags = updateFlagsForComponent(flags, userId, component);
4663 enforceCrossUserPermission(callingUid, userId,
4664 false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4665 synchronized (mPackages) {
4666 PackageParser.Activity a = mReceivers.mActivities.get(component);
4667 if (DEBUG_PACKAGE_INFO) Log.v(
4668 TAG, "getReceiverInfo " + component + ": " + a);
4669 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4670 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4671 if (ps == null) return null;
4672 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4675 return PackageParser.generateActivityInfo(
4676 a, flags, ps.readUserState(userId), userId);
4683 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4684 int flags, int userId) {
4685 if (!sUserManager.exists(userId)) return null;
4686 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4687 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4691 flags = updateFlagsForPackage(flags, userId, null);
4693 final boolean canSeeStaticLibraries =
4694 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4695 == PERMISSION_GRANTED
4696 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4697 == PERMISSION_GRANTED
4698 || canRequestPackageInstallsInternal(packageName,
4699 PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4700 false /* throwIfPermNotDeclared*/)
4701 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4702 == PERMISSION_GRANTED;
4704 synchronized (mPackages) {
4705 List<SharedLibraryInfo> result = null;
4707 final int libCount = mSharedLibraries.size();
4708 for (int i = 0; i < libCount; i++) {
4709 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4710 if (versionedLib == null) {
4714 final int versionCount = versionedLib.size();
4715 for (int j = 0; j < versionCount; j++) {
4716 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4717 if (!canSeeStaticLibraries && libInfo.isStatic()) {
4720 final long identity = Binder.clearCallingIdentity();
4722 PackageInfo packageInfo = getPackageInfoVersioned(
4723 libInfo.getDeclaringPackage(), flags
4724 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4725 if (packageInfo == null) {
4729 Binder.restoreCallingIdentity(identity);
4732 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4733 libInfo.getVersion(), libInfo.getType(),
4734 libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4737 if (result == null) {
4738 result = new ArrayList<>();
4740 result.add(resLibInfo);
4744 return result != null ? new ParceledListSlice<>(result) : null;
4748 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4749 SharedLibraryInfo libInfo, int flags, int userId) {
4750 List<VersionedPackage> versionedPackages = null;
4751 final int packageCount = mSettings.mPackages.size();
4752 for (int i = 0; i < packageCount; i++) {
4753 PackageSetting ps = mSettings.mPackages.valueAt(i);
4759 if (!ps.getUserState().get(userId).isAvailable(flags)) {
4763 final String libName = libInfo.getName();
4764 if (libInfo.isStatic()) {
4765 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4769 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4772 if (versionedPackages == null) {
4773 versionedPackages = new ArrayList<>();
4775 // If the dependent is a static shared lib, use the public package name
4776 String dependentPackageName = ps.name;
4777 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4778 dependentPackageName = ps.pkg.manifestPackageName;
4780 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4781 } else if (ps.pkg != null) {
4782 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4783 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4784 if (versionedPackages == null) {
4785 versionedPackages = new ArrayList<>();
4787 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4792 return versionedPackages;
4796 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4797 if (!sUserManager.exists(userId)) return null;
4798 final int callingUid = Binder.getCallingUid();
4799 flags = updateFlagsForComponent(flags, userId, component);
4800 enforceCrossUserPermission(callingUid, userId,
4801 false /* requireFullPermission */, false /* checkShell */, "get service info");
4802 synchronized (mPackages) {
4803 PackageParser.Service s = mServices.mServices.get(component);
4804 if (DEBUG_PACKAGE_INFO) Log.v(
4805 TAG, "getServiceInfo " + component + ": " + s);
4806 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4807 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4808 if (ps == null) return null;
4809 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4812 return PackageParser.generateServiceInfo(
4813 s, flags, ps.readUserState(userId), userId);
4820 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4821 if (!sUserManager.exists(userId)) return null;
4822 final int callingUid = Binder.getCallingUid();
4823 flags = updateFlagsForComponent(flags, userId, component);
4824 enforceCrossUserPermission(callingUid, userId,
4825 false /* requireFullPermission */, false /* checkShell */, "get provider info");
4826 synchronized (mPackages) {
4827 PackageParser.Provider p = mProviders.mProviders.get(component);
4828 if (DEBUG_PACKAGE_INFO) Log.v(
4829 TAG, "getProviderInfo " + component + ": " + p);
4830 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4831 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4832 if (ps == null) return null;
4833 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4836 return PackageParser.generateProviderInfo(
4837 p, flags, ps.readUserState(userId), userId);
4844 public String[] getSystemSharedLibraryNames() {
4845 // allow instant applications
4846 synchronized (mPackages) {
4847 Set<String> libs = null;
4848 final int libCount = mSharedLibraries.size();
4849 for (int i = 0; i < libCount; i++) {
4850 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4851 if (versionedLib == null) {
4854 final int versionCount = versionedLib.size();
4855 for (int j = 0; j < versionCount; j++) {
4856 SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4857 if (!libEntry.info.isStatic()) {
4859 libs = new ArraySet<>();
4861 libs.add(libEntry.info.getName());
4864 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4865 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4866 UserHandle.getUserId(Binder.getCallingUid()),
4867 PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4869 libs = new ArraySet<>();
4871 libs.add(libEntry.info.getName());
4878 String[] libsArray = new String[libs.size()];
4879 libs.toArray(libsArray);
4888 public @NonNull String getServicesSystemSharedLibraryPackageName() {
4889 // allow instant applications
4890 synchronized (mPackages) {
4891 return mServicesSystemSharedLibraryPackageName;
4896 public @NonNull String getSharedSystemSharedLibraryPackageName() {
4897 // allow instant applications
4898 synchronized (mPackages) {
4899 return mSharedSystemSharedLibraryPackageName;
4903 private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4904 for (int i = userList.length - 1; i >= 0; --i) {
4905 final int userId = userList[i];
4906 // don't add instant app to the list of updates
4907 if (pkgSetting.getInstantApp(userId)) {
4910 SparseArray<String> changedPackages = mChangedPackages.get(userId);
4911 if (changedPackages == null) {
4912 changedPackages = new SparseArray<>();
4913 mChangedPackages.put(userId, changedPackages);
4915 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4916 if (sequenceNumbers == null) {
4917 sequenceNumbers = new HashMap<>();
4918 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4920 final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4921 if (sequenceNumber != null) {
4922 changedPackages.remove(sequenceNumber);
4924 changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4925 sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4927 mChangedPackagesSequenceNumber++;
4931 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4932 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4935 synchronized (mPackages) {
4936 if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4939 final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4940 if (changedPackages == null) {
4943 final List<String> packageNames =
4944 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4945 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4946 final String packageName = changedPackages.get(i);
4947 if (packageName != null) {
4948 packageNames.add(packageName);
4951 return packageNames.isEmpty()
4952 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4957 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4958 // allow instant applications
4959 ArrayList<FeatureInfo> res;
4960 synchronized (mAvailableFeatures) {
4961 res = new ArrayList<>(mAvailableFeatures.size() + 1);
4962 res.addAll(mAvailableFeatures.values());
4964 final FeatureInfo fi = new FeatureInfo();
4965 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4966 FeatureInfo.GL_ES_VERSION_UNDEFINED);
4969 return new ParceledListSlice<>(res);
4973 public boolean hasSystemFeature(String name, int version) {
4974 // allow instant applications
4975 synchronized (mAvailableFeatures) {
4976 final FeatureInfo feat = mAvailableFeatures.get(name);
4980 return feat.version >= version;
4986 public int checkPermission(String permName, String pkgName, int userId) {
4987 if (!sUserManager.exists(userId)) {
4988 return PackageManager.PERMISSION_DENIED;
4990 final int callingUid = Binder.getCallingUid();
4992 synchronized (mPackages) {
4993 final PackageParser.Package p = mPackages.get(pkgName);
4994 if (p != null && p.mExtras != null) {
4995 final PackageSetting ps = (PackageSetting) p.mExtras;
4996 if (filterAppAccessLPr(ps, callingUid, userId)) {
4997 return PackageManager.PERMISSION_DENIED;
4999 final boolean instantApp = ps.getInstantApp(userId);
5000 final PermissionsState permissionsState = ps.getPermissionsState();
5001 if (permissionsState.hasPermission(permName, userId)) {
5003 BasePermission bp = mSettings.mPermissions.get(permName);
5004 if (bp != null && bp.isInstant()) {
5005 return PackageManager.PERMISSION_GRANTED;
5008 return PackageManager.PERMISSION_GRANTED;
5011 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5012 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5013 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5014 return PackageManager.PERMISSION_GRANTED;
5019 return PackageManager.PERMISSION_DENIED;
5023 public int checkUidPermission(String permName, int uid) {
5024 final int callingUid = Binder.getCallingUid();
5025 final int callingUserId = UserHandle.getUserId(callingUid);
5026 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5027 final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5028 final int userId = UserHandle.getUserId(uid);
5029 if (!sUserManager.exists(userId)) {
5030 return PackageManager.PERMISSION_DENIED;
5033 synchronized (mPackages) {
5034 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5036 if (obj instanceof SharedUserSetting) {
5037 if (isCallerInstantApp) {
5038 return PackageManager.PERMISSION_DENIED;
5040 } else if (obj instanceof PackageSetting) {
5041 final PackageSetting ps = (PackageSetting) obj;
5042 if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5043 return PackageManager.PERMISSION_DENIED;
5046 final SettingBase settingBase = (SettingBase) obj;
5047 final PermissionsState permissionsState = settingBase.getPermissionsState();
5048 if (permissionsState.hasPermission(permName, userId)) {
5049 if (isUidInstantApp) {
5050 BasePermission bp = mSettings.mPermissions.get(permName);
5051 if (bp != null && bp.isInstant()) {
5052 return PackageManager.PERMISSION_GRANTED;
5055 return PackageManager.PERMISSION_GRANTED;
5058 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5059 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5060 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5061 return PackageManager.PERMISSION_GRANTED;
5064 ArraySet<String> perms = mSystemPermissions.get(uid);
5065 if (perms != null) {
5066 if (perms.contains(permName)) {
5067 return PackageManager.PERMISSION_GRANTED;
5069 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5070 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5071 return PackageManager.PERMISSION_GRANTED;
5077 return PackageManager.PERMISSION_DENIED;
5081 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5082 if (UserHandle.getCallingUserId() != userId) {
5083 mContext.enforceCallingPermission(
5084 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5085 "isPermissionRevokedByPolicy for user " + userId);
5088 if (checkPermission(permission, packageName, userId)
5089 == PackageManager.PERMISSION_GRANTED) {
5093 final int callingUid = Binder.getCallingUid();
5094 if (getInstantAppPackageName(callingUid) != null) {
5095 if (!isCallerSameApp(packageName, callingUid)) {
5099 if (isInstantApp(packageName, userId)) {
5104 final long identity = Binder.clearCallingIdentity();
5106 final int flags = getPermissionFlags(permission, packageName, userId);
5107 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5109 Binder.restoreCallingIdentity(identity);
5114 public String getPermissionControllerPackageName() {
5115 synchronized (mPackages) {
5116 return mRequiredInstallerPackage;
5121 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5122 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5123 * @param checkShell whether to prevent shell from access if there's a debugging restriction
5124 * @param message the message to log on security exception
5126 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5127 boolean checkShell, String message) {
5129 throw new IllegalArgumentException("Invalid userId " + userId);
5132 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5134 if (userId == UserHandle.getUserId(callingUid)) return;
5135 if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5136 if (requireFullPermission) {
5137 mContext.enforceCallingOrSelfPermission(
5138 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5141 mContext.enforceCallingOrSelfPermission(
5142 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5143 } catch (SecurityException se) {
5144 mContext.enforceCallingOrSelfPermission(
5145 android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5151 void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5152 if (callingUid == Process.SHELL_UID) {
5154 && sUserManager.hasUserRestriction(restriction, userHandle)) {
5155 throw new SecurityException("Shell does not have permission to access user "
5157 } else if (userHandle < 0) {
5158 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5159 + Debug.getCallers(3));
5164 private BasePermission findPermissionTreeLP(String permName) {
5165 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5166 if (permName.startsWith(bp.name) &&
5167 permName.length() > bp.name.length() &&
5168 permName.charAt(bp.name.length()) == '.') {
5175 private BasePermission checkPermissionTreeLP(String permName) {
5176 if (permName != null) {
5177 BasePermission bp = findPermissionTreeLP(permName);
5179 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5182 throw new SecurityException("Calling uid "
5183 + Binder.getCallingUid()
5184 + " is not allowed to add to permission tree "
5185 + bp.name + " owned by uid " + bp.uid);
5188 throw new SecurityException("No permission tree found for " + permName);
5191 static boolean compareStrings(CharSequence s1, CharSequence s2) {
5198 if (s1.getClass() != s2.getClass()) {
5201 return s1.equals(s2);
5204 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5205 if (pi1.icon != pi2.icon) return false;
5206 if (pi1.logo != pi2.logo) return false;
5207 if (pi1.protectionLevel != pi2.protectionLevel) return false;
5208 if (!compareStrings(pi1.name, pi2.name)) return false;
5209 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5210 // We'll take care of setting this one.
5211 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5212 // These are not currently stored in settings.
5213 //if (!compareStrings(pi1.group, pi2.group)) return false;
5214 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5215 //if (pi1.labelRes != pi2.labelRes) return false;
5216 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5220 int permissionInfoFootprint(PermissionInfo info) {
5221 int size = info.name.length();
5222 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5223 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5227 int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5229 for (BasePermission perm : mSettings.mPermissions.values()) {
5230 if (perm.uid == tree.uid) {
5231 size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5237 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5238 // We calculate the max size of permissions defined by this uid and throw
5239 // if that plus the size of 'info' would exceed our stated maximum.
5240 if (tree.uid != Process.SYSTEM_UID) {
5241 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5242 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5243 throw new SecurityException("Permission tree size cap exceeded");
5248 boolean addPermissionLocked(PermissionInfo info, boolean async) {
5249 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5250 throw new SecurityException("Instant apps can't add permissions");
5252 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5253 throw new SecurityException("Label must be specified in permission");
5255 BasePermission tree = checkPermissionTreeLP(info.name);
5256 BasePermission bp = mSettings.mPermissions.get(info.name);
5257 boolean added = bp == null;
5258 boolean changed = true;
5259 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5261 enforcePermissionCapLocked(info, tree);
5262 bp = new BasePermission(info.name, tree.sourcePackage,
5263 BasePermission.TYPE_DYNAMIC);
5264 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5265 throw new SecurityException(
5266 "Not allowed to modify non-dynamic permission "
5269 if (bp.protectionLevel == fixedLevel
5270 && bp.perm.owner.equals(tree.perm.owner)
5271 && bp.uid == tree.uid
5272 && comparePermissionInfos(bp.perm.info, info)) {
5276 bp.protectionLevel = fixedLevel;
5277 info = new PermissionInfo(info);
5278 info.protectionLevel = fixedLevel;
5279 bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5280 bp.perm.info.packageName = tree.perm.info.packageName;
5283 mSettings.mPermissions.put(info.name, bp);
5287 mSettings.writeLPr();
5289 scheduleWriteSettingsLocked();
5296 public boolean addPermission(PermissionInfo info) {
5297 synchronized (mPackages) {
5298 return addPermissionLocked(info, false);
5303 public boolean addPermissionAsync(PermissionInfo info) {
5304 synchronized (mPackages) {
5305 return addPermissionLocked(info, true);
5310 public void removePermission(String name) {
5311 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5312 throw new SecurityException("Instant applications don't have access to this method");
5314 synchronized (mPackages) {
5315 checkPermissionTreeLP(name);
5316 BasePermission bp = mSettings.mPermissions.get(name);
5318 if (bp.type != BasePermission.TYPE_DYNAMIC) {
5319 throw new SecurityException(
5320 "Not allowed to modify non-dynamic permission "
5323 mSettings.mPermissions.remove(name);
5324 mSettings.writeLPr();
5329 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5330 PackageParser.Package pkg, BasePermission bp) {
5331 int index = pkg.requestedPermissions.indexOf(bp.name);
5333 throw new SecurityException("Package " + pkg.packageName
5334 + " has not requested permission " + bp.name);
5336 if (!bp.isRuntime() && !bp.isDevelopment()) {
5337 throw new SecurityException("Permission " + bp.name
5338 + " is not a changeable permission type");
5343 public void grantRuntimePermission(String packageName, String name, final int userId) {
5344 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5347 private void grantRuntimePermission(String packageName, String name, final int userId,
5348 boolean overridePolicy) {
5349 if (!sUserManager.exists(userId)) {
5350 Log.e(TAG, "No such user:" + userId);
5353 final int callingUid = Binder.getCallingUid();
5355 mContext.enforceCallingOrSelfPermission(
5356 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5357 "grantRuntimePermission");
5359 enforceCrossUserPermission(callingUid, userId,
5360 true /* requireFullPermission */, true /* checkShell */,
5361 "grantRuntimePermission");
5364 final PackageSetting ps;
5366 synchronized (mPackages) {
5367 final PackageParser.Package pkg = mPackages.get(packageName);
5369 throw new IllegalArgumentException("Unknown package: " + packageName);
5371 final BasePermission bp = mSettings.mPermissions.get(name);
5373 throw new IllegalArgumentException("Unknown permission: " + name);
5375 ps = (PackageSetting) pkg.mExtras;
5377 || filterAppAccessLPr(ps, callingUid, userId)) {
5378 throw new IllegalArgumentException("Unknown package: " + packageName);
5381 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5383 // If a permission review is required for legacy apps we represent
5384 // their permissions as always granted runtime ones since we need
5385 // to keep the review required permission flag per user while an
5386 // install permission's state is shared across all users.
5387 if (mPermissionReviewRequired
5388 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5389 && bp.isRuntime()) {
5393 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5395 final PermissionsState permissionsState = ps.getPermissionsState();
5397 final int flags = permissionsState.getPermissionFlags(name, userId);
5398 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5399 throw new SecurityException("Cannot grant system fixed permission "
5400 + name + " for package " + packageName);
5402 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5403 throw new SecurityException("Cannot grant policy fixed permission "
5404 + name + " for package " + packageName);
5407 if (bp.isDevelopment()) {
5408 // Development permissions must be handled specially, since they are not
5409 // normal runtime permissions. For now they apply to all users.
5410 if (permissionsState.grantInstallPermission(bp) !=
5411 PermissionsState.PERMISSION_OPERATION_FAILURE) {
5412 scheduleWriteSettingsLocked();
5417 if (ps.getInstantApp(userId) && !bp.isInstant()) {
5418 throw new SecurityException("Cannot grant non-ephemeral permission"
5419 + name + " for package " + packageName);
5422 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5423 Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5427 final int result = permissionsState.grantRuntimePermission(bp, userId);
5429 case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5433 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5434 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5435 mHandler.post(new Runnable() {
5438 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5445 if (bp.isRuntime()) {
5446 logPermissionGranted(mContext, name, packageName);
5449 mOnPermissionChangeListeners.onPermissionsChanged(uid);
5451 // Not critical if that is lost - app has to request again.
5452 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5455 // Only need to do this if user is initialized. Otherwise it's a new user
5456 // and there are no processes running as the user yet and there's no need
5457 // to make an expensive call to remount processes for the changed permissions.
5458 if (READ_EXTERNAL_STORAGE.equals(name)
5459 || WRITE_EXTERNAL_STORAGE.equals(name)) {
5460 final long token = Binder.clearCallingIdentity();
5462 if (sUserManager.isInitialized(userId)) {
5463 StorageManagerInternal storageManagerInternal = LocalServices.getService(
5464 StorageManagerInternal.class);
5465 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5468 Binder.restoreCallingIdentity(token);
5474 public void revokeRuntimePermission(String packageName, String name, int userId) {
5475 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5478 private void revokeRuntimePermission(String packageName, String name, int userId,
5479 boolean overridePolicy) {
5480 if (!sUserManager.exists(userId)) {
5481 Log.e(TAG, "No such user:" + userId);
5485 mContext.enforceCallingOrSelfPermission(
5486 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5487 "revokeRuntimePermission");
5489 enforceCrossUserPermission(Binder.getCallingUid(), userId,
5490 true /* requireFullPermission */, true /* checkShell */,
5491 "revokeRuntimePermission");
5495 synchronized (mPackages) {
5496 final PackageParser.Package pkg = mPackages.get(packageName);
5498 throw new IllegalArgumentException("Unknown package: " + packageName);
5500 final PackageSetting ps = (PackageSetting) pkg.mExtras;
5502 || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5503 throw new IllegalArgumentException("Unknown package: " + packageName);
5505 final BasePermission bp = mSettings.mPermissions.get(name);
5507 throw new IllegalArgumentException("Unknown permission: " + name);
5510 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5512 // If a permission review is required for legacy apps we represent
5513 // their permissions as always granted runtime ones since we need
5514 // to keep the review required permission flag per user while an
5515 // install permission's state is shared across all users.
5516 if (mPermissionReviewRequired
5517 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5518 && bp.isRuntime()) {
5522 final PermissionsState permissionsState = ps.getPermissionsState();
5524 final int flags = permissionsState.getPermissionFlags(name, userId);
5525 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5526 throw new SecurityException("Cannot revoke system fixed permission "
5527 + name + " for package " + packageName);
5529 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5530 throw new SecurityException("Cannot revoke policy fixed permission "
5531 + name + " for package " + packageName);
5534 if (bp.isDevelopment()) {
5535 // Development permissions must be handled specially, since they are not
5536 // normal runtime permissions. For now they apply to all users.
5537 if (permissionsState.revokeInstallPermission(bp) !=
5538 PermissionsState.PERMISSION_OPERATION_FAILURE) {
5539 scheduleWriteSettingsLocked();
5544 if (permissionsState.revokeRuntimePermission(bp, userId) ==
5545 PermissionsState.PERMISSION_OPERATION_FAILURE) {
5549 if (bp.isRuntime()) {
5550 logPermissionRevoked(mContext, name, packageName);
5553 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5555 // Critical, after this call app should never have the permission.
5556 mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5558 appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5561 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5565 * Get the first event id for the permission.
5567 * <p>There are four events for each permission: <ul>
5568 * <li>Request permission: first id + 0</li>
5569 * <li>Grant permission: first id + 1</li>
5570 * <li>Request for permission denied: first id + 2</li>
5571 * <li>Revoke permission: first id + 3</li>
5574 * @param name name of the permission
5576 * @return The first event id for the permission
5578 private static int getBaseEventId(@NonNull String name) {
5579 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5581 if (eventIdIndex == -1) {
5582 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5583 || "user".equals(Build.TYPE)) {
5584 Log.i(TAG, "Unknown permission " + name);
5586 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5588 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5591 // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5592 // - metrics_constants.proto
5593 throw new IllegalStateException("Unknown permission " + name);
5597 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5601 * Log that a permission was revoked.
5603 * @param context Context of the caller
5604 * @param name name of the permission
5605 * @param packageName package permission if for
5607 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5608 @NonNull String packageName) {
5609 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5613 * Log that a permission request was granted.
5615 * @param context Context of the caller
5616 * @param name name of the permission
5617 * @param packageName package permission if for
5619 private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5620 @NonNull String packageName) {
5621 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5625 public void resetRuntimePermissions() {
5626 mContext.enforceCallingOrSelfPermission(
5627 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5628 "revokeRuntimePermission");
5630 int callingUid = Binder.getCallingUid();
5631 if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5632 mContext.enforceCallingOrSelfPermission(
5633 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5634 "resetRuntimePermissions");
5637 synchronized (mPackages) {
5638 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5639 for (int userId : UserManagerService.getInstance().getUserIds()) {
5640 final int packageCount = mPackages.size();
5641 for (int i = 0; i < packageCount; i++) {
5642 PackageParser.Package pkg = mPackages.valueAt(i);
5643 if (!(pkg.mExtras instanceof PackageSetting)) {
5646 PackageSetting ps = (PackageSetting) pkg.mExtras;
5647 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5654 public int getPermissionFlags(String name, String packageName, int userId) {
5655 if (!sUserManager.exists(userId)) {
5659 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5661 final int callingUid = Binder.getCallingUid();
5662 enforceCrossUserPermission(callingUid, userId,
5663 true /* requireFullPermission */, false /* checkShell */,
5664 "getPermissionFlags");
5666 synchronized (mPackages) {
5667 final PackageParser.Package pkg = mPackages.get(packageName);
5671 final BasePermission bp = mSettings.mPermissions.get(name);
5675 final PackageSetting ps = (PackageSetting) pkg.mExtras;
5677 || filterAppAccessLPr(ps, callingUid, userId)) {
5680 PermissionsState permissionsState = ps.getPermissionsState();
5681 return permissionsState.getPermissionFlags(name, userId);
5686 public void updatePermissionFlags(String name, String packageName, int flagMask,
5687 int flagValues, int userId) {
5688 if (!sUserManager.exists(userId)) {
5692 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5694 final int callingUid = Binder.getCallingUid();
5695 enforceCrossUserPermission(callingUid, userId,
5696 true /* requireFullPermission */, true /* checkShell */,
5697 "updatePermissionFlags");
5699 // Only the system can change these flags and nothing else.
5700 if (getCallingUid() != Process.SYSTEM_UID) {
5701 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5702 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5703 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5704 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5705 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5708 synchronized (mPackages) {
5709 final PackageParser.Package pkg = mPackages.get(packageName);
5711 throw new IllegalArgumentException("Unknown package: " + packageName);
5713 final PackageSetting ps = (PackageSetting) pkg.mExtras;
5715 || filterAppAccessLPr(ps, callingUid, userId)) {
5716 throw new IllegalArgumentException("Unknown package: " + packageName);
5719 final BasePermission bp = mSettings.mPermissions.get(name);
5721 throw new IllegalArgumentException("Unknown permission: " + name);
5724 PermissionsState permissionsState = ps.getPermissionsState();
5726 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5728 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5729 // Install and runtime permissions are stored in different places,
5730 // so figure out what permission changed and persist the change.
5731 if (permissionsState.getInstallPermissionState(name) != null) {
5732 scheduleWriteSettingsLocked();
5733 } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5735 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5742 * Update the permission flags for all packages and runtime permissions of a user in order
5743 * to allow device or profile owner to remove POLICY_FIXED.
5746 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5747 if (!sUserManager.exists(userId)) {
5751 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5753 enforceCrossUserPermission(Binder.getCallingUid(), userId,
5754 true /* requireFullPermission */, true /* checkShell */,
5755 "updatePermissionFlagsForAllApps");
5757 // Only the system can change system fixed flags.
5758 if (getCallingUid() != Process.SYSTEM_UID) {
5759 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5760 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5763 synchronized (mPackages) {
5764 boolean changed = false;
5765 final int packageCount = mPackages.size();
5766 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5767 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5768 final PackageSetting ps = (PackageSetting) pkg.mExtras;
5772 PermissionsState permissionsState = ps.getPermissionsState();
5773 changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5774 userId, flagMask, flagValues);
5777 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5782 private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5783 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5784 != PackageManager.PERMISSION_GRANTED
5785 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5786 != PackageManager.PERMISSION_GRANTED) {
5787 throw new SecurityException(message + " requires "
5788 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5789 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5794 public boolean shouldShowRequestPermissionRationale(String permissionName,
5795 String packageName, int userId) {
5796 if (UserHandle.getCallingUserId() != userId) {
5797 mContext.enforceCallingPermission(
5798 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5799 "canShowRequestPermissionRationale for user " + userId);
5802 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5803 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5807 if (checkPermission(permissionName, packageName, userId)
5808 == PackageManager.PERMISSION_GRANTED) {
5814 final long identity = Binder.clearCallingIdentity();
5816 flags = getPermissionFlags(permissionName,
5817 packageName, userId);
5819 Binder.restoreCallingIdentity(identity);
5822 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5823 | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5824 | PackageManager.FLAG_PERMISSION_USER_FIXED;
5826 if ((flags & fixedFlags) != 0) {
5830 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5834 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5835 mContext.enforceCallingOrSelfPermission(
5836 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5837 "addOnPermissionsChangeListener");
5839 synchronized (mPackages) {
5840 mOnPermissionChangeListeners.addListenerLocked(listener);
5845 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5846 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5847 throw new SecurityException("Instant applications don't have access to this method");
5849 synchronized (mPackages) {
5850 mOnPermissionChangeListeners.removeListenerLocked(listener);
5855 public boolean isProtectedBroadcast(String actionName) {
5856 // allow instant applications
5857 synchronized (mPackages) {
5858 if (mProtectedBroadcasts.contains(actionName)) {
5860 } else if (actionName != null) {
5861 // TODO: remove these terrible hacks
5862 if (actionName.startsWith("android.net.netmon.lingerExpired")
5863 || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5864 || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5865 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5874 public int checkSignatures(String pkg1, String pkg2) {
5875 synchronized (mPackages) {
5876 final PackageParser.Package p1 = mPackages.get(pkg1);
5877 final PackageParser.Package p2 = mPackages.get(pkg2);
5878 if (p1 == null || p1.mExtras == null
5879 || p2 == null || p2.mExtras == null) {
5880 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5882 final int callingUid = Binder.getCallingUid();
5883 final int callingUserId = UserHandle.getUserId(callingUid);
5884 final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5885 final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5886 if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5887 || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5888 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5890 return compareSignatures(p1.mSignatures, p2.mSignatures);
5895 public int checkUidSignatures(int uid1, int uid2) {
5896 final int callingUid = Binder.getCallingUid();
5897 final int callingUserId = UserHandle.getUserId(callingUid);
5898 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5899 // Map to base uids.
5900 uid1 = UserHandle.getAppId(uid1);
5901 uid2 = UserHandle.getAppId(uid2);
5903 synchronized (mPackages) {
5906 Object obj = mSettings.getUserIdLPr(uid1);
5908 if (obj instanceof SharedUserSetting) {
5909 if (isCallerInstantApp) {
5910 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5912 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5913 } else if (obj instanceof PackageSetting) {
5914 final PackageSetting ps = (PackageSetting) obj;
5915 if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5916 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5918 s1 = ps.signatures.mSignatures;
5920 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5923 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5925 obj = mSettings.getUserIdLPr(uid2);
5927 if (obj instanceof SharedUserSetting) {
5928 if (isCallerInstantApp) {
5929 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5931 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5932 } else if (obj instanceof PackageSetting) {
5933 final PackageSetting ps = (PackageSetting) obj;
5934 if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5935 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5937 s2 = ps.signatures.mSignatures;
5939 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5942 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5944 return compareSignatures(s1, s2);
5949 * This method should typically only be used when granting or revoking
5950 * permissions, since the app may immediately restart after this call.
5952 * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5953 * guard your work against the app being relaunched.
5955 private void killUid(int appId, int userId, String reason) {
5956 final long identity = Binder.clearCallingIdentity();
5958 IActivityManager am = ActivityManager.getService();
5961 am.killUid(appId, userId, reason);
5962 } catch (RemoteException e) {
5963 /* ignore - same process */
5967 Binder.restoreCallingIdentity(identity);
5972 * Compares two sets of signatures. Returns:
5974 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5976 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5978 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5980 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5982 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5984 static int compareSignatures(Signature[] s1, Signature[] s2) {
5987 ? PackageManager.SIGNATURE_NEITHER_SIGNED
5988 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5992 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5995 if (s1.length != s2.length) {
5996 return PackageManager.SIGNATURE_NO_MATCH;
5999 // Since both signature sets are of size 1, we can compare without HashSets.
6000 if (s1.length == 1) {
6001 return s1[0].equals(s2[0]) ?
6002 PackageManager.SIGNATURE_MATCH :
6003 PackageManager.SIGNATURE_NO_MATCH;
6006 ArraySet<Signature> set1 = new ArraySet<Signature>();
6007 for (Signature sig : s1) {
6010 ArraySet<Signature> set2 = new ArraySet<Signature>();
6011 for (Signature sig : s2) {
6014 // Make sure s2 contains all signatures in s1.
6015 if (set1.equals(set2)) {
6016 return PackageManager.SIGNATURE_MATCH;
6018 return PackageManager.SIGNATURE_NO_MATCH;
6022 * If the database version for this type of package (internal storage or
6023 * external storage) is less than the version where package signatures
6024 * were updated, return true.
6026 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6027 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6028 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6032 * Used for backward compatibility to make sure any packages with
6033 * certificate chains get upgraded to the new style. {@code existingSigs}
6034 * will be in the old format (since they were stored on disk from before the
6035 * system upgrade) and {@code scannedSigs} will be in the newer format.
6037 private int compareSignaturesCompat(PackageSignatures existingSigs,
6038 PackageParser.Package scannedPkg) {
6039 if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6040 return PackageManager.SIGNATURE_NO_MATCH;
6043 ArraySet<Signature> existingSet = new ArraySet<Signature>();
6044 for (Signature sig : existingSigs.mSignatures) {
6045 existingSet.add(sig);
6047 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6048 for (Signature sig : scannedPkg.mSignatures) {
6050 Signature[] chainSignatures = sig.getChainSignatures();
6051 for (Signature chainSig : chainSignatures) {
6052 scannedCompatSet.add(chainSig);
6054 } catch (CertificateEncodingException e) {
6055 scannedCompatSet.add(sig);
6059 * Make sure the expanded scanned set contains all signatures in the
6062 if (scannedCompatSet.equals(existingSet)) {
6063 // Migrate the old signatures to the new scheme.
6064 existingSigs.assignSignatures(scannedPkg.mSignatures);
6065 // The new KeySets will be re-added later in the scanning process.
6066 synchronized (mPackages) {
6067 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6069 return PackageManager.SIGNATURE_MATCH;
6071 return PackageManager.SIGNATURE_NO_MATCH;
6074 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6075 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6076 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6079 private int compareSignaturesRecover(PackageSignatures existingSigs,
6080 PackageParser.Package scannedPkg) {
6081 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6082 return PackageManager.SIGNATURE_NO_MATCH;
6087 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6088 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6089 + scannedPkg.packageName);
6090 return PackageManager.SIGNATURE_MATCH;
6092 } catch (CertificateException e) {
6093 msg = e.getMessage();
6096 logCriticalInfo(Log.INFO,
6097 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6098 return PackageManager.SIGNATURE_NO_MATCH;
6102 public List<String> getAllPackages() {
6103 final int callingUid = Binder.getCallingUid();
6104 final int callingUserId = UserHandle.getUserId(callingUid);
6105 synchronized (mPackages) {
6106 if (canViewInstantApps(callingUid, callingUserId)) {
6107 return new ArrayList<String>(mPackages.keySet());
6109 final String instantAppPkgName = getInstantAppPackageName(callingUid);
6110 final List<String> result = new ArrayList<>();
6111 if (instantAppPkgName != null) {
6112 // caller is an instant application; filter unexposed applications
6113 for (PackageParser.Package pkg : mPackages.values()) {
6114 if (!pkg.visibleToInstantApps) {
6117 result.add(pkg.packageName);
6120 // caller is a normal application; filter instant applications
6121 for (PackageParser.Package pkg : mPackages.values()) {
6122 final PackageSetting ps =
6123 pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6125 && ps.getInstantApp(callingUserId)
6126 && !mInstantAppRegistry.isInstantAccessGranted(
6127 callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6130 result.add(pkg.packageName);
6138 public String[] getPackagesForUid(int uid) {
6139 final int callingUid = Binder.getCallingUid();
6140 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6141 final int userId = UserHandle.getUserId(uid);
6142 uid = UserHandle.getAppId(uid);
6144 synchronized (mPackages) {
6145 Object obj = mSettings.getUserIdLPr(uid);
6146 if (obj instanceof SharedUserSetting) {
6147 if (isCallerInstantApp) {
6150 final SharedUserSetting sus = (SharedUserSetting) obj;
6151 final int N = sus.packages.size();
6152 String[] res = new String[N];
6153 final Iterator<PackageSetting> it = sus.packages.iterator();
6155 while (it.hasNext()) {
6156 PackageSetting ps = it.next();
6157 if (ps.getInstalled(userId)) {
6160 res = ArrayUtils.removeElement(String.class, res, res[i]);
6164 } else if (obj instanceof PackageSetting) {
6165 final PackageSetting ps = (PackageSetting) obj;
6166 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6167 return new String[]{ps.name};
6175 public String getNameForUid(int uid) {
6176 final int callingUid = Binder.getCallingUid();
6177 if (getInstantAppPackageName(callingUid) != null) {
6180 synchronized (mPackages) {
6181 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6182 if (obj instanceof SharedUserSetting) {
6183 final SharedUserSetting sus = (SharedUserSetting) obj;
6184 return sus.name + ":" + sus.userId;
6185 } else if (obj instanceof PackageSetting) {
6186 final PackageSetting ps = (PackageSetting) obj;
6187 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6197 public int getUidForSharedUser(String sharedUserName) {
6198 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6201 if (sharedUserName == null) {
6205 synchronized (mPackages) {
6206 SharedUserSetting suid;
6208 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6212 } catch (PackageManagerException ignore) {
6213 // can't happen, but, still need to catch it
6220 public int getFlagsForUid(int uid) {
6221 final int callingUid = Binder.getCallingUid();
6222 if (getInstantAppPackageName(callingUid) != null) {
6225 synchronized (mPackages) {
6226 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6227 if (obj instanceof SharedUserSetting) {
6228 final SharedUserSetting sus = (SharedUserSetting) obj;
6229 return sus.pkgFlags;
6230 } else if (obj instanceof PackageSetting) {
6231 final PackageSetting ps = (PackageSetting) obj;
6232 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6242 public int getPrivateFlagsForUid(int uid) {
6243 final int callingUid = Binder.getCallingUid();
6244 if (getInstantAppPackageName(callingUid) != null) {
6247 synchronized (mPackages) {
6248 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6249 if (obj instanceof SharedUserSetting) {
6250 final SharedUserSetting sus = (SharedUserSetting) obj;
6251 return sus.pkgPrivateFlags;
6252 } else if (obj instanceof PackageSetting) {
6253 final PackageSetting ps = (PackageSetting) obj;
6254 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6257 return ps.pkgPrivateFlags;
6264 public boolean isUidPrivileged(int uid) {
6265 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6268 uid = UserHandle.getAppId(uid);
6270 synchronized (mPackages) {
6271 Object obj = mSettings.getUserIdLPr(uid);
6272 if (obj instanceof SharedUserSetting) {
6273 final SharedUserSetting sus = (SharedUserSetting) obj;
6274 final Iterator<PackageSetting> it = sus.packages.iterator();
6275 while (it.hasNext()) {
6276 if (it.next().isPrivileged()) {
6280 } else if (obj instanceof PackageSetting) {
6281 final PackageSetting ps = (PackageSetting) obj;
6282 return ps.isPrivileged();
6289 public String[] getAppOpPermissionPackages(String permissionName) {
6290 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6293 synchronized (mPackages) {
6294 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6298 return pkgs.toArray(new String[pkgs.size()]);
6303 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6304 int flags, int userId) {
6305 return resolveIntentInternal(
6306 intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6309 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6310 int flags, int userId, boolean resolveForStart) {
6312 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6314 if (!sUserManager.exists(userId)) return null;
6315 final int callingUid = Binder.getCallingUid();
6316 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6317 enforceCrossUserPermission(callingUid, userId,
6318 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6320 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6321 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6322 flags, callingUid, userId, resolveForStart);
6323 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6325 final ResolveInfo bestChoice =
6326 chooseBestActivity(intent, resolvedType, flags, query, userId);
6329 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6334 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6335 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6336 throw new SecurityException(
6337 "findPersistentPreferredActivity can only be run by the system");
6339 if (!sUserManager.exists(userId)) {
6342 final int callingUid = Binder.getCallingUid();
6343 intent = updateIntentForResolve(intent);
6344 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6345 final int flags = updateFlagsForResolve(
6346 0, userId, intent, callingUid, false /*includeInstantApps*/);
6347 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6349 synchronized (mPackages) {
6350 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6356 public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6357 IntentFilter filter, int match, ComponentName activity) {
6358 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6361 final int userId = UserHandle.getCallingUserId();
6362 if (DEBUG_PREFERRED) {
6363 Log.v(TAG, "setLastChosenActivity intent=" + intent
6364 + " resolvedType=" + resolvedType
6366 + " filter=" + filter
6368 + " activity=" + activity);
6369 filter.dump(new PrintStreamPrinter(System.out), " ");
6371 intent.setComponent(null);
6372 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6374 // Find any earlier preferred or last chosen entries and nuke them
6375 findPreferredActivity(intent, resolvedType,
6376 flags, query, 0, false, true, false, userId);
6377 // Add the new activity as the last chosen for this filter
6378 addPreferredActivityInternal(filter, match, null, activity, false, userId,
6379 "Setting last chosen");
6383 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6384 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6387 final int userId = UserHandle.getCallingUserId();
6388 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6389 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6391 return findPreferredActivity(intent, resolvedType, flags, query, 0,
6392 false, false, false, userId);
6396 * Returns whether or not instant apps have been disabled remotely.
6398 private boolean isEphemeralDisabled() {
6399 return mEphemeralAppsDisabled;
6402 private boolean isInstantAppAllowed(
6403 Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6404 boolean skipPackageCheck) {
6405 if (mInstantAppResolverConnection == null) {
6408 if (mInstantAppInstallerActivity == null) {
6411 if (intent.getComponent() != null) {
6414 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6417 if (!skipPackageCheck && intent.getPackage() != null) {
6420 final boolean isWebUri = hasWebURI(intent);
6421 if (!isWebUri || intent.getData().getHost() == null) {
6424 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6425 // Or if there's already an ephemeral app installed that handles the action
6426 synchronized (mPackages) {
6427 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6428 for (int n = 0; n < count; n++) {
6429 final ResolveInfo info = resolvedActivities.get(n);
6430 final String packageName = info.activityInfo.packageName;
6431 final PackageSetting ps = mSettings.mPackages.get(packageName);
6433 // only check domain verification status if the app is not a browser
6434 if (!info.handleAllWebDataURI) {
6435 // Try to get the status from User settings first
6436 final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6437 final int status = (int) (packedStatus >> 32);
6438 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6439 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6440 if (DEBUG_EPHEMERAL) {
6441 Slog.v(TAG, "DENY instant app;"
6442 + " pkg: " + packageName + ", status: " + status);
6447 if (ps.getInstantApp(userId)) {
6448 if (DEBUG_EPHEMERAL) {
6449 Slog.v(TAG, "DENY instant app installed;"
6450 + " pkg: " + packageName);
6457 // We've exhausted all ways to deny ephemeral application; let the system look for them.
6461 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6462 Intent origIntent, String resolvedType, String callingPackage,
6463 Bundle verificationBundle, int userId) {
6464 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6465 new InstantAppRequest(responseObj, origIntent, resolvedType,
6466 callingPackage, userId, verificationBundle));
6467 mHandler.sendMessage(msg);
6470 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6471 int flags, List<ResolveInfo> query, int userId) {
6472 if (query != null) {
6473 final int N = query.size();
6475 return query.get(0);
6477 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6478 // If there is more than one activity with the same priority,
6479 // then let the user decide between them.
6480 ResolveInfo r0 = query.get(0);
6481 ResolveInfo r1 = query.get(1);
6482 if (DEBUG_INTENT_MATCHING || debug) {
6483 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6484 + r1.activityInfo.name + "=" + r1.priority);
6486 // If the first activity has a higher priority, or a different
6487 // default, then it is always desirable to pick it.
6488 if (r0.priority != r1.priority
6489 || r0.preferredOrder != r1.preferredOrder
6490 || r0.isDefault != r1.isDefault) {
6491 return query.get(0);
6493 // If we have saved a preference for a preferred activity for
6494 // this Intent, use that.
6495 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6496 flags, query, r0.priority, true, false, debug, userId);
6500 // If we have an ephemeral app, use it
6501 for (int i = 0; i < N; i++) {
6503 if (ri.activityInfo.applicationInfo.isInstantApp()) {
6504 final String packageName = ri.activityInfo.packageName;
6505 final PackageSetting ps = mSettings.mPackages.get(packageName);
6506 final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6507 final int status = (int)(packedStatus >> 32);
6508 if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6513 ri = new ResolveInfo(mResolveInfo);
6514 ri.activityInfo = new ActivityInfo(ri.activityInfo);
6515 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6516 // If all of the options come from the same package, show the application's
6517 // label and icon instead of the generic resolver's.
6518 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6519 // and then throw away the ResolveInfo itself, meaning that the caller loses
6520 // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6521 // a fallback for this case; we only set the target package's resources on
6522 // the ResolveInfo, not the ActivityInfo.
6523 final String intentPackage = intent.getPackage();
6524 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6525 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6526 ri.resolvePackageName = intentPackage;
6527 if (userNeedsBadging(userId)) {
6528 ri.noResourceId = true;
6530 ri.icon = appi.icon;
6532 ri.iconResourceId = appi.icon;
6533 ri.labelRes = appi.labelRes;
6535 ri.activityInfo.applicationInfo = new ApplicationInfo(
6536 ri.activityInfo.applicationInfo);
6538 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6539 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6541 // Make sure that the resolver is displayable in car mode
6542 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6543 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6551 * Return true if the given list is not empty and all of its contents have
6552 * an activityInfo with the given package name.
6554 private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6555 if (ArrayUtils.isEmpty(list)) {
6558 for (int i = 0, N = list.size(); i < N; i++) {
6559 final ResolveInfo ri = list.get(i);
6560 final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6561 if (ai == null || !packageName.equals(ai.packageName)) {
6568 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6569 int flags, List<ResolveInfo> query, boolean debug, int userId) {
6570 final int N = query.size();
6571 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6573 // Get the list of persistent preferred activities that handle the intent
6574 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6575 List<PersistentPreferredActivity> pprefs = ppir != null
6576 ? ppir.queryIntent(intent, resolvedType,
6577 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6580 if (pprefs != null && pprefs.size() > 0) {
6581 final int M = pprefs.size();
6582 for (int i=0; i<M; i++) {
6583 final PersistentPreferredActivity ppa = pprefs.get(i);
6584 if (DEBUG_PREFERRED || debug) {
6585 Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6586 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6587 + "\n component=" + ppa.mComponent);
6588 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
6590 final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6591 flags | MATCH_DISABLED_COMPONENTS, userId);
6592 if (DEBUG_PREFERRED || debug) {
6593 Slog.v(TAG, "Found persistent preferred activity:");
6595 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
6597 Slog.v(TAG, " null");
6601 // This previously registered persistent preferred activity
6602 // component is no longer known. Ignore it and do NOT remove it.
6605 for (int j=0; j<N; j++) {
6606 final ResolveInfo ri = query.get(j);
6607 if (!ri.activityInfo.applicationInfo.packageName
6608 .equals(ai.applicationInfo.packageName)) {
6611 if (!ri.activityInfo.name.equals(ai.name)) {
6614 // Found a persistent preference that can handle the intent.
6615 if (DEBUG_PREFERRED || debug) {
6616 Slog.v(TAG, "Returning persistent preferred activity: " +
6617 ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6626 // TODO: handle preferred activities missing while user has amnesia
6627 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6628 List<ResolveInfo> query, int priority, boolean always,
6629 boolean removeMatches, boolean debug, int userId) {
6630 if (!sUserManager.exists(userId)) return null;
6631 final int callingUid = Binder.getCallingUid();
6632 flags = updateFlagsForResolve(
6633 flags, userId, intent, callingUid, false /*includeInstantApps*/);
6634 intent = updateIntentForResolve(intent);
6636 synchronized (mPackages) {
6637 // Try to find a matching persistent preferred activity.
6638 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6641 // If a persistent preferred activity matched, use it.
6646 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6647 // Get the list of preferred activities that handle the intent
6648 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6649 List<PreferredActivity> prefs = pir != null
6650 ? pir.queryIntent(intent, resolvedType,
6651 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6654 if (prefs != null && prefs.size() > 0) {
6655 boolean changed = false;
6657 // First figure out how good the original match set is.
6658 // We will only allow preferred activities that came
6659 // from the same match quality.
6662 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6664 final int N = query.size();
6665 for (int j=0; j<N; j++) {
6666 final ResolveInfo ri = query.get(j);
6667 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6668 + ": 0x" + Integer.toHexString(match));
6669 if (ri.match > match) {
6674 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6675 + Integer.toHexString(match));
6677 match &= IntentFilter.MATCH_CATEGORY_MASK;
6678 final int M = prefs.size();
6679 for (int i=0; i<M; i++) {
6680 final PreferredActivity pa = prefs.get(i);
6681 if (DEBUG_PREFERRED || debug) {
6682 Slog.v(TAG, "Checking PreferredActivity ds="
6683 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6684 + "\n component=" + pa.mPref.mComponent);
6685 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
6687 if (pa.mPref.mMatch != match) {
6688 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6689 + Integer.toHexString(pa.mPref.mMatch));
6692 // If it's not an "always" type preferred activity and that's what we're
6693 // looking for, skip it.
6694 if (always && !pa.mPref.mAlways) {
6695 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6698 final ActivityInfo ai = getActivityInfo(
6699 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6700 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6702 if (DEBUG_PREFERRED || debug) {
6703 Slog.v(TAG, "Found preferred activity:");
6705 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " ");
6707 Slog.v(TAG, " null");
6711 // This previously registered preferred activity
6712 // component is no longer known. Most likely an update
6713 // to the app was installed and in the new version this
6714 // component no longer exists. Clean it up by removing
6715 // it from the preferred activities list, and skip it.
6716 Slog.w(TAG, "Removing dangling preferred activity: "
6717 + pa.mPref.mComponent);
6718 pir.removeFilter(pa);
6722 for (int j=0; j<N; j++) {
6723 final ResolveInfo ri = query.get(j);
6724 if (!ri.activityInfo.applicationInfo.packageName
6725 .equals(ai.applicationInfo.packageName)) {
6728 if (!ri.activityInfo.name.equals(ai.name)) {
6732 if (removeMatches) {
6733 pir.removeFilter(pa);
6735 if (DEBUG_PREFERRED) {
6736 Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6741 // Okay we found a previously set preferred or last chosen app.
6742 // If the result set is different from when this
6743 // was created, we need to clear it and re-ask the
6744 // user their preference, if we're looking for an "always" type entry.
6745 if (always && !pa.mPref.sameSet(query)) {
6746 Slog.i(TAG, "Result set changed, dropping preferred activity for "
6747 + intent + " type " + resolvedType);
6748 if (DEBUG_PREFERRED) {
6749 Slog.v(TAG, "Removing preferred activity since set changed "
6750 + pa.mPref.mComponent);
6752 pir.removeFilter(pa);
6753 // Re-add the filter as a "last chosen" entry (!always)
6754 PreferredActivity lastChosen = new PreferredActivity(
6755 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6756 pir.addFilter(lastChosen);
6761 // Yay! Either the set matched or we're looking for the last chosen
6762 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6763 + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6769 if (DEBUG_PREFERRED) {
6770 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6772 scheduleWritePackageRestrictionsLocked(userId);
6777 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6782 * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6785 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6787 mContext.enforceCallingOrSelfPermission(
6788 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6789 List<CrossProfileIntentFilter> matches =
6790 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6791 if (matches != null) {
6792 int size = matches.size();
6793 for (int i = 0; i < size; i++) {
6794 if (matches.get(i).getTargetUserId() == targetUserId) return true;
6797 if (hasWebURI(intent)) {
6798 // cross-profile app linking works only towards the parent.
6799 final int callingUid = Binder.getCallingUid();
6800 final UserInfo parent = getProfileParent(sourceUserId);
6801 synchronized(mPackages) {
6802 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6803 false /*includeInstantApps*/);
6804 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6805 intent, resolvedType, flags, sourceUserId, parent.id);
6806 return xpDomainInfo != null;
6812 private UserInfo getProfileParent(int userId) {
6813 final long identity = Binder.clearCallingIdentity();
6815 return sUserManager.getProfileParent(userId);
6817 Binder.restoreCallingIdentity(identity);
6821 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6822 String resolvedType, int userId) {
6823 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6824 if (resolver != null) {
6825 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6831 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6832 String resolvedType, int flags, int userId) {
6834 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6836 return new ParceledListSlice<>(
6837 queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6839 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6844 * Returns the package name of the calling Uid if it's an instant app. If it isn't
6845 * instant, returns {@code null}.
6847 private String getInstantAppPackageName(int callingUid) {
6848 synchronized (mPackages) {
6849 // If the caller is an isolated app use the owner's uid for the lookup.
6850 if (Process.isIsolated(callingUid)) {
6851 callingUid = mIsolatedOwners.get(callingUid);
6853 final int appId = UserHandle.getAppId(callingUid);
6854 final Object obj = mSettings.getUserIdLPr(appId);
6855 if (obj instanceof PackageSetting) {
6856 final PackageSetting ps = (PackageSetting) obj;
6857 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6858 return isInstantApp ? ps.pkg.packageName : null;
6864 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6865 String resolvedType, int flags, int userId) {
6866 return queryIntentActivitiesInternal(
6867 intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6870 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6871 String resolvedType, int flags, int filterCallingUid, int userId,
6872 boolean resolveForStart) {
6873 if (!sUserManager.exists(userId)) return Collections.emptyList();
6874 final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6875 enforceCrossUserPermission(Binder.getCallingUid(), userId,
6876 false /* requireFullPermission */, false /* checkShell */,
6877 "query intent activities");
6878 final String pkgName = intent.getPackage();
6879 ComponentName comp = intent.getComponent();
6881 if (intent.getSelector() != null) {
6882 intent = intent.getSelector();
6883 comp = intent.getComponent();
6887 flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6888 comp != null || pkgName != null /*onlyExposedExplicitly*/);
6890 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6891 final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6893 // When specifying an explicit component, we prevent the activity from being
6894 // used when either 1) the calling package is normal and the activity is within
6895 // an ephemeral application or 2) the calling package is ephemeral and the
6896 // activity is not visible to ephemeral applications.
6897 final boolean matchInstantApp =
6898 (flags & PackageManager.MATCH_INSTANT) != 0;
6899 final boolean matchVisibleToInstantAppOnly =
6900 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6901 final boolean matchExplicitlyVisibleOnly =
6902 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6903 final boolean isCallerInstantApp =
6904 instantAppPkgName != null;
6905 final boolean isTargetSameInstantApp =
6906 comp.getPackageName().equals(instantAppPkgName);
6907 final boolean isTargetInstantApp =
6908 (ai.applicationInfo.privateFlags
6909 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6910 final boolean isTargetVisibleToInstantApp =
6911 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6912 final boolean isTargetExplicitlyVisibleToInstantApp =
6913 isTargetVisibleToInstantApp
6914 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6915 final boolean isTargetHiddenFromInstantApp =
6916 !isTargetVisibleToInstantApp
6917 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6918 final boolean blockResolution =
6919 !isTargetSameInstantApp
6920 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6921 || (matchVisibleToInstantAppOnly && isCallerInstantApp
6922 && isTargetHiddenFromInstantApp));
6923 if (!blockResolution) {
6924 final ResolveInfo ri = new ResolveInfo();
6925 ri.activityInfo = ai;
6929 return applyPostResolutionFilter(list, instantAppPkgName);
6933 boolean sortResult = false;
6934 boolean addEphemeral = false;
6935 List<ResolveInfo> result;
6936 final boolean ephemeralDisabled = isEphemeralDisabled();
6937 synchronized (mPackages) {
6938 if (pkgName == null) {
6939 List<CrossProfileIntentFilter> matchingFilters =
6940 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6941 // Check for results that need to skip the current profile.
6942 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
6943 resolvedType, flags, userId);
6944 if (xpResolveInfo != null) {
6945 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6946 xpResult.add(xpResolveInfo);
6947 return applyPostResolutionFilter(
6948 filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6951 // Check for results in the current profile.
6952 result = filterIfNotSystemUser(mActivities.queryIntent(
6953 intent, resolvedType, flags, userId), userId);
6954 addEphemeral = !ephemeralDisabled
6955 && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6956 // Check for cross profile results.
6957 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6958 xpResolveInfo = queryCrossProfileIntents(
6959 matchingFilters, intent, resolvedType, flags, userId,
6960 hasNonNegativePriorityResult);
6961 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6962 boolean isVisibleToUser = filterIfNotSystemUser(
6963 Collections.singletonList(xpResolveInfo), userId).size() > 0;
6964 if (isVisibleToUser) {
6965 result.add(xpResolveInfo);
6969 if (hasWebURI(intent)) {
6970 CrossProfileDomainInfo xpDomainInfo = null;
6971 final UserInfo parent = getProfileParent(userId);
6972 if (parent != null) {
6973 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6974 flags, userId, parent.id);
6976 if (xpDomainInfo != null) {
6977 if (xpResolveInfo != null) {
6978 // If we didn't remove it, the cross-profile ResolveInfo would be twice
6980 result.remove(xpResolveInfo);
6982 if (result.size() == 0 && !addEphemeral) {
6983 // No result in current profile, but found candidate in parent user.
6984 // And we are not going to add emphemeral app, so we can return the
6985 // result straight away.
6986 result.add(xpDomainInfo.resolveInfo);
6987 return applyPostResolutionFilter(result, instantAppPkgName);
6989 } else if (result.size() <= 1 && !addEphemeral) {
6990 // No result in parent user and <= 1 result in current profile, and we
6991 // are not going to add emphemeral app, so we can return the result without
6992 // further processing.
6993 return applyPostResolutionFilter(result, instantAppPkgName);
6995 // We have more than one candidate (combining results from current and parent
6996 // profile), so we need filtering and sorting.
6997 result = filterCandidatesWithDomainPreferredActivitiesLPr(
6998 intent, flags, result, xpDomainInfo, userId);
7002 final PackageParser.Package pkg = mPackages.get(pkgName);
7005 result = filterIfNotSystemUser(
7006 mActivities.queryIntentForPackage(
7007 intent, resolvedType, flags, pkg.activities, userId),
7010 if (result == null || result.size() == 0) {
7011 // the caller wants to resolve for a particular package; however, there
7012 // were no installed results, so, try to find an ephemeral result
7013 addEphemeral = !ephemeralDisabled
7014 && isInstantAppAllowed(
7015 intent, null /*result*/, userId, true /*skipPackageCheck*/);
7016 if (result == null) {
7017 result = new ArrayList<>();
7023 result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7026 Collections.sort(result, mResolvePrioritySorter);
7028 return applyPostResolutionFilter(result, instantAppPkgName);
7031 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7032 String resolvedType, int flags, int userId) {
7033 // first, check to see if we've got an instant app already installed
7034 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7035 ResolveInfo localInstantApp = null;
7036 boolean blockResolution = false;
7037 if (!alreadyResolvedLocally) {
7038 final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7040 | PackageManager.GET_RESOLVED_FILTER
7041 | PackageManager.MATCH_INSTANT
7042 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7044 for (int i = instantApps.size() - 1; i >= 0; --i) {
7045 final ResolveInfo info = instantApps.get(i);
7046 final String packageName = info.activityInfo.packageName;
7047 final PackageSetting ps = mSettings.mPackages.get(packageName);
7048 if (ps.getInstantApp(userId)) {
7049 final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7050 final int status = (int)(packedStatus >> 32);
7051 final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7052 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7053 // there's a local instant application installed, but, the user has
7054 // chosen to never use it; skip resolution and don't acknowledge
7055 // an instant application is even available
7056 if (DEBUG_EPHEMERAL) {
7057 Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7059 blockResolution = true;
7062 // we have a locally installed instant application; skip resolution
7063 // but acknowledge there's an instant application available
7064 if (DEBUG_EPHEMERAL) {
7065 Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7067 localInstantApp = info;
7073 // no app installed, let's see if one's available
7074 AuxiliaryResolveInfo auxiliaryResponse = null;
7075 if (!blockResolution) {
7076 if (localInstantApp == null) {
7077 // we don't have an instant app locally, resolve externally
7078 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7079 final InstantAppRequest requestObject = new InstantAppRequest(
7080 null /*responseObj*/, intent /*origIntent*/, resolvedType,
7081 null /*callingPackage*/, userId, null /*verificationBundle*/);
7083 InstantAppResolver.doInstantAppResolutionPhaseOne(
7084 mContext, mInstantAppResolverConnection, requestObject);
7085 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7087 // we have an instant application locally, but, we can't admit that since
7088 // callers shouldn't be able to determine prior browsing. create a dummy
7089 // auxiliary response so the downstream code behaves as if there's an
7090 // instant application available externally. when it comes time to start
7091 // the instant application, we'll do the right thing.
7092 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7093 auxiliaryResponse = new AuxiliaryResolveInfo(
7094 ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7097 if (auxiliaryResponse != null) {
7098 if (DEBUG_EPHEMERAL) {
7099 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7101 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7102 final PackageSetting ps =
7103 mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7105 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7106 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7107 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7108 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7109 // make sure this resolver is the default
7110 ephemeralInstaller.isDefault = true;
7111 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7112 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7113 // add a non-generic filter
7114 ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7115 ephemeralInstaller.filter.addDataPath(
7116 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7117 ephemeralInstaller.isInstantAppAvailable = true;
7118 result.add(ephemeralInstaller);
7124 private static class CrossProfileDomainInfo {
7125 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7126 ResolveInfo resolveInfo;
7127 /* Best domain verification status of the activities found in the other profile */
7128 int bestDomainVerificationStatus;
7131 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7132 String resolvedType, int flags, int sourceUserId, int parentUserId) {
7133 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7137 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7138 resolvedType, flags, parentUserId);
7140 if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7143 CrossProfileDomainInfo result = null;
7144 int size = resultTargetUser.size();
7145 for (int i = 0; i < size; i++) {
7146 ResolveInfo riTargetUser = resultTargetUser.get(i);
7147 // Intent filter verification is only for filters that specify a host. So don't return
7148 // those that handle all web uris.
7149 if (riTargetUser.handleAllWebDataURI) {
7152 String packageName = riTargetUser.activityInfo.packageName;
7153 PackageSetting ps = mSettings.mPackages.get(packageName);
7157 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7158 int status = (int)(verificationState >> 32);
7159 if (result == null) {
7160 result = new CrossProfileDomainInfo();
7161 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7162 sourceUserId, parentUserId);
7163 result.bestDomainVerificationStatus = status;
7165 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7166 result.bestDomainVerificationStatus);
7169 // Don't consider matches with status NEVER across profiles.
7170 if (result != null && result.bestDomainVerificationStatus
7171 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7178 * Verification statuses are ordered from the worse to the best, except for
7179 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7181 private int bestDomainVerificationStatus(int status1, int status2) {
7182 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7185 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7188 return (int) MathUtils.max(status1, status2);
7191 private boolean isUserEnabled(int userId) {
7192 long callingId = Binder.clearCallingIdentity();
7194 UserInfo userInfo = sUserManager.getUserInfo(userId);
7195 return userInfo != null && userInfo.isEnabled();
7197 Binder.restoreCallingIdentity(callingId);
7202 * Filter out activities with systemUserOnly flag set, when current user is not System.
7204 * @return filtered list
7206 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7207 if (userId == UserHandle.USER_SYSTEM) {
7208 return resolveInfos;
7210 for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7211 ResolveInfo info = resolveInfos.get(i);
7212 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7213 resolveInfos.remove(i);
7216 return resolveInfos;
7220 * Filters out ephemeral activities.
7221 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7222 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7224 * @param resolveInfos The pre-filtered list of resolved activities
7225 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7227 * @return A filtered list of resolved activities.
7229 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7230 String ephemeralPkgName) {
7231 for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7232 final ResolveInfo info = resolveInfos.get(i);
7233 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7234 // TODO: When adding on-demand split support for non-instant apps, remove this check
7235 // and always apply post filtering
7236 // allow activities that are defined in the provided package
7237 if (isEphemeralApp) {
7238 if (info.activityInfo.splitName != null
7239 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7240 info.activityInfo.splitName)) {
7241 // requested activity is defined in a split that hasn't been installed yet.
7242 // add the installer to the resolve list
7243 if (DEBUG_EPHEMERAL) {
7244 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7246 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7247 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7248 info.activityInfo.packageName, info.activityInfo.splitName,
7249 info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7250 // make sure this resolver is the default
7251 installerInfo.isDefault = true;
7252 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7253 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7254 // add a non-generic filter
7255 installerInfo.filter = new IntentFilter();
7256 // load resources from the correct package
7257 installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7258 resolveInfos.set(i, installerInfo);
7262 // caller is a full app, don't need to apply any other filtering
7263 if (ephemeralPkgName == null) {
7265 } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7266 // caller is same app; don't need to apply any other filtering
7269 // allow activities that have been explicitly exposed to ephemeral apps
7271 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7274 resolveInfos.remove(i);
7276 return resolveInfos;
7280 * @param resolveInfos list of resolve infos in descending priority order
7281 * @return if the list contains a resolve info with non-negative priority
7283 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7284 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7287 private static boolean hasWebURI(Intent intent) {
7288 if (intent.getData() == null) {
7291 final String scheme = intent.getScheme();
7292 if (TextUtils.isEmpty(scheme)) {
7295 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7298 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7299 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7301 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7303 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7304 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7308 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7309 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7310 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7311 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7312 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7313 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7315 synchronized (mPackages) {
7316 final int count = candidates.size();
7317 // First, try to use linked apps. Partition the candidates into four lists:
7318 // one for the final results, one for the "do not use ever", one for "undefined status"
7319 // and finally one for "browser app type".
7320 for (int n=0; n<count; n++) {
7321 ResolveInfo info = candidates.get(n);
7322 String packageName = info.activityInfo.packageName;
7323 PackageSetting ps = mSettings.mPackages.get(packageName);
7325 // Add to the special match all list (Browser use case)
7326 if (info.handleAllWebDataURI) {
7327 matchAllList.add(info);
7330 // Try to get the status from User settings first
7331 long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7332 int status = (int)(packedStatus >> 32);
7333 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7334 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7335 if (DEBUG_DOMAIN_VERIFICATION || debug) {
7336 Slog.i(TAG, " + always: " + info.activityInfo.packageName
7337 + " : linkgen=" + linkGeneration);
7339 // Use link-enabled generation as preferredOrder, i.e.
7340 // prefer newly-enabled over earlier-enabled.
7341 info.preferredOrder = linkGeneration;
7342 alwaysList.add(info);
7343 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7344 if (DEBUG_DOMAIN_VERIFICATION || debug) {
7345 Slog.i(TAG, " + never: " + info.activityInfo.packageName);
7347 neverList.add(info);
7348 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7349 if (DEBUG_DOMAIN_VERIFICATION || debug) {
7350 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName);
7352 alwaysAskList.add(info);
7353 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7354 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7355 if (DEBUG_DOMAIN_VERIFICATION || debug) {
7356 Slog.i(TAG, " + ask: " + info.activityInfo.packageName);
7358 undefinedList.add(info);
7363 // We'll want to include browser possibilities in a few cases
7364 boolean includeBrowser = false;
7366 // First try to add the "always" resolution(s) for the current user, if any
7367 if (alwaysList.size() > 0) {
7368 result.addAll(alwaysList);
7370 // Add all undefined apps as we want them to appear in the disambiguation dialog.
7371 result.addAll(undefinedList);
7372 // Maybe add one for the other profile.
7373 if (xpDomainInfo != null && (
7374 xpDomainInfo.bestDomainVerificationStatus
7375 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7376 result.add(xpDomainInfo.resolveInfo);
7378 includeBrowser = true;
7381 // The presence of any 'always ask' alternatives means we'll also offer browsers.
7382 // If there were 'always' entries their preferred order has been set, so we also
7383 // back that off to make the alternatives equivalent
7384 if (alwaysAskList.size() > 0) {
7385 for (ResolveInfo i : result) {
7386 i.preferredOrder = 0;
7388 result.addAll(alwaysAskList);
7389 includeBrowser = true;
7392 if (includeBrowser) {
7393 // Also add browsers (all of them or only the default one)
7394 if (DEBUG_DOMAIN_VERIFICATION) {
7395 Slog.v(TAG, " ...including browsers in candidate set");
7397 if ((matchFlags & MATCH_ALL) != 0) {
7398 result.addAll(matchAllList);
7400 // Browser/generic handling case. If there's a default browser, go straight
7401 // to that (but only if there is no other higher-priority match).
7402 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7403 int maxMatchPrio = 0;
7404 ResolveInfo defaultBrowserMatch = null;
7405 final int numCandidates = matchAllList.size();
7406 for (int n = 0; n < numCandidates; n++) {
7407 ResolveInfo info = matchAllList.get(n);
7408 // track the highest overall match priority...
7409 if (info.priority > maxMatchPrio) {
7410 maxMatchPrio = info.priority;
7412 // ...and the highest-priority default browser match
7413 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7414 if (defaultBrowserMatch == null
7415 || (defaultBrowserMatch.priority < info.priority)) {
7417 Slog.v(TAG, "Considering default browser match " + info);
7419 defaultBrowserMatch = info;
7423 if (defaultBrowserMatch != null
7424 && defaultBrowserMatch.priority >= maxMatchPrio
7425 && !TextUtils.isEmpty(defaultBrowserPackageName))
7428 Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7430 result.add(defaultBrowserMatch);
7432 result.addAll(matchAllList);
7436 // If there is nothing selected, add all candidates and remove the ones that the user
7437 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7438 if (result.size() == 0) {
7439 result.addAll(candidates);
7440 result.removeAll(neverList);
7444 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7445 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7447 for (ResolveInfo info : result) {
7448 Slog.v(TAG, " + " + info.activityInfo);
7454 // Returns a packed value as a long:
7456 // high 'int'-sized word: link status: undefined/ask/never/always.
7457 // low 'int'-sized word: relative priority among 'always' results.
7458 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7459 long result = ps.getDomainVerificationStatusForUser(userId);
7460 // if none available, get the master status
7461 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7462 if (ps.getIntentFilterVerificationInfo() != null) {
7463 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7469 private ResolveInfo querySkipCurrentProfileIntents(
7470 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7471 int flags, int sourceUserId) {
7472 if (matchingFilters != null) {
7473 int size = matchingFilters.size();
7474 for (int i = 0; i < size; i ++) {
7475 CrossProfileIntentFilter filter = matchingFilters.get(i);
7476 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7477 // Checking if there are activities in the target user that can handle the
7479 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7480 resolvedType, flags, sourceUserId);
7481 if (resolveInfo != null) {
7490 // Return matching ResolveInfo in target user if any.
7491 private ResolveInfo queryCrossProfileIntents(
7492 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7493 int flags, int sourceUserId, boolean matchInCurrentProfile) {
7494 if (matchingFilters != null) {
7495 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7496 // match the same intent. For performance reasons, it is better not to
7497 // run queryIntent twice for the same userId
7498 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7499 int size = matchingFilters.size();
7500 for (int i = 0; i < size; i++) {
7501 CrossProfileIntentFilter filter = matchingFilters.get(i);
7502 int targetUserId = filter.getTargetUserId();
7503 boolean skipCurrentProfile =
7504 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7505 boolean skipCurrentProfileIfNoMatchFound =
7506 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7507 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7508 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7509 // Checking if there are activities in the target user that can handle the
7511 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7512 resolvedType, flags, sourceUserId);
7513 if (resolveInfo != null) return resolveInfo;
7514 alreadyTriedUserIds.put(targetUserId, true);
7522 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7523 * will forward the intent to the filter's target user.
7524 * Otherwise, returns null.
7526 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7527 String resolvedType, int flags, int sourceUserId) {
7528 int targetUserId = filter.getTargetUserId();
7529 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7530 resolvedType, flags, targetUserId);
7531 if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7532 // If all the matches in the target profile are suspended, return null.
7533 for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7534 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7535 & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7536 return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7544 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7545 int sourceUserId, int targetUserId) {
7546 ResolveInfo forwardingResolveInfo = new ResolveInfo();
7547 long ident = Binder.clearCallingIdentity();
7548 boolean targetIsProfile;
7550 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7552 Binder.restoreCallingIdentity(ident);
7555 if (targetIsProfile) {
7556 className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7558 className = FORWARD_INTENT_TO_PARENT;
7560 ComponentName forwardingActivityComponentName = new ComponentName(
7561 mAndroidApplication.packageName, className);
7562 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7564 if (!targetIsProfile) {
7565 forwardingActivityInfo.showUserIcon = targetUserId;
7566 forwardingResolveInfo.noResourceId = true;
7568 forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7569 forwardingResolveInfo.priority = 0;
7570 forwardingResolveInfo.preferredOrder = 0;
7571 forwardingResolveInfo.match = 0;
7572 forwardingResolveInfo.isDefault = true;
7573 forwardingResolveInfo.filter = filter;
7574 forwardingResolveInfo.targetUserId = targetUserId;
7575 return forwardingResolveInfo;
7579 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7580 Intent[] specifics, String[] specificTypes, Intent intent,
7581 String resolvedType, int flags, int userId) {
7582 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7583 specificTypes, intent, resolvedType, flags, userId));
7586 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7587 Intent[] specifics, String[] specificTypes, Intent intent,
7588 String resolvedType, int flags, int userId) {
7589 if (!sUserManager.exists(userId)) return Collections.emptyList();
7590 final int callingUid = Binder.getCallingUid();
7591 flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7592 false /*includeInstantApps*/);
7593 enforceCrossUserPermission(callingUid, userId,
7594 false /*requireFullPermission*/, false /*checkShell*/,
7595 "query intent activity options");
7596 final String resultsAction = intent.getAction();
7598 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7599 | PackageManager.GET_RESOLVED_FILTER, userId);
7601 if (DEBUG_INTENT_MATCHING) {
7602 Log.v(TAG, "Query " + intent + ": " + results);
7605 int specificsPos = 0;
7608 // todo: note that the algorithm used here is O(N^2). This
7609 // isn't a problem in our current environment, but if we start running
7610 // into situations where we have more than 5 or 10 matches then this
7611 // should probably be changed to something smarter...
7613 // First we go through and resolve each of the specific items
7614 // that were supplied, taking care of removing any corresponding
7615 // duplicate items in the generic resolve list.
7616 if (specifics != null) {
7617 for (int i=0; i<specifics.length; i++) {
7618 final Intent sintent = specifics[i];
7619 if (sintent == null) {
7623 if (DEBUG_INTENT_MATCHING) {
7624 Log.v(TAG, "Specific #" + i + ": " + sintent);
7627 String action = sintent.getAction();
7628 if (resultsAction != null && resultsAction.equals(action)) {
7629 // If this action was explicitly requested, then don't
7630 // remove things that have it.
7634 ResolveInfo ri = null;
7635 ActivityInfo ai = null;
7637 ComponentName comp = sintent.getComponent();
7641 specificTypes != null ? specificTypes[i] : null,
7646 if (ri == mResolveInfo) {
7647 // ACK! Must do something better with this.
7649 ai = ri.activityInfo;
7650 comp = new ComponentName(ai.applicationInfo.packageName,
7653 ai = getActivityInfo(comp, flags, userId);
7659 // Look for any generic query activities that are duplicates
7660 // of this specific one, and remove them from the results.
7661 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7664 for (j=specificsPos; j<N; j++) {
7665 ResolveInfo sri = results.get(j);
7666 if ((sri.activityInfo.name.equals(comp.getClassName())
7667 && sri.activityInfo.applicationInfo.packageName.equals(
7668 comp.getPackageName()))
7669 || (action != null && sri.filter.matchAction(action))) {
7671 if (DEBUG_INTENT_MATCHING) Log.v(
7672 TAG, "Removing duplicate item from " + j
7673 + " due to specific " + specificsPos);
7682 // Add this specific item to its proper place.
7684 ri = new ResolveInfo();
7685 ri.activityInfo = ai;
7687 results.add(specificsPos, ri);
7688 ri.specificIndex = i;
7693 // Now we go through the remaining generic results and remove any
7694 // duplicate actions that are found here.
7696 for (int i=specificsPos; i<N-1; i++) {
7697 final ResolveInfo rii = results.get(i);
7698 if (rii.filter == null) {
7702 // Iterate over all of the actions of this result's intent
7703 // filter... typically this should be just one.
7704 final Iterator<String> it = rii.filter.actionsIterator();
7708 while (it.hasNext()) {
7709 final String action = it.next();
7710 if (resultsAction != null && resultsAction.equals(action)) {
7711 // If this action was explicitly requested, then don't
7712 // remove things that have it.
7715 for (int j=i+1; j<N; j++) {
7716 final ResolveInfo rij = results.get(j);
7717 if (rij.filter != null && rij.filter.hasAction(action)) {
7719 if (DEBUG_INTENT_MATCHING) Log.v(
7720 TAG, "Removing duplicate item from " + j
7721 + " due to action " + action + " at " + i);
7728 // If the caller didn't request filter information, drop it now
7729 // so we don't have to marshall/unmarshall it.
7730 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7735 // Filter out the caller activity if so requested.
7736 if (caller != null) {
7738 for (int i=0; i<N; i++) {
7739 ActivityInfo ainfo = results.get(i).activityInfo;
7740 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7741 && caller.getClassName().equals(ainfo.name)) {
7748 // If the caller didn't request filter information,
7749 // drop them now so we don't have to
7750 // marshall/unmarshall it.
7751 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7753 for (int i=0; i<N; i++) {
7754 results.get(i).filter = null;
7758 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7763 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7764 String resolvedType, int flags, int userId) {
7765 return new ParceledListSlice<>(
7766 queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7769 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7770 String resolvedType, int flags, int userId) {
7771 if (!sUserManager.exists(userId)) return Collections.emptyList();
7772 final int callingUid = Binder.getCallingUid();
7773 final String instantAppPkgName = getInstantAppPackageName(callingUid);
7774 flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7775 false /*includeInstantApps*/);
7776 ComponentName comp = intent.getComponent();
7778 if (intent.getSelector() != null) {
7779 intent = intent.getSelector();
7780 comp = intent.getComponent();
7784 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7785 final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7787 // When specifying an explicit component, we prevent the activity from being
7788 // used when either 1) the calling package is normal and the activity is within
7789 // an instant application or 2) the calling package is ephemeral and the
7790 // activity is not visible to instant applications.
7791 final boolean matchInstantApp =
7792 (flags & PackageManager.MATCH_INSTANT) != 0;
7793 final boolean matchVisibleToInstantAppOnly =
7794 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7795 final boolean matchExplicitlyVisibleOnly =
7796 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7797 final boolean isCallerInstantApp =
7798 instantAppPkgName != null;
7799 final boolean isTargetSameInstantApp =
7800 comp.getPackageName().equals(instantAppPkgName);
7801 final boolean isTargetInstantApp =
7802 (ai.applicationInfo.privateFlags
7803 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7804 final boolean isTargetVisibleToInstantApp =
7805 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7806 final boolean isTargetExplicitlyVisibleToInstantApp =
7807 isTargetVisibleToInstantApp
7808 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7809 final boolean isTargetHiddenFromInstantApp =
7810 !isTargetVisibleToInstantApp
7811 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7812 final boolean blockResolution =
7813 !isTargetSameInstantApp
7814 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7815 || (matchVisibleToInstantAppOnly && isCallerInstantApp
7816 && isTargetHiddenFromInstantApp));
7817 if (!blockResolution) {
7818 ResolveInfo ri = new ResolveInfo();
7819 ri.activityInfo = ai;
7823 return applyPostResolutionFilter(list, instantAppPkgName);
7827 synchronized (mPackages) {
7828 String pkgName = intent.getPackage();
7829 if (pkgName == null) {
7830 final List<ResolveInfo> result =
7831 mReceivers.queryIntent(intent, resolvedType, flags, userId);
7832 return applyPostResolutionFilter(result, instantAppPkgName);
7834 final PackageParser.Package pkg = mPackages.get(pkgName);
7836 final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7837 intent, resolvedType, flags, pkg.receivers, userId);
7838 return applyPostResolutionFilter(result, instantAppPkgName);
7840 return Collections.emptyList();
7845 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7846 final int callingUid = Binder.getCallingUid();
7847 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7850 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7851 int userId, int callingUid) {
7852 if (!sUserManager.exists(userId)) return null;
7853 flags = updateFlagsForResolve(
7854 flags, userId, intent, callingUid, false /*includeInstantApps*/);
7855 List<ResolveInfo> query = queryIntentServicesInternal(
7856 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7857 if (query != null) {
7858 if (query.size() >= 1) {
7859 // If there is more than one service with the same priority,
7860 // just arbitrarily pick the first one.
7861 return query.get(0);
7868 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7869 String resolvedType, int flags, int userId) {
7870 final int callingUid = Binder.getCallingUid();
7871 return new ParceledListSlice<>(queryIntentServicesInternal(
7872 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7875 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7876 String resolvedType, int flags, int userId, int callingUid,
7877 boolean includeInstantApps) {
7878 if (!sUserManager.exists(userId)) return Collections.emptyList();
7879 final String instantAppPkgName = getInstantAppPackageName(callingUid);
7880 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7881 ComponentName comp = intent.getComponent();
7883 if (intent.getSelector() != null) {
7884 intent = intent.getSelector();
7885 comp = intent.getComponent();
7889 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7890 final ServiceInfo si = getServiceInfo(comp, flags, userId);
7892 // When specifying an explicit component, we prevent the service from being
7893 // used when either 1) the service is in an instant application and the
7894 // caller is not the same instant application or 2) the calling package is
7895 // ephemeral and the activity is not visible to ephemeral applications.
7896 final boolean matchInstantApp =
7897 (flags & PackageManager.MATCH_INSTANT) != 0;
7898 final boolean matchVisibleToInstantAppOnly =
7899 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7900 final boolean isCallerInstantApp =
7901 instantAppPkgName != null;
7902 final boolean isTargetSameInstantApp =
7903 comp.getPackageName().equals(instantAppPkgName);
7904 final boolean isTargetInstantApp =
7905 (si.applicationInfo.privateFlags
7906 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7907 final boolean isTargetHiddenFromInstantApp =
7908 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7909 final boolean blockResolution =
7910 !isTargetSameInstantApp
7911 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7912 || (matchVisibleToInstantAppOnly && isCallerInstantApp
7913 && isTargetHiddenFromInstantApp));
7914 if (!blockResolution) {
7915 final ResolveInfo ri = new ResolveInfo();
7916 ri.serviceInfo = si;
7924 synchronized (mPackages) {
7925 String pkgName = intent.getPackage();
7926 if (pkgName == null) {
7927 return applyPostServiceResolutionFilter(
7928 mServices.queryIntent(intent, resolvedType, flags, userId),
7931 final PackageParser.Package pkg = mPackages.get(pkgName);
7933 return applyPostServiceResolutionFilter(
7934 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7938 return Collections.emptyList();
7942 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7943 String instantAppPkgName) {
7944 // TODO: When adding on-demand split support for non-instant apps, remove this check
7945 // and always apply post filtering
7946 if (instantAppPkgName == null) {
7947 return resolveInfos;
7949 for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7950 final ResolveInfo info = resolveInfos.get(i);
7951 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7952 // allow services that are defined in the provided package
7953 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7954 if (info.serviceInfo.splitName != null
7955 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7956 info.serviceInfo.splitName)) {
7957 // requested service is defined in a split that hasn't been installed yet.
7958 // add the installer to the resolve list
7959 if (DEBUG_EPHEMERAL) {
7960 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7962 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7963 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7964 info.serviceInfo.packageName, info.serviceInfo.splitName,
7965 info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7966 // make sure this resolver is the default
7967 installerInfo.isDefault = true;
7968 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7969 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7970 // add a non-generic filter
7971 installerInfo.filter = new IntentFilter();
7972 // load resources from the correct package
7973 installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7974 resolveInfos.set(i, installerInfo);
7978 // allow services that have been explicitly exposed to ephemeral apps
7980 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7983 resolveInfos.remove(i);
7985 return resolveInfos;
7989 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7990 String resolvedType, int flags, int userId) {
7991 return new ParceledListSlice<>(
7992 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7995 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7996 Intent intent, String resolvedType, int flags, int userId) {
7997 if (!sUserManager.exists(userId)) return Collections.emptyList();
7998 final int callingUid = Binder.getCallingUid();
7999 final String instantAppPkgName = getInstantAppPackageName(callingUid);
8000 flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8001 false /*includeInstantApps*/);
8002 ComponentName comp = intent.getComponent();
8004 if (intent.getSelector() != null) {
8005 intent = intent.getSelector();
8006 comp = intent.getComponent();
8010 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8011 final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8013 // When specifying an explicit component, we prevent the provider from being
8014 // used when either 1) the provider is in an instant application and the
8015 // caller is not the same instant application or 2) the calling package is an
8016 // instant application and the provider is not visible to instant applications.
8017 final boolean matchInstantApp =
8018 (flags & PackageManager.MATCH_INSTANT) != 0;
8019 final boolean matchVisibleToInstantAppOnly =
8020 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8021 final boolean isCallerInstantApp =
8022 instantAppPkgName != null;
8023 final boolean isTargetSameInstantApp =
8024 comp.getPackageName().equals(instantAppPkgName);
8025 final boolean isTargetInstantApp =
8026 (pi.applicationInfo.privateFlags
8027 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8028 final boolean isTargetHiddenFromInstantApp =
8029 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8030 final boolean blockResolution =
8031 !isTargetSameInstantApp
8032 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8033 || (matchVisibleToInstantAppOnly && isCallerInstantApp
8034 && isTargetHiddenFromInstantApp));
8035 if (!blockResolution) {
8036 final ResolveInfo ri = new ResolveInfo();
8037 ri.providerInfo = pi;
8045 synchronized (mPackages) {
8046 String pkgName = intent.getPackage();
8047 if (pkgName == null) {
8048 return applyPostContentProviderResolutionFilter(
8049 mProviders.queryIntent(intent, resolvedType, flags, userId),
8052 final PackageParser.Package pkg = mPackages.get(pkgName);
8054 return applyPostContentProviderResolutionFilter(
8055 mProviders.queryIntentForPackage(
8056 intent, resolvedType, flags, pkg.providers, userId),
8059 return Collections.emptyList();
8063 private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8064 List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8065 // TODO: When adding on-demand split support for non-instant applications, remove
8066 // this check and always apply post filtering
8067 if (instantAppPkgName == null) {
8068 return resolveInfos;
8070 for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8071 final ResolveInfo info = resolveInfos.get(i);
8072 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8073 // allow providers that are defined in the provided package
8074 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8075 if (info.providerInfo.splitName != null
8076 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8077 info.providerInfo.splitName)) {
8078 // requested provider is defined in a split that hasn't been installed yet.
8079 // add the installer to the resolve list
8080 if (DEBUG_EPHEMERAL) {
8081 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8083 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8084 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8085 info.providerInfo.packageName, info.providerInfo.splitName,
8086 info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8087 // make sure this resolver is the default
8088 installerInfo.isDefault = true;
8089 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8090 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8091 // add a non-generic filter
8092 installerInfo.filter = new IntentFilter();
8093 // load resources from the correct package
8094 installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8095 resolveInfos.set(i, installerInfo);
8099 // allow providers that have been explicitly exposed to instant applications
8101 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8104 resolveInfos.remove(i);
8106 return resolveInfos;
8110 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8111 final int callingUid = Binder.getCallingUid();
8112 if (getInstantAppPackageName(callingUid) != null) {
8113 return ParceledListSlice.emptyList();
8115 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8116 flags = updateFlagsForPackage(flags, userId, null);
8117 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8118 enforceCrossUserPermission(callingUid, userId,
8119 true /* requireFullPermission */, false /* checkShell */,
8120 "get installed packages");
8123 synchronized (mPackages) {
8124 ArrayList<PackageInfo> list;
8125 if (listUninstalled) {
8126 list = new ArrayList<>(mSettings.mPackages.size());
8127 for (PackageSetting ps : mSettings.mPackages.values()) {
8128 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8131 if (filterAppAccessLPr(ps, callingUid, userId)) {
8134 final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8140 list = new ArrayList<>(mPackages.size());
8141 for (PackageParser.Package p : mPackages.values()) {
8142 final PackageSetting ps = (PackageSetting) p.mExtras;
8143 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8146 if (filterAppAccessLPr(ps, callingUid, userId)) {
8149 final PackageInfo pi = generatePackageInfo((PackageSetting)
8150 p.mExtras, flags, userId);
8157 return new ParceledListSlice<>(list);
8161 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8162 String[] permissions, boolean[] tmp, int flags, int userId) {
8164 final PermissionsState permissionsState = ps.getPermissionsState();
8165 for (int i=0; i<permissions.length; i++) {
8166 final String permission = permissions[i];
8167 if (permissionsState.hasPermission(permission, userId)) {
8174 if (numMatch == 0) {
8177 final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8179 // The above might return null in cases of uninstalled apps or install-state
8180 // skew across users/profiles.
8182 if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8183 if (numMatch == permissions.length) {
8184 pi.requestedPermissions = permissions;
8186 pi.requestedPermissions = new String[numMatch];
8188 for (int i=0; i<permissions.length; i++) {
8190 pi.requestedPermissions[numMatch] = permissions[i];
8201 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8202 String[] permissions, int flags, int userId) {
8203 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8204 flags = updateFlagsForPackage(flags, userId, permissions);
8205 enforceCrossUserPermission(Binder.getCallingUid(), userId,
8206 true /* requireFullPermission */, false /* checkShell */,
8207 "get packages holding permissions");
8208 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8211 synchronized (mPackages) {
8212 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8213 boolean[] tmpBools = new boolean[permissions.length];
8214 if (listUninstalled) {
8215 for (PackageSetting ps : mSettings.mPackages.values()) {
8216 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8220 for (PackageParser.Package pkg : mPackages.values()) {
8221 PackageSetting ps = (PackageSetting)pkg.mExtras;
8223 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8229 return new ParceledListSlice<PackageInfo>(list);
8234 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8235 final int callingUid = Binder.getCallingUid();
8236 if (getInstantAppPackageName(callingUid) != null) {
8237 return ParceledListSlice.emptyList();
8239 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8240 flags = updateFlagsForApplication(flags, userId, null);
8241 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8244 synchronized (mPackages) {
8245 ArrayList<ApplicationInfo> list;
8246 if (listUninstalled) {
8247 list = new ArrayList<>(mSettings.mPackages.size());
8248 for (PackageSetting ps : mSettings.mPackages.values()) {
8250 int effectiveFlags = flags;
8251 if (ps.isSystem()) {
8252 effectiveFlags |= PackageManager.MATCH_ANY_USER;
8254 if (ps.pkg != null) {
8255 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8258 if (filterAppAccessLPr(ps, callingUid, userId)) {
8261 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8262 ps.readUserState(userId), userId);
8264 ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8267 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8268 // and already converts to externally visible package name
8269 ai = generateApplicationInfoFromSettingsLPw(ps.name,
8270 callingUid, effectiveFlags, userId);
8277 list = new ArrayList<>(mPackages.size());
8278 for (PackageParser.Package p : mPackages.values()) {
8279 if (p.mExtras != null) {
8280 PackageSetting ps = (PackageSetting) p.mExtras;
8281 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8284 if (filterAppAccessLPr(ps, callingUid, userId)) {
8287 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8288 ps.readUserState(userId), userId);
8290 ai.packageName = resolveExternalPackageNameLPr(p);
8297 return new ParceledListSlice<>(list);
8302 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8303 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8306 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8307 "getEphemeralApplications");
8308 enforceCrossUserPermission(Binder.getCallingUid(), userId,
8309 true /* requireFullPermission */, false /* checkShell */,
8310 "getEphemeralApplications");
8311 synchronized (mPackages) {
8312 List<InstantAppInfo> instantApps = mInstantAppRegistry
8313 .getInstantAppsLPr(userId);
8314 if (instantApps != null) {
8315 return new ParceledListSlice<>(instantApps);
8322 public boolean isInstantApp(String packageName, int userId) {
8323 enforceCrossUserPermission(Binder.getCallingUid(), userId,
8324 true /* requireFullPermission */, false /* checkShell */,
8326 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8329 int callingUid = Binder.getCallingUid();
8330 if (Process.isIsolated(callingUid)) {
8331 callingUid = mIsolatedOwners.get(callingUid);
8334 synchronized (mPackages) {
8335 final PackageSetting ps = mSettings.mPackages.get(packageName);
8336 PackageParser.Package pkg = mPackages.get(packageName);
8337 final boolean returnAllowed =
8339 && (isCallerSameApp(packageName, callingUid)
8340 || canViewInstantApps(callingUid, userId)
8341 || mInstantAppRegistry.isInstantAccessGranted(
8342 userId, UserHandle.getAppId(callingUid), ps.appId));
8343 if (returnAllowed) {
8344 return ps.getInstantApp(userId);
8351 public byte[] getInstantAppCookie(String packageName, int userId) {
8352 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8356 enforceCrossUserPermission(Binder.getCallingUid(), userId,
8357 true /* requireFullPermission */, false /* checkShell */,
8358 "getInstantAppCookie");
8359 if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8362 synchronized (mPackages) {
8363 return mInstantAppRegistry.getInstantAppCookieLPw(
8364 packageName, userId);
8369 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8370 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8374 enforceCrossUserPermission(Binder.getCallingUid(), userId,
8375 true /* requireFullPermission */, true /* checkShell */,
8376 "setInstantAppCookie");
8377 if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8380 synchronized (mPackages) {
8381 return mInstantAppRegistry.setInstantAppCookieLPw(
8382 packageName, cookie, userId);
8387 public Bitmap getInstantAppIcon(String packageName, int userId) {
8388 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8392 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8393 "getInstantAppIcon");
8395 enforceCrossUserPermission(Binder.getCallingUid(), userId,
8396 true /* requireFullPermission */, false /* checkShell */,
8397 "getInstantAppIcon");
8399 synchronized (mPackages) {
8400 return mInstantAppRegistry.getInstantAppIconLPw(
8401 packageName, userId);
8405 private boolean isCallerSameApp(String packageName, int uid) {
8406 PackageParser.Package pkg = mPackages.get(packageName);
8408 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8412 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8413 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8414 return ParceledListSlice.emptyList();
8416 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8419 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8420 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8423 synchronized (mPackages) {
8424 final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8425 final int userId = UserHandle.getCallingUserId();
8426 while (i.hasNext()) {
8427 final PackageParser.Package p = i.next();
8428 if (p.applicationInfo == null) continue;
8430 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8431 && !p.applicationInfo.isDirectBootAware();
8432 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8433 && p.applicationInfo.isDirectBootAware();
8435 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8436 && (!mSafeMode || isSystemApp(p))
8437 && (matchesUnaware || matchesAware)) {
8438 PackageSetting ps = mSettings.mPackages.get(p.packageName);
8440 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8441 ps.readUserState(userId), userId);
8454 public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8455 if (!sUserManager.exists(userId)) return null;
8456 flags = updateFlagsForComponent(flags, userId, name);
8457 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8459 synchronized (mPackages) {
8460 final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8461 PackageSetting ps = provider != null
8462 ? mSettings.mPackages.get(provider.owner.packageName)
8465 final boolean isInstantApp = ps.getInstantApp(userId);
8466 // normal application; filter out instant application provider
8467 if (instantAppPkgName == null && isInstantApp) {
8470 // instant application; filter out other instant applications
8471 if (instantAppPkgName != null
8473 && !provider.owner.packageName.equals(instantAppPkgName)) {
8476 // instant application; filter out non-exposed provider
8477 if (instantAppPkgName != null
8479 && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8482 // provider not enabled
8483 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8486 return PackageParser.generateProviderInfo(
8487 provider, flags, ps.readUserState(userId), userId);
8497 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8498 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8502 synchronized (mPackages) {
8503 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8504 .entrySet().iterator();
8505 final int userId = UserHandle.getCallingUserId();
8506 while (i.hasNext()) {
8507 Map.Entry<String, PackageParser.Provider> entry = i.next();
8508 PackageParser.Provider p = entry.getValue();
8509 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8511 if (ps != null && p.syncable
8512 && (!mSafeMode || (p.info.applicationInfo.flags
8513 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8514 ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8515 ps.readUserState(userId), userId);
8517 outNames.add(entry.getKey());
8526 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8527 int uid, int flags, String metaDataKey) {
8528 final int callingUid = Binder.getCallingUid();
8529 final int userId = processName != null ? UserHandle.getUserId(uid)
8530 : UserHandle.getCallingUserId();
8531 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8532 flags = updateFlagsForComponent(flags, userId, processName);
8533 ArrayList<ProviderInfo> finalList = null;
8535 synchronized (mPackages) {
8536 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8537 while (i.hasNext()) {
8538 final PackageParser.Provider p = i.next();
8539 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8540 if (ps != null && p.info.authority != null
8541 && (processName == null
8542 || (p.info.processName.equals(processName)
8543 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8544 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8546 // See PM.queryContentProviders()'s javadoc for why we have the metaData
8548 if (metaDataKey != null
8549 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8552 final ComponentName component =
8553 new ComponentName(p.info.packageName, p.info.name);
8554 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8557 if (finalList == null) {
8558 finalList = new ArrayList<ProviderInfo>(3);
8560 ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8561 ps.readUserState(userId), userId);
8563 finalList.add(info);
8569 if (finalList != null) {
8570 Collections.sort(finalList, mProviderInitOrderSorter);
8571 return new ParceledListSlice<ProviderInfo>(finalList);
8574 return ParceledListSlice.emptyList();
8578 public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8580 synchronized (mPackages) {
8581 final int callingUid = Binder.getCallingUid();
8582 final int callingUserId = UserHandle.getUserId(callingUid);
8583 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8584 if (ps == null) return null;
8585 if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8588 final PackageParser.Instrumentation i = mInstrumentation.get(component);
8589 return PackageParser.generateInstrumentationInfo(i, flags);
8594 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8595 String targetPackage, int flags) {
8596 final int callingUid = Binder.getCallingUid();
8597 final int callingUserId = UserHandle.getUserId(callingUid);
8598 final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8599 if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8600 return ParceledListSlice.emptyList();
8602 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8605 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8607 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8610 synchronized (mPackages) {
8611 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8612 while (i.hasNext()) {
8613 final PackageParser.Instrumentation p = i.next();
8614 if (targetPackage == null
8615 || targetPackage.equals(p.info.targetPackage)) {
8616 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8628 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8629 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8631 scanDirLI(dir, parseFlags, scanFlags, currentTime);
8633 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8637 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8638 final File[] files = dir.listFiles();
8639 if (ArrayUtils.isEmpty(files)) {
8640 Log.d(TAG, "No files in app dir " + dir);
8644 if (DEBUG_PACKAGE_SCANNING) {
8645 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8646 + " flags=0x" + Integer.toHexString(parseFlags));
8648 ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8649 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8650 mParallelPackageParserCallback);
8652 // Submit files for parsing in parallel
8654 for (File file : files) {
8655 final boolean isPackage = (isApkFile(file) || file.isDirectory())
8656 && !PackageInstallerService.isStageName(file.getName());
8658 // Ignore entries which are not packages
8661 parallelPackageParser.submit(file, parseFlags);
8665 // Process results one by one
8666 for (; fileCount > 0; fileCount--) {
8667 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8668 Throwable throwable = parseResult.throwable;
8669 int errorCode = PackageManager.INSTALL_SUCCEEDED;
8671 if (throwable == null) {
8672 // Static shared libraries have synthetic package names
8673 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8674 renameStaticSharedLibraryPackage(parseResult.pkg);
8677 if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8678 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8681 } catch (PackageManagerException e) {
8682 errorCode = e.error;
8683 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8685 } else if (throwable instanceof PackageParser.PackageParserException) {
8686 PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8688 errorCode = e.error;
8689 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8691 throw new IllegalStateException("Unexpected exception occurred while parsing "
8692 + parseResult.scanFile, throwable);
8695 // Delete invalid userdata apps
8696 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8697 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8698 logCriticalInfo(Log.WARN,
8699 "Deleting invalid package at " + parseResult.scanFile);
8700 removeCodePathLI(parseResult.scanFile);
8703 parallelPackageParser.close();
8706 private static File getSettingsProblemFile() {
8707 File dataDir = Environment.getDataDirectory();
8708 File systemDir = new File(dataDir, "system");
8709 File fname = new File(systemDir, "uiderrors.txt");
8713 static void reportSettingsProblem(int priority, String msg) {
8714 logCriticalInfo(priority, msg);
8717 public static void logCriticalInfo(int priority, String msg) {
8718 Slog.println(priority, TAG, msg);
8719 EventLogTags.writePmCriticalInfo(msg);
8721 File fname = getSettingsProblemFile();
8722 FileOutputStream out = new FileOutputStream(fname, true);
8723 PrintWriter pw = new FastPrintWriter(out);
8724 SimpleDateFormat formatter = new SimpleDateFormat();
8725 String dateString = formatter.format(new Date(System.currentTimeMillis()));
8726 pw.println(dateString + ": " + msg);
8728 FileUtils.setPermissions(
8730 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8732 } catch (java.io.IOException e) {
8736 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8737 if (srcFile.isDirectory()) {
8738 final File baseFile = new File(pkg.baseCodePath);
8739 long maxModifiedTime = baseFile.lastModified();
8740 if (pkg.splitCodePaths != null) {
8741 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8742 final File splitFile = new File(pkg.splitCodePaths[i]);
8743 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8746 return maxModifiedTime;
8748 return srcFile.lastModified();
8751 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8752 final int policyFlags) throws PackageManagerException {
8753 // When upgrading from pre-N MR1, verify the package time stamp using the package
8754 // directory and not the APK file.
8755 final long lastModifiedTime = mIsPreNMR1Upgrade
8756 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8758 && ps.codePath.equals(srcFile)
8759 && ps.timeStamp == lastModifiedTime
8760 && !isCompatSignatureUpdateNeeded(pkg)
8761 && !isRecoverSignatureUpdateNeeded(pkg)) {
8762 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8763 KeySetManagerService ksms = mSettings.mKeySetManagerService;
8764 ArraySet<PublicKey> signingKs;
8765 synchronized (mPackages) {
8766 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8768 if (ps.signatures.mSignatures != null
8769 && ps.signatures.mSignatures.length != 0
8770 && signingKs != null) {
8771 // Optimization: reuse the existing cached certificates
8772 // if the package appears to be unchanged.
8773 pkg.mSignatures = ps.signatures.mSignatures;
8774 pkg.mSigningKeys = signingKs;
8778 Slog.w(TAG, "PackageSetting for " + ps.name
8779 + " is missing signatures. Collecting certs again to recover them.");
8781 Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8785 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8786 PackageParser.collectCertificates(pkg, policyFlags);
8787 } catch (PackageParserException e) {
8788 throw PackageManagerException.from(e);
8790 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8795 * Traces a package scan.
8796 * @see #scanPackageLI(File, int, int, long, UserHandle)
8798 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8799 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8800 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8802 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8804 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8809 * Scans a package and returns the newly parsed package.
8810 * Returns {@code null} in case of errors and the error code is stored in mLastScanError
8812 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8813 long currentTime, UserHandle user) throws PackageManagerException {
8814 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8815 PackageParser pp = new PackageParser();
8816 pp.setSeparateProcesses(mSeparateProcesses);
8817 pp.setOnlyCoreApps(mOnlyCore);
8818 pp.setDisplayMetrics(mMetrics);
8819 pp.setCallback(mPackageParserCallback);
8821 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8822 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8825 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8826 final PackageParser.Package pkg;
8828 pkg = pp.parsePackage(scanFile, parseFlags);
8829 } catch (PackageParserException e) {
8830 throw PackageManagerException.from(e);
8832 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8835 // Static shared libraries have synthetic package names
8836 if (pkg.applicationInfo.isStaticSharedLibrary()) {
8837 renameStaticSharedLibraryPackage(pkg);
8840 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8844 * Scans a package and returns the newly parsed package.
8845 * @throws PackageManagerException on a parse error.
8847 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8848 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8849 throws PackageManagerException {
8850 // If the package has children and this is the first dive in the function
8851 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8852 // packages (parent and children) would be successfully scanned before the
8853 // actual scan since scanning mutates internal state and we want to atomically
8854 // install the package and its children.
8855 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8856 if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8857 scanFlags |= SCAN_CHECK_ONLY;
8860 scanFlags &= ~SCAN_CHECK_ONLY;
8864 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8865 scanFlags, currentTime, user);
8867 // Scan the children
8868 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8869 for (int i = 0; i < childCount; i++) {
8870 PackageParser.Package childPackage = pkg.childPackages.get(i);
8871 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8876 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8877 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8884 * Scans a package and returns the newly parsed package.
8885 * @throws PackageManagerException on a parse error.
8887 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8888 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8889 throws PackageManagerException {
8890 PackageSetting ps = null;
8891 PackageSetting updatedPkg;
8893 synchronized (mPackages) {
8894 // Look to see if we already know about this package.
8895 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8896 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8897 // This package has been renamed to its original name. Let's
8899 ps = mSettings.getPackageLPr(oldName);
8901 // If there was no original package, see one for the real package name.
8903 ps = mSettings.getPackageLPr(pkg.packageName);
8905 // Check to see if this package could be hiding/updating a system
8906 // package. Must look for it either under the original or real
8907 // package name depending on our state.
8908 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8909 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8911 // If this is a package we don't know about on the system partition, we
8912 // may need to remove disabled child packages on the system partition
8913 // or may need to not add child packages if the parent apk is updated
8914 // on the data partition and no longer defines this child package.
8915 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8916 // If this is a parent package for an updated system app and this system
8917 // app got an OTA update which no longer defines some of the child packages
8918 // we have to prune them from the disabled system packages.
8919 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8920 if (disabledPs != null) {
8921 final int scannedChildCount = (pkg.childPackages != null)
8922 ? pkg.childPackages.size() : 0;
8923 final int disabledChildCount = disabledPs.childPackageNames != null
8924 ? disabledPs.childPackageNames.size() : 0;
8925 for (int i = 0; i < disabledChildCount; i++) {
8926 String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8927 boolean disabledPackageAvailable = false;
8928 for (int j = 0; j < scannedChildCount; j++) {
8929 PackageParser.Package childPkg = pkg.childPackages.get(j);
8930 if (childPkg.packageName.equals(disabledChildPackageName)) {
8931 disabledPackageAvailable = true;
8935 if (!disabledPackageAvailable) {
8936 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8943 boolean updatedPkgBetter = false;
8944 // First check if this is a system package that may involve an update
8945 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8946 // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8947 // it needs to drop FLAG_PRIVILEGED.
8948 if (locationIsPrivileged(scanFile)) {
8949 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8951 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8954 if (ps != null && !ps.codePath.equals(scanFile)) {
8955 // The path has changed from what was last scanned... check the
8956 // version of the new path against what we have stored to determine
8958 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8959 if (pkg.mVersionCode <= ps.versionCode) {
8960 // The system package has been updated and the code path does not match
8961 // Ignore entry. Skip it.
8962 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8963 + " ignored: updated version " + ps.versionCode
8964 + " better than this " + pkg.mVersionCode);
8965 if (!updatedPkg.codePath.equals(scanFile)) {
8966 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8967 + ps.name + " changing from " + updatedPkg.codePathString
8968 + " to " + scanFile);
8969 updatedPkg.codePath = scanFile;
8970 updatedPkg.codePathString = scanFile.toString();
8971 updatedPkg.resourcePath = scanFile;
8972 updatedPkg.resourcePathString = scanFile.toString();
8974 updatedPkg.pkg = pkg;
8975 updatedPkg.versionCode = pkg.mVersionCode;
8977 // Update the disabled system child packages to point to the package too.
8978 final int childCount = updatedPkg.childPackageNames != null
8979 ? updatedPkg.childPackageNames.size() : 0;
8980 for (int i = 0; i < childCount; i++) {
8981 String childPackageName = updatedPkg.childPackageNames.get(i);
8982 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8984 if (updatedChildPkg != null) {
8985 updatedChildPkg.pkg = pkg;
8986 updatedChildPkg.versionCode = pkg.mVersionCode;
8990 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8991 + scanFile + " ignored: updated version " + ps.versionCode
8992 + " better than this " + pkg.mVersionCode);
8994 // The current app on the system partition is better than
8995 // what we have updated to on the data partition; switch
8996 // back to the system partition version.
8997 // At this point, its safely assumed that package installation for
8998 // apps in system partition will go through. If not there won't be a working
8999 // version of the app
9001 synchronized (mPackages) {
9002 // Just remove the loaded entries from package lists.
9003 mPackages.remove(ps.name);
9006 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9007 + " reverting from " + ps.codePathString
9008 + ": new version " + pkg.mVersionCode
9009 + " better than installed " + ps.versionCode);
9011 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9012 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9013 synchronized (mInstallLock) {
9014 args.cleanUpResourcesLI();
9016 synchronized (mPackages) {
9017 mSettings.enableSystemPackageLPw(ps.name);
9019 updatedPkgBetter = true;
9024 if (updatedPkg != null) {
9025 // An updated system app will not have the PARSE_IS_SYSTEM flag set
9027 policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9029 // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9030 // flag set initially
9031 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9032 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9036 // Verify certificates against what was last scanned
9037 collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9040 * A new system app appeared, but we already had a non-system one of the
9041 * same name installed earlier.
9043 boolean shouldHideSystemApp = false;
9044 if (updatedPkg == null && ps != null
9045 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9047 * Check to make sure the signatures match first. If they don't,
9048 * wipe the installed application and its data.
9050 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9051 != PackageManager.SIGNATURE_MATCH) {
9052 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9053 + " signatures don't match existing userdata copy; removing");
9054 try (PackageFreezer freezer = freezePackage(pkg.packageName,
9055 "scanPackageInternalLI")) {
9056 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9061 * If the newly-added system app is an older version than the
9062 * already installed version, hide it. It will be scanned later
9063 * and re-added like an update.
9065 if (pkg.mVersionCode <= ps.versionCode) {
9066 shouldHideSystemApp = true;
9067 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9068 + " but new version " + pkg.mVersionCode + " better than installed "
9069 + ps.versionCode + "; hiding system");
9072 * The newly found system app is a newer version that the
9073 * one previously installed. Simply remove the
9074 * already-installed application and replace it with our own
9075 * while keeping the application data.
9077 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9078 + " reverting from " + ps.codePathString + ": new version "
9079 + pkg.mVersionCode + " better than installed " + ps.versionCode);
9080 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9081 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9082 synchronized (mInstallLock) {
9083 args.cleanUpResourcesLI();
9089 // The apk is forward locked (not public) if its code and resources
9090 // are kept in different files. (except for app in either system or
9092 // TODO grab this value from PackageSettings
9093 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9094 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9095 policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9099 // TODO: extend to support forward-locked splits
9100 String resourcePath = null;
9101 String baseResourcePath = null;
9102 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
9103 if (ps != null && ps.resourcePathString != null) {
9104 resourcePath = ps.resourcePathString;
9105 baseResourcePath = ps.resourcePathString;
9107 // Should not happen at all. Just log an error.
9108 Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9111 resourcePath = pkg.codePath;
9112 baseResourcePath = pkg.baseCodePath;
9115 // Set application objects path explicitly.
9116 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9117 pkg.setApplicationInfoCodePath(pkg.codePath);
9118 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9119 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9120 pkg.setApplicationInfoResourcePath(resourcePath);
9121 pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9122 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9124 final int userId = ((user == null) ? 0 : user.getIdentifier());
9125 if (ps != null && ps.getInstantApp(userId)) {
9126 scanFlags |= SCAN_AS_INSTANT_APP;
9129 // Note that we invoke the following method only if we are about to unpack an application
9130 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9131 | SCAN_UPDATE_SIGNATURE, currentTime, user);
9134 * If the system app should be overridden by a previously installed
9135 * data, hide the system app now and let the /data/app scan pick it up
9138 if (shouldHideSystemApp) {
9139 synchronized (mPackages) {
9140 mSettings.disableSystemPackageLPw(pkg.packageName, true);
9147 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9148 // Derive the new package synthetic package name
9149 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9150 + pkg.staticSharedLibVersion);
9153 private static String fixProcessName(String defProcessName,
9154 String processName) {
9155 if (processName == null) {
9156 return defProcessName;
9161 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9162 throws PackageManagerException {
9163 if (pkgSetting.signatures.mSignatures != null) {
9164 // Already existing package. Make sure signatures match
9165 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9166 == PackageManager.SIGNATURE_MATCH;
9168 match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9169 == PackageManager.SIGNATURE_MATCH;
9172 match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9173 == PackageManager.SIGNATURE_MATCH;
9176 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9177 + pkg.packageName + " signatures do not match the "
9178 + "previously installed version; ignoring!");
9182 // Check for shared user signatures
9183 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9184 // Already existing package. Make sure signatures match
9185 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9186 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9188 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9189 == PackageManager.SIGNATURE_MATCH;
9192 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9193 == PackageManager.SIGNATURE_MATCH;
9196 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9197 "Package " + pkg.packageName
9198 + " has no signatures that match those in shared user "
9199 + pkgSetting.sharedUser.name + "; ignoring!");
9205 * Enforces that only the system UID or root's UID can call a method exposed
9208 * @param message used as message if SecurityException is thrown
9209 * @throws SecurityException if the caller is not system or root
9211 private static final void enforceSystemOrRoot(String message) {
9212 final int uid = Binder.getCallingUid();
9213 if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9214 throw new SecurityException(message);
9219 public void performFstrimIfNeeded() {
9220 enforceSystemOrRoot("Only the system can request fstrim");
9222 // Before everything else, see whether we need to fstrim.
9224 IStorageManager sm = PackageHelper.getStorageManager();
9226 boolean doTrim = false;
9227 final long interval = android.provider.Settings.Global.getLong(
9228 mContext.getContentResolver(),
9229 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9230 DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9232 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9233 if (timeSinceLast > interval) {
9235 Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9236 + "; running immediately");
9240 final boolean dexOptDialogShown;
9241 synchronized (mPackages) {
9242 dexOptDialogShown = mDexOptDialogShown;
9244 if (!isFirstBoot() && dexOptDialogShown) {
9246 ActivityManager.getService().showBootMessage(
9247 mContext.getResources().getString(
9248 R.string.android_upgrading_fstrim), true);
9249 } catch (RemoteException e) {
9252 sm.runMaintenance();
9255 Slog.e(TAG, "storageManager service unavailable!");
9257 } catch (RemoteException e) {
9258 // Can't happen; StorageManagerService is local
9263 public void updatePackagesIfNeeded() {
9264 enforceSystemOrRoot("Only the system can request package update");
9266 // We need to re-extract after an OTA.
9267 boolean causeUpgrade = isUpgrade();
9269 // First boot or factory reset.
9270 // Note: we also handle devices that are upgrading to N right now as if it is their
9271 // first boot, as they do not have profile data.
9272 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9274 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9275 boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9277 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9281 List<PackageParser.Package> pkgs;
9282 synchronized (mPackages) {
9283 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9286 final long startTime = System.nanoTime();
9287 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9288 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
9290 final int elapsedTimeSeconds =
9291 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9293 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9294 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9295 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9296 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9297 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9301 * Performs dexopt on the set of packages in {@code packages} and returns an int array
9302 * containing statistics about the invocation. The array consists of three elements,
9303 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9304 * and {@code numberOfPackagesFailed}.
9306 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9307 String compilerFilter) {
9309 int numberOfPackagesVisited = 0;
9310 int numberOfPackagesOptimized = 0;
9311 int numberOfPackagesSkipped = 0;
9312 int numberOfPackagesFailed = 0;
9313 final int numberOfPackagesToDexopt = pkgs.size();
9315 for (PackageParser.Package pkg : pkgs) {
9316 numberOfPackagesVisited++;
9318 if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9320 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9322 numberOfPackagesSkipped++;
9327 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9328 numberOfPackagesToDexopt + ": " + pkg.packageName);
9333 ActivityManager.getService().showBootMessage(
9334 mContext.getResources().getString(R.string.android_upgrading_apk,
9335 numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9336 } catch (RemoteException e) {
9338 synchronized (mPackages) {
9339 mDexOptDialogShown = true;
9343 // If the OTA updates a system app which was previously preopted to a non-preopted state
9344 // the app might end up being verified at runtime. That's because by default the apps
9345 // are verify-profile but for preopted apps there's no profile.
9346 // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9347 // that before the OTA the app was preopted) the app gets compiled with a non-profile
9348 // filter (by default 'quicken').
9349 // Note that at this stage unused apps are already filtered.
9350 if (isSystemApp(pkg) &&
9351 DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9352 !Environment.getReferenceProfile(pkg.packageName).exists()) {
9353 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9356 // checkProfiles is false to avoid merging profiles during boot which
9357 // might interfere with background compilation (b/28612421).
9358 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9359 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9360 // trade-off worth doing to save boot time work.
9361 int dexOptStatus = performDexOptTraced(pkg.packageName,
9362 false /* checkProfiles */,
9365 switch (dexOptStatus) {
9366 case PackageDexOptimizer.DEX_OPT_PERFORMED:
9367 numberOfPackagesOptimized++;
9369 case PackageDexOptimizer.DEX_OPT_SKIPPED:
9370 numberOfPackagesSkipped++;
9372 case PackageDexOptimizer.DEX_OPT_FAILED:
9373 numberOfPackagesFailed++;
9376 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
9381 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9382 numberOfPackagesFailed };
9386 public void notifyPackageUse(String packageName, int reason) {
9387 synchronized (mPackages) {
9388 final int callingUid = Binder.getCallingUid();
9389 final int callingUserId = UserHandle.getUserId(callingUid);
9390 if (getInstantAppPackageName(callingUid) != null) {
9391 if (!isCallerSameApp(packageName, callingUid)) {
9395 if (isInstantApp(packageName, callingUserId)) {
9399 final PackageParser.Package p = mPackages.get(packageName);
9403 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9408 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9409 int userId = UserHandle.getCallingUserId();
9410 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9412 Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9413 + loadingPackageName + ", user=" + userId);
9416 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9420 public boolean performDexOpt(String packageName,
9421 boolean checkProfiles, int compileReason, boolean force) {
9422 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9424 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9427 return performDexOptWithStatus(packageName, checkProfiles, compileReason, force) !=
9428 PackageDexOptimizer.DEX_OPT_FAILED;
9432 * Perform dexopt on the given package and return one of following result:
9433 * {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9434 * {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9435 * {@link PackageDexOptimizer#DEX_OPT_FAILED}
9437 /* package */ int performDexOptWithStatus(String packageName,
9438 boolean checkProfiles, int compileReason, boolean force) {
9439 return performDexOptTraced(packageName, checkProfiles,
9440 getCompilerFilterForReason(compileReason), force);
9444 public boolean performDexOptMode(String packageName,
9445 boolean checkProfiles, String targetCompilerFilter, boolean force) {
9446 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9448 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9451 int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
9452 targetCompilerFilter, force);
9453 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9456 private int performDexOptTraced(String packageName,
9457 boolean checkProfiles, String targetCompilerFilter, boolean force) {
9458 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9460 return performDexOptInternal(packageName, checkProfiles,
9461 targetCompilerFilter, force);
9463 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9467 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9468 // if the package can now be considered up to date for the given filter.
9469 private int performDexOptInternal(String packageName,
9470 boolean checkProfiles, String targetCompilerFilter, boolean force) {
9471 PackageParser.Package p;
9472 synchronized (mPackages) {
9473 p = mPackages.get(packageName);
9475 // Package could not be found. Report failure.
9476 return PackageDexOptimizer.DEX_OPT_FAILED;
9478 mPackageUsage.maybeWriteAsync(mPackages);
9479 mCompilerStats.maybeWriteAsync();
9481 long callingId = Binder.clearCallingIdentity();
9483 synchronized (mInstallLock) {
9484 return performDexOptInternalWithDependenciesLI(p, checkProfiles,
9485 targetCompilerFilter, force);
9488 Binder.restoreCallingIdentity(callingId);
9492 public ArraySet<String> getOptimizablePackages() {
9493 ArraySet<String> pkgs = new ArraySet<String>();
9494 synchronized (mPackages) {
9495 for (PackageParser.Package p : mPackages.values()) {
9496 if (PackageDexOptimizer.canOptimizePackage(p)) {
9497 pkgs.add(p.packageName);
9504 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9505 boolean checkProfiles, String targetCompilerFilter,
9507 // Select the dex optimizer based on the force parameter.
9508 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9509 // allocate an object here.
9510 PackageDexOptimizer pdo = force
9511 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9512 : mPackageDexOptimizer;
9514 // Dexopt all dependencies first. Note: we ignore the return value and march on
9516 // Note that we are going to call performDexOpt on those libraries as many times as
9517 // they are referenced in packages. When we do a batch of performDexOpt (for example
9518 // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9519 // and the first package that uses the library will dexopt it. The
9520 // others will see that the compiled code for the library is up to date.
9521 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9522 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9523 if (!deps.isEmpty()) {
9524 for (PackageParser.Package depPackage : deps) {
9525 // TODO: Analyze and investigate if we (should) profile libraries.
9526 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9527 false /* checkProfiles */,
9528 targetCompilerFilter,
9529 getOrCreateCompilerPackageStats(depPackage),
9530 true /* isUsedByOtherApps */);
9533 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
9534 targetCompilerFilter, getOrCreateCompilerPackageStats(p),
9535 mDexManager.isUsedByOtherApps(p.packageName));
9538 // Performs dexopt on the used secondary dex files belonging to the given package.
9539 // Returns true if all dex files were process successfully (which could mean either dexopt or
9540 // skip). Returns false if any of the files caused errors.
9542 public boolean performDexOptSecondary(String packageName, String compilerFilter,
9544 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9546 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9549 mDexManager.reconcileSecondaryDexFiles(packageName);
9550 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
9553 public boolean performDexOptSecondary(String packageName, int compileReason,
9555 return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
9559 * Reconcile the information we have about the secondary dex files belonging to
9560 * {@code packagName} and the actual dex files. For all dex files that were
9561 * deleted, update the internal records and delete the generated oat files.
9564 public void reconcileSecondaryDexFiles(String packageName) {
9565 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9567 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9570 mDexManager.reconcileSecondaryDexFiles(packageName);
9573 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9574 // a reference there.
9575 /*package*/ DexManager getDexManager() {
9580 * Execute the background dexopt job immediately.
9583 public boolean runBackgroundDexoptJob() {
9584 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9587 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9590 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9591 if (p.usesLibraries != null || p.usesOptionalLibraries != null
9592 || p.usesStaticLibraries != null) {
9593 ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9594 Set<String> collectedNames = new HashSet<>();
9595 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9601 return Collections.emptyList();
9605 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9606 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9607 if (!collectedNames.contains(p.packageName)) {
9608 collectedNames.add(p.packageName);
9611 if (p.usesLibraries != null) {
9612 findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9613 null, collected, collectedNames);
9615 if (p.usesOptionalLibraries != null) {
9616 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9617 null, collected, collectedNames);
9619 if (p.usesStaticLibraries != null) {
9620 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9621 p.usesStaticLibrariesVersions, collected, collectedNames);
9626 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9627 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9628 final int libNameCount = libs.size();
9629 for (int i = 0; i < libNameCount; i++) {
9630 String libName = libs.get(i);
9631 int version = (versions != null && versions.length == libNameCount)
9632 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9633 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9634 if (libPkg != null) {
9635 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9640 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9641 synchronized (mPackages) {
9642 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9643 if (libEntry != null) {
9644 return mPackages.get(libEntry.apk);
9650 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9651 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9652 if (versionedLib == null) {
9655 return versionedLib.get(version);
9658 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9659 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9660 pkg.staticSharedLibName);
9661 if (versionedLib == null) {
9664 int previousLibVersion = -1;
9665 final int versionCount = versionedLib.size();
9666 for (int i = 0; i < versionCount; i++) {
9667 final int libVersion = versionedLib.keyAt(i);
9668 if (libVersion < pkg.staticSharedLibVersion) {
9669 previousLibVersion = Math.max(previousLibVersion, libVersion);
9672 if (previousLibVersion >= 0) {
9673 return versionedLib.get(previousLibVersion);
9678 public void shutdown() {
9679 mPackageUsage.writeNow(mPackages);
9680 mCompilerStats.writeNow();
9684 public void dumpProfiles(String packageName) {
9685 PackageParser.Package pkg;
9686 synchronized (mPackages) {
9687 pkg = mPackages.get(packageName);
9689 throw new IllegalArgumentException("Unknown package: " + packageName);
9692 /* Only the shell, root, or the app user should be able to dump profiles. */
9693 int callingUid = Binder.getCallingUid();
9694 if (callingUid != Process.SHELL_UID &&
9695 callingUid != Process.ROOT_UID &&
9696 callingUid != pkg.applicationInfo.uid) {
9697 throw new SecurityException("dumpProfiles");
9700 synchronized (mInstallLock) {
9701 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9702 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9704 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9705 String codePaths = TextUtils.join(";", allCodePaths);
9706 mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9707 } catch (InstallerException e) {
9708 Slog.w(TAG, "Failed to dump profiles", e);
9710 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9715 public void forceDexOpt(String packageName) {
9716 enforceSystemOrRoot("forceDexOpt");
9718 PackageParser.Package pkg;
9719 synchronized (mPackages) {
9720 pkg = mPackages.get(packageName);
9722 throw new IllegalArgumentException("Unknown package: " + packageName);
9726 synchronized (mInstallLock) {
9727 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9729 // Whoever is calling forceDexOpt wants a compiled package.
9730 // Don't use profiles since that may cause compilation to be skipped.
9731 final int res = performDexOptInternalWithDependenciesLI(pkg,
9732 false /* checkProfiles */, getDefaultCompilerFilter(),
9735 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9736 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9737 throw new IllegalStateException("Failed to dexopt: " + res);
9742 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9743 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9744 Slog.w(TAG, "Unable to update from " + oldPkg.name
9745 + " to " + newPkg.packageName
9746 + ": old package not in system partition");
9748 } else if (mPackages.get(oldPkg.name) != null) {
9749 Slog.w(TAG, "Unable to update from " + oldPkg.name
9750 + " to " + newPkg.packageName
9751 + ": old package still exists");
9757 void removeCodePathLI(File codePath) {
9758 if (codePath.isDirectory()) {
9760 mInstaller.rmPackageDir(codePath.getAbsolutePath());
9761 } catch (InstallerException e) {
9762 Slog.w(TAG, "Failed to remove code path", e);
9769 private int[] resolveUserIds(int userId) {
9770 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9773 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9775 Slog.wtf(TAG, "Package was null!", new Throwable());
9778 clearAppDataLeafLIF(pkg, userId, flags);
9779 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9780 for (int i = 0; i < childCount; i++) {
9781 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9785 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9786 final PackageSetting ps;
9787 synchronized (mPackages) {
9788 ps = mSettings.mPackages.get(pkg.packageName);
9790 for (int realUserId : resolveUserIds(userId)) {
9791 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9793 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9795 } catch (InstallerException e) {
9796 Slog.w(TAG, String.valueOf(e));
9801 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9803 Slog.wtf(TAG, "Package was null!", new Throwable());
9806 destroyAppDataLeafLIF(pkg, userId, flags);
9807 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9808 for (int i = 0; i < childCount; i++) {
9809 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9813 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9814 final PackageSetting ps;
9815 synchronized (mPackages) {
9816 ps = mSettings.mPackages.get(pkg.packageName);
9818 for (int realUserId : resolveUserIds(userId)) {
9819 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9821 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9823 } catch (InstallerException e) {
9824 Slog.w(TAG, String.valueOf(e));
9826 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9830 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9832 Slog.wtf(TAG, "Package was null!", new Throwable());
9835 destroyAppProfilesLeafLIF(pkg);
9836 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9837 for (int i = 0; i < childCount; i++) {
9838 destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9842 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9844 mInstaller.destroyAppProfiles(pkg.packageName);
9845 } catch (InstallerException e) {
9846 Slog.w(TAG, String.valueOf(e));
9850 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9852 Slog.wtf(TAG, "Package was null!", new Throwable());
9855 clearAppProfilesLeafLIF(pkg);
9856 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9857 for (int i = 0; i < childCount; i++) {
9858 clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9862 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9864 mInstaller.clearAppProfiles(pkg.packageName);
9865 } catch (InstallerException e) {
9866 Slog.w(TAG, String.valueOf(e));
9870 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9871 long lastUpdateTime) {
9872 // Set parent install/update time
9873 PackageSetting ps = (PackageSetting) pkg.mExtras;
9875 ps.firstInstallTime = firstInstallTime;
9876 ps.lastUpdateTime = lastUpdateTime;
9878 // Set children install/update time
9879 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9880 for (int i = 0; i < childCount; i++) {
9881 PackageParser.Package childPkg = pkg.childPackages.get(i);
9882 ps = (PackageSetting) childPkg.mExtras;
9884 ps.firstInstallTime = firstInstallTime;
9885 ps.lastUpdateTime = lastUpdateTime;
9890 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9891 PackageParser.Package changingLib) {
9892 if (file.path != null) {
9893 usesLibraryFiles.add(file.path);
9896 PackageParser.Package p = mPackages.get(file.apk);
9897 if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9898 // If we are doing this while in the middle of updating a library apk,
9899 // then we need to make sure to use that new apk for determining the
9900 // dependencies here. (We haven't yet finished committing the new apk
9901 // to the package manager state.)
9902 if (p == null || p.packageName.equals(changingLib.packageName)) {
9907 usesLibraryFiles.addAll(p.getAllCodePaths());
9908 if (p.usesLibraryFiles != null) {
9909 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9914 private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9915 PackageParser.Package changingLib) throws PackageManagerException {
9919 ArraySet<String> usesLibraryFiles = null;
9920 if (pkg.usesLibraries != null) {
9921 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9922 null, null, pkg.packageName, changingLib, true, null);
9924 if (pkg.usesStaticLibraries != null) {
9925 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9926 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9927 pkg.packageName, changingLib, true, usesLibraryFiles);
9929 if (pkg.usesOptionalLibraries != null) {
9930 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9931 null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9933 if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9934 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9936 pkg.usesLibraryFiles = null;
9940 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9941 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9942 @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9943 boolean required, @Nullable ArraySet<String> outUsedLibraries)
9944 throws PackageManagerException {
9945 final int libCount = requestedLibraries.size();
9946 for (int i = 0; i < libCount; i++) {
9947 final String libName = requestedLibraries.get(i);
9948 final int libVersion = requiredVersions != null ? requiredVersions[i]
9949 : SharedLibraryInfo.VERSION_UNDEFINED;
9950 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9951 if (libEntry == null) {
9953 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9954 "Package " + packageName + " requires unavailable shared library "
9955 + libName + "; failing!");
9956 } else if (DEBUG_SHARED_LIBRARIES) {
9957 Slog.i(TAG, "Package " + packageName
9958 + " desires unavailable shared library "
9959 + libName + "; ignoring!");
9962 if (requiredVersions != null && requiredCertDigests != null) {
9963 if (libEntry.info.getVersion() != requiredVersions[i]) {
9964 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9965 "Package " + packageName + " requires unavailable static shared"
9966 + " library " + libName + " version "
9967 + libEntry.info.getVersion() + "; failing!");
9970 PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9971 if (libPkg == null) {
9972 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9973 "Package " + packageName + " requires unavailable static shared"
9974 + " library; failing!");
9977 String expectedCertDigest = requiredCertDigests[i];
9978 String libCertDigest = PackageUtils.computeCertSha256Digest(
9979 libPkg.mSignatures[0]);
9980 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9981 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9982 "Package " + packageName + " requires differently signed" +
9983 " static shared library; failing!");
9987 if (outUsedLibraries == null) {
9988 outUsedLibraries = new ArraySet<>();
9990 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9993 return outUsedLibraries;
9996 private static boolean hasString(List<String> list, List<String> which) {
10000 for (int i=list.size()-1; i>=0; i--) {
10001 for (int j=which.size()-1; j>=0; j--) {
10002 if (which.get(j).equals(list.get(i))) {
10010 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10011 PackageParser.Package changingPkg) {
10012 ArrayList<PackageParser.Package> res = null;
10013 for (PackageParser.Package pkg : mPackages.values()) {
10014 if (changingPkg != null
10015 && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10016 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10017 && !ArrayUtils.contains(pkg.usesStaticLibraries,
10018 changingPkg.staticSharedLibName)) {
10022 res = new ArrayList<>();
10026 updateSharedLibrariesLPr(pkg, changingPkg);
10027 } catch (PackageManagerException e) {
10028 // If a system app update or an app and a required lib missing we
10029 // delete the package and for updated system apps keep the data as
10030 // it is better for the user to reinstall than to be in an limbo
10031 // state. Also libs disappearing under an app should never happen
10033 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10034 final int flags = pkg.isUpdatedSystemApp()
10035 ? PackageManager.DELETE_KEEP_DATA : 0;
10036 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10037 flags , null, true, null);
10039 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10046 * Derive the value of the {@code cpuAbiOverride} based on the provided
10047 * value and an optional stored value from the package settings.
10049 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10050 String cpuAbiOverride = null;
10052 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10053 cpuAbiOverride = null;
10054 } else if (abiOverride != null) {
10055 cpuAbiOverride = abiOverride;
10056 } else if (settings != null) {
10057 cpuAbiOverride = settings.cpuAbiOverrideString;
10060 return cpuAbiOverride;
10063 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10064 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10065 throws PackageManagerException {
10066 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10067 // If the package has children and this is the first dive in the function
10068 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10069 // whether all packages (parent and children) would be successfully scanned
10070 // before the actual scan since scanning mutates internal state and we want
10071 // to atomically install the package and its children.
10072 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10073 if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10074 scanFlags |= SCAN_CHECK_ONLY;
10077 scanFlags &= ~SCAN_CHECK_ONLY;
10080 final PackageParser.Package scannedPkg;
10083 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10084 // Scan the children
10085 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10086 for (int i = 0; i < childCount; i++) {
10087 PackageParser.Package childPkg = pkg.childPackages.get(i);
10088 scanPackageLI(childPkg, policyFlags,
10089 scanFlags, currentTime, user);
10092 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10095 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10096 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10102 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10103 int scanFlags, long currentTime, @Nullable UserHandle user)
10104 throws PackageManagerException {
10105 boolean success = false;
10107 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10108 currentTime, user);
10112 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10113 // DELETE_DATA_ON_FAILURES is only used by frozen paths
10114 destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10115 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10116 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10122 * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10124 private static boolean apkHasCode(String fileName) {
10125 StrictJarFile jarFile = null;
10127 jarFile = new StrictJarFile(fileName,
10128 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10129 return jarFile.findEntry("classes.dex") != null;
10130 } catch (IOException ignore) {
10133 if (jarFile != null) {
10136 } catch (IOException ignore) {}
10142 * Enforces code policy for the package. This ensures that if an APK has
10143 * declared hasCode="true" in its manifest that the APK actually contains
10146 * @throws PackageManagerException If bytecode could not be found when it should exist
10148 private static void assertCodePolicy(PackageParser.Package pkg)
10149 throws PackageManagerException {
10150 final boolean shouldHaveCode =
10151 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10152 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10153 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10154 "Package " + pkg.baseCodePath + " code is missing");
10157 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10158 for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10159 final boolean splitShouldHaveCode =
10160 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10161 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10162 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10163 "Package " + pkg.splitCodePaths[i] + " code is missing");
10169 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10170 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10171 throws PackageManagerException {
10172 if (DEBUG_PACKAGE_SCANNING) {
10173 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10174 Log.d(TAG, "Scanning package " + pkg.packageName);
10177 applyPolicy(pkg, policyFlags);
10179 assertPackageIsValid(pkg, policyFlags, scanFlags);
10181 // Initialize package source and resource directories
10182 final File scanFile = new File(pkg.codePath);
10183 final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10184 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10186 SharedUserSetting suid = null;
10187 PackageSetting pkgSetting = null;
10189 // Getting the package setting may have a side-effect, so if we
10190 // are only checking if scan would succeed, stash a copy of the
10191 // old setting to restore at the end.
10192 PackageSetting nonMutatedPs = null;
10194 // We keep references to the derived CPU Abis from settings in oder to reuse
10195 // them in the case where we're not upgrading or booting for the first time.
10196 String primaryCpuAbiFromSettings = null;
10197 String secondaryCpuAbiFromSettings = null;
10200 synchronized (mPackages) {
10201 if (pkg.mSharedUserId != null) {
10202 // SIDE EFFECTS; may potentially allocate a new shared user
10203 suid = mSettings.getSharedUserLPw(
10204 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10205 if (DEBUG_PACKAGE_SCANNING) {
10206 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10207 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10208 + "): packages=" + suid.packages);
10212 // Check if we are renaming from an original package name.
10213 PackageSetting origPackage = null;
10214 String realName = null;
10215 if (pkg.mOriginalPackages != null) {
10216 // This package may need to be renamed to a previously
10217 // installed name. Let's check on that...
10218 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10219 if (pkg.mOriginalPackages.contains(renamed)) {
10220 // This package had originally been installed as the
10221 // original name, and we have already taken care of
10222 // transitioning to the new one. Just update the new
10223 // one to continue using the old name.
10224 realName = pkg.mRealPackage;
10225 if (!pkg.packageName.equals(renamed)) {
10226 // Callers into this function may have already taken
10227 // care of renaming the package; only do it here if
10228 // it is not already done.
10229 pkg.setPackageName(renamed);
10232 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10233 if ((origPackage = mSettings.getPackageLPr(
10234 pkg.mOriginalPackages.get(i))) != null) {
10235 // We do have the package already installed under its
10236 // original name... should we use it?
10237 if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10238 // New package is not compatible with original.
10239 origPackage = null;
10241 } else if (origPackage.sharedUser != null) {
10242 // Make sure uid is compatible between packages.
10243 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10244 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10245 + " to " + pkg.packageName + ": old uid "
10246 + origPackage.sharedUser.name
10247 + " differs from " + pkg.mSharedUserId);
10248 origPackage = null;
10251 // TODO: Add case when shared user id is added [b/28144775]
10253 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10254 + pkg.packageName + " to old name " + origPackage.name);
10262 if (mTransferedPackages.contains(pkg.packageName)) {
10263 Slog.w(TAG, "Package " + pkg.packageName
10264 + " was transferred to another, but its .apk remains");
10267 // See comments in nonMutatedPs declaration
10268 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10269 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10270 if (foundPs != null) {
10271 nonMutatedPs = new PackageSetting(foundPs);
10275 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10276 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10277 if (foundPs != null) {
10278 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10279 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10283 pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10284 if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10285 PackageManagerService.reportSettingsProblem(Log.WARN,
10286 "Package " + pkg.packageName + " shared user changed from "
10287 + (pkgSetting.sharedUser != null
10288 ? pkgSetting.sharedUser.name : "<nothing>")
10290 + (suid != null ? suid.name : "<nothing>")
10291 + "; replacing with new");
10294 final PackageSetting oldPkgSetting =
10295 pkgSetting == null ? null : new PackageSetting(pkgSetting);
10296 final PackageSetting disabledPkgSetting =
10297 mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10299 String[] usesStaticLibraries = null;
10300 if (pkg.usesStaticLibraries != null) {
10301 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10302 pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10305 if (pkgSetting == null) {
10306 final String parentPackageName = (pkg.parentPackage != null)
10307 ? pkg.parentPackage.packageName : null;
10308 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10309 // REMOVE SharedUserSetting from method; update in a separate call
10310 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10311 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10312 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10313 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10314 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10315 true /*allowInstall*/, instantApp, parentPackageName,
10316 pkg.getChildPackageNames(), UserManagerService.getInstance(),
10317 usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10318 // SIDE EFFECTS; updates system state; move elsewhere
10319 if (origPackage != null) {
10320 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10322 mSettings.addUserToSettingLPw(pkgSetting);
10324 // REMOVE SharedUserSetting from method; update in a separate call.
10326 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10327 // secondaryCpuAbi are not known at this point so we always update them
10328 // to null here, only to reset them at a later point.
10329 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10330 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10331 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10332 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10333 UserManagerService.getInstance(), usesStaticLibraries,
10334 pkg.usesStaticLibrariesVersions);
10336 // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10337 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10339 // SIDE EFFECTS; modifies system state; move elsewhere
10340 if (pkgSetting.origPackage != null) {
10341 // If we are first transitioning from an original package,
10342 // fix up the new package's name now. We need to do this after
10343 // looking up the package under its new name, so getPackageLP
10344 // can take care of fiddling things correctly.
10345 pkg.setPackageName(origPackage.name);
10347 // File a report about this.
10348 String msg = "New package " + pkgSetting.realName
10349 + " renamed to replace old package " + pkgSetting.name;
10350 reportSettingsProblem(Log.WARN, msg);
10352 // Make a note of it.
10353 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10354 mTransferedPackages.add(origPackage.name);
10357 // No longer need to retain this.
10358 pkgSetting.origPackage = null;
10361 // SIDE EFFECTS; modifies system state; move elsewhere
10362 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10363 // Make a note of it.
10364 mTransferedPackages.add(pkg.packageName);
10367 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10368 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10371 if ((scanFlags & SCAN_BOOTING) == 0
10372 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10373 // Check all shared libraries and map to their actual file path.
10374 // We only do this here for apps not on a system dir, because those
10375 // are the only ones that can fail an install due to this. We
10376 // will take care of the system apps by updating all of their
10377 // library paths after the scan is done. Also during the initial
10378 // scan don't update any libs as we do this wholesale after all
10379 // apps are scanned to avoid dependency based scanning.
10380 updateSharedLibrariesLPr(pkg, null);
10383 if (mFoundPolicyFile) {
10384 SELinuxMMAC.assignSeInfoValue(pkg);
10386 pkg.applicationInfo.uid = pkgSetting.appId;
10387 pkg.mExtras = pkgSetting;
10390 // Static shared libs have same package with different versions where
10391 // we internally use a synthetic package name to allow multiple versions
10392 // of the same package, therefore we need to compare signatures against
10393 // the package setting for the latest library version.
10394 PackageSetting signatureCheckPs = pkgSetting;
10395 if (pkg.applicationInfo.isStaticSharedLibrary()) {
10396 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10397 if (libraryEntry != null) {
10398 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10402 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10403 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10404 // We just determined the app is signed correctly, so bring
10405 // over the latest parsed certs.
10406 pkgSetting.signatures.mSignatures = pkg.mSignatures;
10408 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10409 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10410 "Package " + pkg.packageName + " upgrade keys do not match the "
10411 + "previously installed version");
10413 pkgSetting.signatures.mSignatures = pkg.mSignatures;
10414 String msg = "System package " + pkg.packageName
10415 + " signature changed; retaining data.";
10416 reportSettingsProblem(Log.WARN, msg);
10421 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10422 verifySignaturesLP(signatureCheckPs, pkg);
10423 // We just determined the app is signed correctly, so bring
10424 // over the latest parsed certs.
10425 pkgSetting.signatures.mSignatures = pkg.mSignatures;
10426 } catch (PackageManagerException e) {
10427 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10430 // The signature has changed, but this package is in the system
10431 // image... let's recover!
10432 pkgSetting.signatures.mSignatures = pkg.mSignatures;
10433 // However... if this package is part of a shared user, but it
10434 // doesn't match the signature of the shared user, let's fail.
10435 // What this means is that you can't change the signatures
10436 // associated with an overall shared user, which doesn't seem all
10437 // that unreasonable.
10438 if (signatureCheckPs.sharedUser != null) {
10439 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10440 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10441 throw new PackageManagerException(
10442 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10443 "Signature mismatch for shared user: "
10444 + pkgSetting.sharedUser);
10447 // File a report about this.
10448 String msg = "System package " + pkg.packageName
10449 + " signature changed; retaining data.";
10450 reportSettingsProblem(Log.WARN, msg);
10454 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10455 // This package wants to adopt ownership of permissions from
10456 // another package.
10457 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10458 final String origName = pkg.mAdoptPermissions.get(i);
10459 final PackageSetting orig = mSettings.getPackageLPr(origName);
10460 if (orig != null) {
10461 if (verifyPackageUpdateLPr(orig, pkg)) {
10462 Slog.i(TAG, "Adopting permissions from " + origName + " to "
10463 + pkg.packageName);
10464 // SIDE EFFECTS; updates permissions system state; move elsewhere
10465 mSettings.transferPermissionsLPw(origName, pkg.packageName);
10472 pkg.applicationInfo.processName = fixProcessName(
10473 pkg.applicationInfo.packageName,
10474 pkg.applicationInfo.processName);
10476 if (pkg != mPlatformPackage) {
10477 // Get all of our default paths setup
10478 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10481 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10483 if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10484 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10485 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10486 final boolean extractNativeLibs = !pkg.isLibrary();
10487 derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10488 mAppLib32InstallDir);
10489 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10491 // Some system apps still use directory structure for native libraries
10492 // in which case we might end up not detecting abi solely based on apk
10493 // structure. Try to detect abi based on directory structure.
10494 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10495 pkg.applicationInfo.primaryCpuAbi == null) {
10496 setBundledAppAbisAndRoots(pkg, pkgSetting);
10497 setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10500 // This is not a first boot or an upgrade, don't bother deriving the
10501 // ABI during the scan. Instead, trust the value that was stored in the
10502 // package setting.
10503 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10504 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10506 setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10508 if (DEBUG_ABI_SELECTION) {
10509 Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10510 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10511 pkg.applicationInfo.secondaryCpuAbi);
10515 if ((scanFlags & SCAN_MOVE) != 0) {
10516 // We haven't run dex-opt for this move (since we've moved the compiled output too)
10517 // but we already have this packages package info in the PackageSetting. We just
10518 // use that and derive the native library path based on the new codepath.
10519 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10520 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10523 // Set native library paths again. For moves, the path will be updated based on the
10524 // ABIs we've determined above. For non-moves, the path will be updated based on the
10525 // ABIs we determined during compilation, but the path will depend on the final
10526 // package path (after the rename away from the stage path).
10527 setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10530 // This is a special case for the "system" package, where the ABI is
10531 // dictated by the zygote configuration (and init.rc). We should keep track
10532 // of this ABI so that we can deal with "normal" applications that run under
10533 // the same UID correctly.
10534 if (mPlatformPackage == pkg) {
10535 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10536 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10539 // If there's a mismatch between the abi-override in the package setting
10540 // and the abiOverride specified for the install. Warn about this because we
10541 // would've already compiled the app without taking the package setting into
10543 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10544 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10545 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10546 " for package " + pkg.packageName);
10550 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10551 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10552 pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10554 // Copy the derived override back to the parsed package, so that we can
10555 // update the package settings accordingly.
10556 pkg.cpuAbiOverride = cpuAbiOverride;
10558 if (DEBUG_ABI_SELECTION) {
10559 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10560 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10561 + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10564 // Push the derived path down into PackageSettings so we know what to
10565 // clean up at uninstall time.
10566 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10568 if (DEBUG_ABI_SELECTION) {
10569 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10570 " primary=" + pkg.applicationInfo.primaryCpuAbi +
10571 " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10574 // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10575 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10576 // We don't do this here during boot because we can do it all
10577 // at once after scanning all existing packages.
10579 // We also do this *before* we perform dexopt on this package, so that
10580 // we can avoid redundant dexopts, and also to make sure we've got the
10581 // code and package path correct.
10582 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10585 if (mFactoryTest && pkg.requestedPermissions.contains(
10586 android.Manifest.permission.FACTORY_TEST)) {
10587 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10590 if (isSystemApp(pkg)) {
10591 pkgSetting.isOrphaned = true;
10594 // Take care of first install / last update times.
10595 final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10596 if (currentTime != 0) {
10597 if (pkgSetting.firstInstallTime == 0) {
10598 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10599 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10600 pkgSetting.lastUpdateTime = currentTime;
10602 } else if (pkgSetting.firstInstallTime == 0) {
10603 // We need *something*. Take time time stamp of the file.
10604 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10605 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10606 if (scanFileTime != pkgSetting.timeStamp) {
10607 // A package on the system image has changed; consider this
10608 // to be an update.
10609 pkgSetting.lastUpdateTime = scanFileTime;
10612 pkgSetting.setTimeStamp(scanFileTime);
10614 if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10615 if (nonMutatedPs != null) {
10616 synchronized (mPackages) {
10617 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10621 final int userId = user == null ? 0 : user.getIdentifier();
10622 // Modify state for the given package setting
10623 commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10624 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10625 if (pkgSetting.getInstantApp(userId)) {
10626 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10633 * Applies policy to the parsed package based upon the given policy flags.
10634 * Ensures the package is in a good state.
10636 * Implementation detail: This method must NOT have any side effect. It would
10637 * ideally be static, but, it requires locks to read system state.
10639 private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10640 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10641 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10642 if (pkg.applicationInfo.isDirectBootAware()) {
10643 // we're direct boot aware; set for all components
10644 for (PackageParser.Service s : pkg.services) {
10645 s.info.encryptionAware = s.info.directBootAware = true;
10647 for (PackageParser.Provider p : pkg.providers) {
10648 p.info.encryptionAware = p.info.directBootAware = true;
10650 for (PackageParser.Activity a : pkg.activities) {
10651 a.info.encryptionAware = a.info.directBootAware = true;
10653 for (PackageParser.Activity r : pkg.receivers) {
10654 r.info.encryptionAware = r.info.directBootAware = true;
10658 // Only allow system apps to be flagged as core apps.
10659 pkg.coreApp = false;
10660 // clear flags not applicable to regular apps
10661 pkg.applicationInfo.privateFlags &=
10662 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10663 pkg.applicationInfo.privateFlags &=
10664 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10666 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10668 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10669 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10672 if (!isSystemApp(pkg)) {
10673 // Only system apps can use these features.
10674 pkg.mOriginalPackages = null;
10675 pkg.mRealPackage = null;
10676 pkg.mAdoptPermissions = null;
10681 * Asserts the parsed package is valid according to the given policy. If the
10682 * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10684 * Implementation detail: This method must NOT have any side effects. It would
10685 * ideally be static, but, it requires locks to read system state.
10687 * @throws PackageManagerException If the package fails any of the validation checks
10689 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10690 throws PackageManagerException {
10691 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10692 assertCodePolicy(pkg);
10695 if (pkg.applicationInfo.getCodePath() == null ||
10696 pkg.applicationInfo.getResourcePath() == null) {
10697 // Bail out. The resource and code paths haven't been set.
10698 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10699 "Code and resource paths haven't been set correctly");
10702 // Make sure we're not adding any bogus keyset info
10703 KeySetManagerService ksms = mSettings.mKeySetManagerService;
10704 ksms.assertScannedPackageValid(pkg);
10706 synchronized (mPackages) {
10707 // The special "android" package can only be defined once
10708 if (pkg.packageName.equals("android")) {
10709 if (mAndroidApplication != null) {
10710 Slog.w(TAG, "*************************************************");
10711 Slog.w(TAG, "Core android package being redefined. Skipping.");
10712 Slog.w(TAG, " codePath=" + pkg.codePath);
10713 Slog.w(TAG, "*************************************************");
10714 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10715 "Core android package being redefined. Skipping.");
10719 // A package name must be unique; don't allow duplicates
10720 if (mPackages.containsKey(pkg.packageName)) {
10721 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10722 "Application package " + pkg.packageName
10723 + " already installed. Skipping duplicate.");
10726 if (pkg.applicationInfo.isStaticSharedLibrary()) {
10727 // Static libs have a synthetic package name containing the version
10728 // but we still want the base name to be unique.
10729 if (mPackages.containsKey(pkg.manifestPackageName)) {
10730 throw new PackageManagerException(
10731 "Duplicate static shared lib provider package");
10734 // Static shared libraries should have at least O target SDK
10735 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10736 throw new PackageManagerException(
10737 "Packages declaring static-shared libs must target O SDK or higher");
10740 // Package declaring static a shared lib cannot be instant apps
10741 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10742 throw new PackageManagerException(
10743 "Packages declaring static-shared libs cannot be instant apps");
10746 // Package declaring static a shared lib cannot be renamed since the package
10747 // name is synthetic and apps can't code around package manager internals.
10748 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10749 throw new PackageManagerException(
10750 "Packages declaring static-shared libs cannot be renamed");
10753 // Package declaring static a shared lib cannot declare child packages
10754 if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10755 throw new PackageManagerException(
10756 "Packages declaring static-shared libs cannot have child packages");
10759 // Package declaring static a shared lib cannot declare dynamic libs
10760 if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10761 throw new PackageManagerException(
10762 "Packages declaring static-shared libs cannot declare dynamic libs");
10765 // Package declaring static a shared lib cannot declare shared users
10766 if (pkg.mSharedUserId != null) {
10767 throw new PackageManagerException(
10768 "Packages declaring static-shared libs cannot declare shared users");
10771 // Static shared libs cannot declare activities
10772 if (!pkg.activities.isEmpty()) {
10773 throw new PackageManagerException(
10774 "Static shared libs cannot declare activities");
10777 // Static shared libs cannot declare services
10778 if (!pkg.services.isEmpty()) {
10779 throw new PackageManagerException(
10780 "Static shared libs cannot declare services");
10783 // Static shared libs cannot declare providers
10784 if (!pkg.providers.isEmpty()) {
10785 throw new PackageManagerException(
10786 "Static shared libs cannot declare content providers");
10789 // Static shared libs cannot declare receivers
10790 if (!pkg.receivers.isEmpty()) {
10791 throw new PackageManagerException(
10792 "Static shared libs cannot declare broadcast receivers");
10795 // Static shared libs cannot declare permission groups
10796 if (!pkg.permissionGroups.isEmpty()) {
10797 throw new PackageManagerException(
10798 "Static shared libs cannot declare permission groups");
10801 // Static shared libs cannot declare permissions
10802 if (!pkg.permissions.isEmpty()) {
10803 throw new PackageManagerException(
10804 "Static shared libs cannot declare permissions");
10807 // Static shared libs cannot declare protected broadcasts
10808 if (pkg.protectedBroadcasts != null) {
10809 throw new PackageManagerException(
10810 "Static shared libs cannot declare protected broadcasts");
10813 // Static shared libs cannot be overlay targets
10814 if (pkg.mOverlayTarget != null) {
10815 throw new PackageManagerException(
10816 "Static shared libs cannot be overlay targets");
10819 // The version codes must be ordered as lib versions
10820 int minVersionCode = Integer.MIN_VALUE;
10821 int maxVersionCode = Integer.MAX_VALUE;
10823 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10824 pkg.staticSharedLibName);
10825 if (versionedLib != null) {
10826 final int versionCount = versionedLib.size();
10827 for (int i = 0; i < versionCount; i++) {
10828 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10829 final int libVersionCode = libInfo.getDeclaringPackage()
10831 if (libInfo.getVersion() < pkg.staticSharedLibVersion) {
10832 minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10833 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) {
10834 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10836 minVersionCode = maxVersionCode = libVersionCode;
10841 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10842 throw new PackageManagerException("Static shared"
10843 + " lib version codes must be ordered as lib versions");
10847 // Only privileged apps and updated privileged apps can add child packages.
10848 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10849 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10850 throw new PackageManagerException("Only privileged apps can add child "
10851 + "packages. Ignoring package " + pkg.packageName);
10853 final int childCount = pkg.childPackages.size();
10854 for (int i = 0; i < childCount; i++) {
10855 PackageParser.Package childPkg = pkg.childPackages.get(i);
10856 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10857 childPkg.packageName)) {
10858 throw new PackageManagerException("Can't override child of "
10859 + "another disabled app. Ignoring package " + pkg.packageName);
10864 // If we're only installing presumed-existing packages, require that the
10865 // scanned APK is both already known and at the path previously established
10866 // for it. Previously unknown packages we pick up normally, but if we have an
10867 // a priori expectation about this package's install presence, enforce it.
10868 // With a singular exception for new system packages. When an OTA contains
10869 // a new system package, we allow the codepath to change from a system location
10870 // to the user-installed location. If we don't allow this change, any newer,
10871 // user-installed version of the application will be ignored.
10872 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10873 if (mExpectingBetter.containsKey(pkg.packageName)) {
10874 logCriticalInfo(Log.WARN,
10875 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10877 PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10878 if (known != null) {
10879 if (DEBUG_PACKAGE_SCANNING) {
10880 Log.d(TAG, "Examining " + pkg.codePath
10881 + " and requiring known paths " + known.codePathString
10882 + " & " + known.resourcePathString);
10884 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10885 || !pkg.applicationInfo.getResourcePath().equals(
10886 known.resourcePathString)) {
10887 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10888 "Application package " + pkg.packageName
10889 + " found at " + pkg.applicationInfo.getCodePath()
10890 + " but expected at " + known.codePathString
10897 // Verify that this new package doesn't have any content providers
10898 // that conflict with existing packages. Only do this if the
10899 // package isn't already installed, since we don't want to break
10900 // things that are installed.
10901 if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10902 final int N = pkg.providers.size();
10904 for (i=0; i<N; i++) {
10905 PackageParser.Provider p = pkg.providers.get(i);
10906 if (p.info.authority != null) {
10907 String names[] = p.info.authority.split(";");
10908 for (int j = 0; j < names.length; j++) {
10909 if (mProvidersByAuthority.containsKey(names[j])) {
10910 PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10911 final String otherPackageName =
10912 ((other != null && other.getComponentName() != null) ?
10913 other.getComponentName().getPackageName() : "?");
10914 throw new PackageManagerException(
10915 INSTALL_FAILED_CONFLICTING_PROVIDER,
10916 "Can't install because provider name " + names[j]
10917 + " (in package " + pkg.applicationInfo.packageName
10918 + ") is already used by " + otherPackageName);
10927 private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10928 int type, String declaringPackageName, int declaringVersionCode) {
10929 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10930 if (versionedLib == null) {
10931 versionedLib = new SparseArray<>();
10932 mSharedLibraries.put(name, versionedLib);
10933 if (type == SharedLibraryInfo.TYPE_STATIC) {
10934 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10936 } else if (versionedLib.indexOfKey(version) >= 0) {
10939 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10940 version, type, declaringPackageName, declaringVersionCode);
10941 versionedLib.put(version, libEntry);
10945 private boolean removeSharedLibraryLPw(String name, int version) {
10946 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10947 if (versionedLib == null) {
10950 final int libIdx = versionedLib.indexOfKey(version);
10954 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10955 versionedLib.remove(version);
10956 if (versionedLib.size() <= 0) {
10957 mSharedLibraries.remove(name);
10958 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10959 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10960 .getPackageName());
10967 * Adds a scanned package to the system. When this method is finished, the package will
10968 * be available for query, resolution, etc...
10970 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10971 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10972 final String pkgName = pkg.packageName;
10973 if (mCustomResolverComponentName != null &&
10974 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10975 setUpCustomResolverActivity(pkg);
10978 if (pkg.packageName.equals("android")) {
10979 synchronized (mPackages) {
10980 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10981 // Set up information for our fall-back user intent resolution activity.
10982 mPlatformPackage = pkg;
10983 pkg.mVersionCode = mSdkVersion;
10984 mAndroidApplication = pkg.applicationInfo;
10985 if (!mResolverReplaced) {
10986 mResolveActivity.applicationInfo = mAndroidApplication;
10987 mResolveActivity.name = ResolverActivity.class.getName();
10988 mResolveActivity.packageName = mAndroidApplication.packageName;
10989 mResolveActivity.processName = "system:ui";
10990 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10991 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10992 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10993 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10994 mResolveActivity.exported = true;
10995 mResolveActivity.enabled = true;
10996 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10997 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10998 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10999 | ActivityInfo.CONFIG_SCREEN_LAYOUT
11000 | ActivityInfo.CONFIG_ORIENTATION
11001 | ActivityInfo.CONFIG_KEYBOARD
11002 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11003 mResolveInfo.activityInfo = mResolveActivity;
11004 mResolveInfo.priority = 0;
11005 mResolveInfo.preferredOrder = 0;
11006 mResolveInfo.match = 0;
11007 mResolveComponentName = new ComponentName(
11008 mAndroidApplication.packageName, mResolveActivity.name);
11014 ArrayList<PackageParser.Package> clientLibPkgs = null;
11016 synchronized (mPackages) {
11017 boolean hasStaticSharedLibs = false;
11019 // Any app can add new static shared libraries
11020 if (pkg.staticSharedLibName != null) {
11021 // Static shared libs don't allow renaming as they have synthetic package
11022 // names to allow install of multiple versions, so use name from manifest.
11023 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11024 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11025 pkg.manifestPackageName, pkg.mVersionCode)) {
11026 hasStaticSharedLibs = true;
11028 Slog.w(TAG, "Package " + pkg.packageName + " library "
11029 + pkg.staticSharedLibName + " already exists; skipping");
11031 // Static shared libs cannot be updated once installed since they
11032 // use synthetic package name which includes the version code, so
11033 // not need to update other packages's shared lib dependencies.
11036 if (!hasStaticSharedLibs
11037 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11038 // Only system apps can add new dynamic shared libraries.
11039 if (pkg.libraryNames != null) {
11040 for (int i = 0; i < pkg.libraryNames.size(); i++) {
11041 String name = pkg.libraryNames.get(i);
11042 boolean allowed = false;
11043 if (pkg.isUpdatedSystemApp()) {
11044 // New library entries can only be added through the
11045 // system image. This is important to get rid of a lot
11046 // of nasty edge cases: for example if we allowed a non-
11047 // system update of the app to add a library, then uninstalling
11048 // the update would make the library go away, and assumptions
11049 // we made such as through app install filtering would now
11050 // have allowed apps on the device which aren't compatible
11051 // with it. Better to just have the restriction here, be
11052 // conservative, and create many fewer cases that can negatively
11053 // impact the user experience.
11054 final PackageSetting sysPs = mSettings
11055 .getDisabledSystemPkgLPr(pkg.packageName);
11056 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11057 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11058 if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11068 if (!addSharedLibraryLPw(null, pkg.packageName, name,
11069 SharedLibraryInfo.VERSION_UNDEFINED,
11070 SharedLibraryInfo.TYPE_DYNAMIC,
11071 pkg.packageName, pkg.mVersionCode)) {
11072 Slog.w(TAG, "Package " + pkg.packageName + " library "
11073 + name + " already exists; skipping");
11076 Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11077 + name + " that is not declared on system image; skipping");
11081 if ((scanFlags & SCAN_BOOTING) == 0) {
11082 // If we are not booting, we need to update any applications
11083 // that are clients of our shared library. If we are booting,
11084 // this will all be done once the scan is complete.
11085 clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11091 if ((scanFlags & SCAN_BOOTING) != 0) {
11092 // No apps can run during boot scan, so they don't need to be frozen
11093 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11094 // Caller asked to not kill app, so it's probably not frozen
11095 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11096 // Caller asked us to ignore frozen check for some reason; they
11097 // probably didn't know the package name
11099 // We're doing major surgery on this package, so it better be frozen
11100 // right now to keep it from launching
11101 checkPackageFrozen(pkgName);
11104 // Also need to kill any apps that are dependent on the library.
11105 if (clientLibPkgs != null) {
11106 for (int i=0; i<clientLibPkgs.size(); i++) {
11107 PackageParser.Package clientPkg = clientLibPkgs.get(i);
11108 killApplication(clientPkg.applicationInfo.packageName,
11109 clientPkg.applicationInfo.uid, "update lib");
11114 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11116 synchronized (mPackages) {
11117 // We don't expect installation to fail beyond this point
11119 // Add the new setting to mSettings
11120 mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11121 // Add the new setting to mPackages
11122 mPackages.put(pkg.applicationInfo.packageName, pkg);
11123 // Make sure we don't accidentally delete its data.
11124 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11125 while (iter.hasNext()) {
11126 PackageCleanItem item = iter.next();
11127 if (pkgName.equals(item.packageName)) {
11132 // Add the package's KeySets to the global KeySetManagerService
11133 KeySetManagerService ksms = mSettings.mKeySetManagerService;
11134 ksms.addScannedPackageLPw(pkg);
11136 int N = pkg.providers.size();
11137 StringBuilder r = null;
11139 for (i=0; i<N; i++) {
11140 PackageParser.Provider p = pkg.providers.get(i);
11141 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11142 p.info.processName);
11143 mProviders.addProvider(p);
11144 p.syncable = p.info.isSyncable;
11145 if (p.info.authority != null) {
11146 String names[] = p.info.authority.split(";");
11147 p.info.authority = null;
11148 for (int j = 0; j < names.length; j++) {
11149 if (j == 1 && p.syncable) {
11150 // We only want the first authority for a provider to possibly be
11151 // syncable, so if we already added this provider using a different
11152 // authority clear the syncable flag. We copy the provider before
11153 // changing it because the mProviders object contains a reference
11154 // to a provider that we don't want to change.
11155 // Only do this for the second authority since the resulting provider
11156 // object can be the same for all future authorities for this provider.
11157 p = new PackageParser.Provider(p);
11158 p.syncable = false;
11160 if (!mProvidersByAuthority.containsKey(names[j])) {
11161 mProvidersByAuthority.put(names[j], p);
11162 if (p.info.authority == null) {
11163 p.info.authority = names[j];
11165 p.info.authority = p.info.authority + ";" + names[j];
11167 if (DEBUG_PACKAGE_SCANNING) {
11169 Log.d(TAG, "Registered content provider: " + names[j]
11170 + ", className = " + p.info.name + ", isSyncable = "
11171 + p.info.isSyncable);
11174 PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11175 Slog.w(TAG, "Skipping provider name " + names[j] +
11176 " (in package " + pkg.applicationInfo.packageName +
11177 "): name already used by "
11178 + ((other != null && other.getComponentName() != null)
11179 ? other.getComponentName().getPackageName() : "?"));
11185 r = new StringBuilder(256);
11189 r.append(p.info.name);
11193 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r);
11196 N = pkg.services.size();
11198 for (i=0; i<N; i++) {
11199 PackageParser.Service s = pkg.services.get(i);
11200 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11201 s.info.processName);
11202 mServices.addService(s);
11205 r = new StringBuilder(256);
11209 r.append(s.info.name);
11213 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r);
11216 N = pkg.receivers.size();
11218 for (i=0; i<N; i++) {
11219 PackageParser.Activity a = pkg.receivers.get(i);
11220 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11221 a.info.processName);
11222 mReceivers.addActivity(a, "receiver");
11225 r = new StringBuilder(256);
11229 r.append(a.info.name);
11233 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r);
11236 N = pkg.activities.size();
11238 for (i=0; i<N; i++) {
11239 PackageParser.Activity a = pkg.activities.get(i);
11240 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11241 a.info.processName);
11242 mActivities.addActivity(a, "activity");
11245 r = new StringBuilder(256);
11249 r.append(a.info.name);
11253 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r);
11256 N = pkg.permissionGroups.size();
11258 for (i=0; i<N; i++) {
11259 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11260 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11261 final String curPackageName = cur == null ? null : cur.info.packageName;
11262 // Dont allow ephemeral apps to define new permission groups.
11263 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11264 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11265 + pg.info.packageName
11266 + " ignored: instant apps cannot define new permission groups.");
11269 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11270 if (cur == null || isPackageUpdate) {
11271 mPermissionGroups.put(pg.info.name, pg);
11274 r = new StringBuilder(256);
11278 if (isPackageUpdate) {
11281 r.append(pg.info.name);
11284 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11285 + pg.info.packageName + " ignored: original from "
11286 + cur.info.packageName);
11289 r = new StringBuilder(256);
11294 r.append(pg.info.name);
11299 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r);
11302 N = pkg.permissions.size();
11304 for (i=0; i<N; i++) {
11305 PackageParser.Permission p = pkg.permissions.get(i);
11307 // Dont allow ephemeral apps to define new permissions.
11308 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11309 Slog.w(TAG, "Permission " + p.info.name + " from package "
11310 + p.info.packageName
11311 + " ignored: instant apps cannot define new permissions.");
11315 // Assume by default that we did not install this permission into the system.
11316 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11318 // Now that permission groups have a special meaning, we ignore permission
11319 // groups for legacy apps to prevent unexpected behavior. In particular,
11320 // permissions for one app being granted to someone just because they happen
11321 // to be in a group defined by another app (before this had no implications).
11322 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11323 p.group = mPermissionGroups.get(p.info.group);
11324 // Warn for a permission in an unknown group.
11325 if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11326 Slog.i(TAG, "Permission " + p.info.name + " from package "
11327 + p.info.packageName + " in an unknown group " + p.info.group);
11331 ArrayMap<String, BasePermission> permissionMap =
11332 p.tree ? mSettings.mPermissionTrees
11333 : mSettings.mPermissions;
11334 BasePermission bp = permissionMap.get(p.info.name);
11336 // Allow system apps to redefine non-system permissions
11337 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11338 final boolean currentOwnerIsSystem = (bp.perm != null
11339 && isSystemApp(bp.perm.owner));
11340 if (isSystemApp(p.owner)) {
11341 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11342 // It's a built-in permission and no owner, take ownership now
11343 bp.packageSetting = pkgSetting;
11345 bp.uid = pkg.applicationInfo.uid;
11346 bp.sourcePackage = p.info.packageName;
11347 p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11348 } else if (!currentOwnerIsSystem) {
11349 String msg = "New decl " + p.owner + " of permission "
11350 + p.info.name + " is system; overriding " + bp.sourcePackage;
11351 reportSettingsProblem(Log.WARN, msg);
11358 bp = new BasePermission(p.info.name, p.info.packageName,
11359 BasePermission.TYPE_NORMAL);
11360 permissionMap.put(p.info.name, bp);
11363 if (bp.perm == null) {
11364 if (bp.sourcePackage == null
11365 || bp.sourcePackage.equals(p.info.packageName)) {
11366 BasePermission tree = findPermissionTreeLP(p.info.name);
11368 || tree.sourcePackage.equals(p.info.packageName)) {
11369 bp.packageSetting = pkgSetting;
11371 bp.uid = pkg.applicationInfo.uid;
11372 bp.sourcePackage = p.info.packageName;
11373 p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11376 r = new StringBuilder(256);
11380 r.append(p.info.name);
11383 Slog.w(TAG, "Permission " + p.info.name + " from package "
11384 + p.info.packageName + " ignored: base tree "
11385 + tree.name + " is from package "
11386 + tree.sourcePackage);
11389 Slog.w(TAG, "Permission " + p.info.name + " from package "
11390 + p.info.packageName + " ignored: original from "
11391 + bp.sourcePackage);
11393 } else if (chatty) {
11395 r = new StringBuilder(256);
11400 r.append(p.info.name);
11402 if (bp.perm == p) {
11403 bp.protectionLevel = p.info.protectionLevel;
11408 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r);
11411 N = pkg.instrumentation.size();
11413 for (i=0; i<N; i++) {
11414 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11415 a.info.packageName = pkg.applicationInfo.packageName;
11416 a.info.sourceDir = pkg.applicationInfo.sourceDir;
11417 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11418 a.info.splitNames = pkg.splitNames;
11419 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11420 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11421 a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11422 a.info.dataDir = pkg.applicationInfo.dataDir;
11423 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11424 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11425 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11426 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11427 mInstrumentation.put(a.getComponentName(), a);
11430 r = new StringBuilder(256);
11434 r.append(a.info.name);
11438 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r);
11441 if (pkg.protectedBroadcasts != null) {
11442 N = pkg.protectedBroadcasts.size();
11443 for (i=0; i<N; i++) {
11444 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11449 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11453 * Derive the ABI of a non-system package located at {@code scanFile}. This information
11454 * is derived purely on the basis of the contents of {@code scanFile} and
11455 * {@code cpuAbiOverride}.
11457 * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11459 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11460 String cpuAbiOverride, boolean extractLibs,
11461 File appLib32InstallDir)
11462 throws PackageManagerException {
11463 // Give ourselves some initial paths; we'll come back for another
11464 // pass once we've determined ABI below.
11465 setNativeLibraryPaths(pkg, appLib32InstallDir);
11467 // We would never need to extract libs for forward-locked and external packages,
11468 // since the container service will do it for us. We shouldn't attempt to
11469 // extract libs from system app when it was not updated.
11470 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11471 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11472 extractLibs = false;
11475 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11476 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11478 NativeLibraryHelper.Handle handle = null;
11480 handle = NativeLibraryHelper.Handle.create(pkg);
11481 // TODO(multiArch): This can be null for apps that didn't go through the
11482 // usual installation process. We can calculate it again, like we
11483 // do during install time.
11485 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11487 final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11489 // Null out the abis so that they can be recalculated.
11490 pkg.applicationInfo.primaryCpuAbi = null;
11491 pkg.applicationInfo.secondaryCpuAbi = null;
11492 if (isMultiArch(pkg.applicationInfo)) {
11493 // Warn if we've set an abiOverride for multi-lib packages..
11494 // By definition, we need to copy both 32 and 64 bit libraries for
11496 if (pkg.cpuAbiOverride != null
11497 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11498 Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11501 int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11502 int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11503 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11505 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11506 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11507 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11508 useIsaSpecificSubdirs);
11510 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11511 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11513 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11516 // Shared library native code should be in the APK zip aligned
11517 if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11518 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11519 "Shared library native lib extraction not supported");
11522 maybeThrowExceptionForMultiArchCopy(
11523 "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11525 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11527 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11528 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11529 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11530 useIsaSpecificSubdirs);
11532 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11533 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11535 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11538 maybeThrowExceptionForMultiArchCopy(
11539 "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11542 // Shared library native libs should be in the APK zip aligned
11543 if (extractLibs && pkg.isLibrary()) {
11544 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11545 "Shared library native lib extraction not supported");
11547 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11551 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11553 if (pkg.use32bitAbi) {
11554 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11555 pkg.applicationInfo.primaryCpuAbi = abi;
11557 pkg.applicationInfo.secondaryCpuAbi = abi;
11560 pkg.applicationInfo.primaryCpuAbi = abi;
11564 String[] abiList = (cpuAbiOverride != null) ?
11565 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11567 // Enable gross and lame hacks for apps that are built with old
11568 // SDK tools. We must scan their APKs for renderscript bitcode and
11569 // not launch them if it's present. Don't bother checking on devices
11570 // that don't have 64 bit support.
11571 boolean needsRenderScriptOverride = false;
11572 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11573 NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11574 abiList = Build.SUPPORTED_32_BIT_ABIS;
11575 needsRenderScriptOverride = true;
11580 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11581 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11582 nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11584 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11585 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11587 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11589 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11590 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11591 "Error unpackaging native libs for app, errorCode=" + copyRet);
11594 if (copyRet >= 0) {
11595 // Shared libraries that have native libs must be multi-architecture
11596 if (pkg.isLibrary()) {
11597 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11598 "Shared library with native libs must be multiarch");
11600 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11601 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11602 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11603 } else if (needsRenderScriptOverride) {
11604 pkg.applicationInfo.primaryCpuAbi = abiList[0];
11607 } catch (IOException ioe) {
11608 Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11610 IoUtils.closeQuietly(handle);
11613 // Now that we've calculated the ABIs and determined if it's an internal app,
11614 // we will go ahead and populate the nativeLibraryPath.
11615 setNativeLibraryPaths(pkg, appLib32InstallDir);
11619 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11620 * i.e, so that all packages can be run inside a single process if required.
11622 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11623 * this function will either try and make the ABI for all packages in {@code packagesForUser}
11624 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11625 * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11626 * updating a package that belongs to a shared user.
11628 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11629 * adds unnecessary complexity.
11631 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11632 PackageParser.Package scannedPackage) {
11633 String requiredInstructionSet = null;
11634 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11635 requiredInstructionSet = VMRuntime.getInstructionSet(
11636 scannedPackage.applicationInfo.primaryCpuAbi);
11639 PackageSetting requirer = null;
11640 for (PackageSetting ps : packagesForUser) {
11641 // If packagesForUser contains scannedPackage, we skip it. This will happen
11642 // when scannedPackage is an update of an existing package. Without this check,
11643 // we will never be able to change the ABI of any package belonging to a shared
11644 // user, even if it's compatible with other packages.
11645 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11646 if (ps.primaryCpuAbiString == null) {
11650 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11651 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11652 // We have a mismatch between instruction sets (say arm vs arm64) warn about
11653 // this but there's not much we can do.
11654 String errorMessage = "Instruction set mismatch, "
11655 + ((requirer == null) ? "[caller]" : requirer)
11656 + " requires " + requiredInstructionSet + " whereas " + ps
11657 + " requires " + instructionSet;
11658 Slog.w(TAG, errorMessage);
11661 if (requiredInstructionSet == null) {
11662 requiredInstructionSet = instructionSet;
11668 if (requiredInstructionSet != null) {
11669 String adjustedAbi;
11670 if (requirer != null) {
11671 // requirer != null implies that either scannedPackage was null or that scannedPackage
11672 // did not require an ABI, in which case we have to adjust scannedPackage to match
11673 // the ABI of the set (which is the same as requirer's ABI)
11674 adjustedAbi = requirer.primaryCpuAbiString;
11675 if (scannedPackage != null) {
11676 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11679 // requirer == null implies that we're updating all ABIs in the set to
11680 // match scannedPackage.
11681 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi;
11684 for (PackageSetting ps : packagesForUser) {
11685 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11686 if (ps.primaryCpuAbiString != null) {
11690 ps.primaryCpuAbiString = adjustedAbi;
11691 if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11692 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11693 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11694 if (DEBUG_ABI_SELECTION) {
11695 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11697 + (requirer != null ? requirer.pkg : "null")
11698 + ", scannedPackage="
11699 + (scannedPackage != null ? scannedPackage : "null")
11703 mInstaller.rmdex(ps.codePathString,
11704 getDexCodeInstructionSet(getPreferredInstructionSet()));
11705 } catch (InstallerException ignored) {
11713 private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11714 synchronized (mPackages) {
11715 mResolverReplaced = true;
11716 // Set up information for custom user intent resolution activity.
11717 mResolveActivity.applicationInfo = pkg.applicationInfo;
11718 mResolveActivity.name = mCustomResolverComponentName.getClassName();
11719 mResolveActivity.packageName = pkg.applicationInfo.packageName;
11720 mResolveActivity.processName = pkg.applicationInfo.packageName;
11721 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11722 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11723 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11724 mResolveActivity.theme = 0;
11725 mResolveActivity.exported = true;
11726 mResolveActivity.enabled = true;
11727 mResolveInfo.activityInfo = mResolveActivity;
11728 mResolveInfo.priority = 0;
11729 mResolveInfo.preferredOrder = 0;
11730 mResolveInfo.match = 0;
11731 mResolveComponentName = mCustomResolverComponentName;
11732 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11733 mResolveComponentName);
11737 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11738 if (installerActivity == null) {
11739 if (DEBUG_EPHEMERAL) {
11740 Slog.d(TAG, "Clear ephemeral installer activity");
11742 mInstantAppInstallerActivity = null;
11746 if (DEBUG_EPHEMERAL) {
11747 Slog.d(TAG, "Set ephemeral installer activity: "
11748 + installerActivity.getComponentName());
11750 // Set up information for ephemeral installer activity
11751 mInstantAppInstallerActivity = installerActivity;
11752 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11753 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11754 mInstantAppInstallerActivity.exported = true;
11755 mInstantAppInstallerActivity.enabled = true;
11756 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11757 mInstantAppInstallerInfo.priority = 0;
11758 mInstantAppInstallerInfo.preferredOrder = 1;
11759 mInstantAppInstallerInfo.isDefault = true;
11760 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11761 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11764 private static String calculateBundledApkRoot(final String codePathString) {
11765 final File codePath = new File(codePathString);
11766 final File codeRoot;
11767 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11768 codeRoot = Environment.getRootDirectory();
11769 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11770 codeRoot = Environment.getOemDirectory();
11771 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11772 codeRoot = Environment.getVendorDirectory();
11774 // Unrecognized code path; take its top real segment as the apk root:
11775 // e.g. /something/app/blah.apk => /something
11777 File f = codePath.getCanonicalFile();
11778 File parent = f.getParentFile(); // non-null because codePath is a file
11780 while ((tmp = parent.getParentFile()) != null) {
11785 Slog.w(TAG, "Unrecognized code path "
11786 + codePath + " - using " + codeRoot);
11787 } catch (IOException e) {
11788 // Can't canonicalize the code path -- shenanigans?
11789 Slog.w(TAG, "Can't canonicalize code path " + codePath);
11790 return Environment.getRootDirectory().getPath();
11793 return codeRoot.getPath();
11797 * Derive and set the location of native libraries for the given package,
11798 * which varies depending on where and how the package was installed.
11800 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11801 final ApplicationInfo info = pkg.applicationInfo;
11802 final String codePath = pkg.codePath;
11803 final File codeFile = new File(codePath);
11804 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11805 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11807 info.nativeLibraryRootDir = null;
11808 info.nativeLibraryRootRequiresIsa = false;
11809 info.nativeLibraryDir = null;
11810 info.secondaryNativeLibraryDir = null;
11812 if (isApkFile(codeFile)) {
11813 // Monolithic install
11815 // If "/system/lib64/apkname" exists, assume that is the per-package
11816 // native library directory to use; otherwise use "/system/lib/apkname".
11817 final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11818 final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11819 getPrimaryInstructionSet(info));
11821 // This is a bundled system app so choose the path based on the ABI.
11822 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11823 // is just the default path.
11824 final String apkName = deriveCodePathName(codePath);
11825 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11826 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11827 apkName).getAbsolutePath();
11829 if (info.secondaryCpuAbi != null) {
11830 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11831 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11832 secondaryLibDir, apkName).getAbsolutePath();
11834 } else if (asecApp) {
11835 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11836 .getAbsolutePath();
11838 final String apkName = deriveCodePathName(codePath);
11839 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11840 .getAbsolutePath();
11843 info.nativeLibraryRootRequiresIsa = false;
11844 info.nativeLibraryDir = info.nativeLibraryRootDir;
11847 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11848 info.nativeLibraryRootRequiresIsa = true;
11850 info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11851 getPrimaryInstructionSet(info)).getAbsolutePath();
11853 if (info.secondaryCpuAbi != null) {
11854 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11855 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11861 * Calculate the abis and roots for a bundled app. These can uniquely
11862 * be determined from the contents of the system partition, i.e whether
11863 * it contains 64 or 32 bit shared libraries etc. We do not validate any
11864 * of this information, and instead assume that the system was built
11867 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11868 PackageSetting pkgSetting) {
11869 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11871 // If "/system/lib64/apkname" exists, assume that is the per-package
11872 // native library directory to use; otherwise use "/system/lib/apkname".
11873 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11874 setBundledAppAbi(pkg, apkRoot, apkName);
11875 // pkgSetting might be null during rescan following uninstall of updates
11876 // to a bundled app, so accommodate that possibility. The settings in
11877 // that case will be established later from the parsed package.
11879 // If the settings aren't null, sync them up with what we've just derived.
11880 // note that apkRoot isn't stored in the package settings.
11881 if (pkgSetting != null) {
11882 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11883 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11888 * Deduces the ABI of a bundled app and sets the relevant fields on the
11889 * parsed pkg object.
11891 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11892 * under which system libraries are installed.
11893 * @param apkName the name of the installed package.
11895 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11896 final File codeFile = new File(pkg.codePath);
11898 final boolean has64BitLibs;
11899 final boolean has32BitLibs;
11900 if (isApkFile(codeFile)) {
11901 // Monolithic install
11902 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11903 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11906 final File rootDir = new File(codeFile, LIB_DIR_NAME);
11907 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11908 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11909 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11910 has64BitLibs = (new File(rootDir, isa)).exists();
11912 has64BitLibs = false;
11914 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11915 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11916 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11917 has32BitLibs = (new File(rootDir, isa)).exists();
11919 has32BitLibs = false;
11923 if (has64BitLibs && !has32BitLibs) {
11924 // The package has 64 bit libs, but not 32 bit libs. Its primary
11925 // ABI should be 64 bit. We can safely assume here that the bundled
11926 // native libraries correspond to the most preferred ABI in the list.
11928 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11929 pkg.applicationInfo.secondaryCpuAbi = null;
11930 } else if (has32BitLibs && !has64BitLibs) {
11931 // The package has 32 bit libs but not 64 bit libs. Its primary
11932 // ABI should be 32 bit.
11934 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11935 pkg.applicationInfo.secondaryCpuAbi = null;
11936 } else if (has32BitLibs && has64BitLibs) {
11937 // The application has both 64 and 32 bit bundled libraries. We check
11938 // here that the app declares multiArch support, and warn if it doesn't.
11940 // We will be lenient here and record both ABIs. The primary will be the
11941 // ABI that's higher on the list, i.e, a device that's configured to prefer
11942 // 64 bit apps will see a 64 bit primary ABI,
11944 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11945 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11948 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11949 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11950 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11952 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11953 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11956 pkg.applicationInfo.primaryCpuAbi = null;
11957 pkg.applicationInfo.secondaryCpuAbi = null;
11961 private void killApplication(String pkgName, int appId, String reason) {
11962 killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11965 private void killApplication(String pkgName, int appId, int userId, String reason) {
11966 // Request the ActivityManager to kill the process(only for existing packages)
11967 // so that we do not end up in a confused state while the user is still using the older
11968 // version of the application while the new one gets installed.
11969 final long token = Binder.clearCallingIdentity();
11971 IActivityManager am = ActivityManager.getService();
11974 am.killApplication(pkgName, appId, userId, reason);
11975 } catch (RemoteException e) {
11979 Binder.restoreCallingIdentity(token);
11983 private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11984 // Remove the parent package setting
11985 PackageSetting ps = (PackageSetting) pkg.mExtras;
11987 removePackageLI(ps, chatty);
11989 // Remove the child package setting
11990 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11991 for (int i = 0; i < childCount; i++) {
11992 PackageParser.Package childPkg = pkg.childPackages.get(i);
11993 ps = (PackageSetting) childPkg.mExtras;
11995 removePackageLI(ps, chatty);
12000 void removePackageLI(PackageSetting ps, boolean chatty) {
12001 if (DEBUG_INSTALL) {
12003 Log.d(TAG, "Removing package " + ps.name);
12007 synchronized (mPackages) {
12008 mPackages.remove(ps.name);
12009 final PackageParser.Package pkg = ps.pkg;
12011 cleanPackageDataStructuresLILPw(pkg, chatty);
12016 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12017 if (DEBUG_INSTALL) {
12019 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12023 synchronized (mPackages) {
12024 // Remove the parent package
12025 mPackages.remove(pkg.applicationInfo.packageName);
12026 cleanPackageDataStructuresLILPw(pkg, chatty);
12028 // Remove the child packages
12029 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12030 for (int i = 0; i < childCount; i++) {
12031 PackageParser.Package childPkg = pkg.childPackages.get(i);
12032 mPackages.remove(childPkg.applicationInfo.packageName);
12033 cleanPackageDataStructuresLILPw(childPkg, chatty);
12038 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12039 int N = pkg.providers.size();
12040 StringBuilder r = null;
12042 for (i=0; i<N; i++) {
12043 PackageParser.Provider p = pkg.providers.get(i);
12044 mProviders.removeProvider(p);
12045 if (p.info.authority == null) {
12047 /* There was another ContentProvider with this authority when
12048 * this app was installed so this authority is null,
12049 * Ignore it as we don't have to unregister the provider.
12053 String names[] = p.info.authority.split(";");
12054 for (int j = 0; j < names.length; j++) {
12055 if (mProvidersByAuthority.get(names[j]) == p) {
12056 mProvidersByAuthority.remove(names[j]);
12057 if (DEBUG_REMOVE) {
12059 Log.d(TAG, "Unregistered content provider: " + names[j]
12060 + ", className = " + p.info.name + ", isSyncable = "
12061 + p.info.isSyncable);
12065 if (DEBUG_REMOVE && chatty) {
12067 r = new StringBuilder(256);
12071 r.append(p.info.name);
12075 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r);
12078 N = pkg.services.size();
12080 for (i=0; i<N; i++) {
12081 PackageParser.Service s = pkg.services.get(i);
12082 mServices.removeService(s);
12085 r = new StringBuilder(256);
12089 r.append(s.info.name);
12093 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r);
12096 N = pkg.receivers.size();
12098 for (i=0; i<N; i++) {
12099 PackageParser.Activity a = pkg.receivers.get(i);
12100 mReceivers.removeActivity(a, "receiver");
12101 if (DEBUG_REMOVE && chatty) {
12103 r = new StringBuilder(256);
12107 r.append(a.info.name);
12111 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r);
12114 N = pkg.activities.size();
12116 for (i=0; i<N; i++) {
12117 PackageParser.Activity a = pkg.activities.get(i);
12118 mActivities.removeActivity(a, "activity");
12119 if (DEBUG_REMOVE && chatty) {
12121 r = new StringBuilder(256);
12125 r.append(a.info.name);
12129 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r);
12132 N = pkg.permissions.size();
12134 for (i=0; i<N; i++) {
12135 PackageParser.Permission p = pkg.permissions.get(i);
12136 BasePermission bp = mSettings.mPermissions.get(p.info.name);
12138 bp = mSettings.mPermissionTrees.get(p.info.name);
12140 if (bp != null && bp.perm == p) {
12142 if (DEBUG_REMOVE && chatty) {
12144 r = new StringBuilder(256);
12148 r.append(p.info.name);
12151 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12152 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12153 if (appOpPkgs != null) {
12154 appOpPkgs.remove(pkg.packageName);
12159 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r);
12162 N = pkg.requestedPermissions.size();
12164 for (i=0; i<N; i++) {
12165 String perm = pkg.requestedPermissions.get(i);
12166 BasePermission bp = mSettings.mPermissions.get(perm);
12167 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12168 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12169 if (appOpPkgs != null) {
12170 appOpPkgs.remove(pkg.packageName);
12171 if (appOpPkgs.isEmpty()) {
12172 mAppOpPermissionPackages.remove(perm);
12178 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r);
12181 N = pkg.instrumentation.size();
12183 for (i=0; i<N; i++) {
12184 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12185 mInstrumentation.remove(a.getComponentName());
12186 if (DEBUG_REMOVE && chatty) {
12188 r = new StringBuilder(256);
12192 r.append(a.info.name);
12196 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r);
12200 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12201 // Only system apps can hold shared libraries.
12202 if (pkg.libraryNames != null) {
12203 for (i = 0; i < pkg.libraryNames.size(); i++) {
12204 String name = pkg.libraryNames.get(i);
12205 if (removeSharedLibraryLPw(name, 0)) {
12206 if (DEBUG_REMOVE && chatty) {
12208 r = new StringBuilder(256);
12221 // Any package can hold static shared libraries.
12222 if (pkg.staticSharedLibName != null) {
12223 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12224 if (DEBUG_REMOVE && chatty) {
12226 r = new StringBuilder(256);
12230 r.append(pkg.staticSharedLibName);
12236 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r);
12240 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12241 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12242 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12249 static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12250 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12251 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12253 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12254 // Update the parent permissions
12255 updatePermissionsLPw(pkg.packageName, pkg, flags);
12256 // Update the child permissions
12257 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12258 for (int i = 0; i < childCount; i++) {
12259 PackageParser.Package childPkg = pkg.childPackages.get(i);
12260 updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12264 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12266 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12267 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12270 private void updatePermissionsLPw(String changingPkg,
12271 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12272 // Make sure there are no dangling permission trees.
12273 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12274 while (it.hasNext()) {
12275 final BasePermission bp = it.next();
12276 if (bp.packageSetting == null) {
12277 // We may not yet have parsed the package, so just see if
12278 // we still know about its settings.
12279 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12281 if (bp.packageSetting == null) {
12282 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12283 + " from package " + bp.sourcePackage);
12285 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12286 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12287 Slog.i(TAG, "Removing old permission tree: " + bp.name
12288 + " from package " + bp.sourcePackage);
12289 flags |= UPDATE_PERMISSIONS_ALL;
12295 // Make sure all dynamic permissions have been assigned to a package,
12296 // and make sure there are no dangling permissions.
12297 it = mSettings.mPermissions.values().iterator();
12298 while (it.hasNext()) {
12299 final BasePermission bp = it.next();
12300 if (bp.type == BasePermission.TYPE_DYNAMIC) {
12301 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12302 + bp.name + " pkg=" + bp.sourcePackage
12303 + " info=" + bp.pendingInfo);
12304 if (bp.packageSetting == null && bp.pendingInfo != null) {
12305 final BasePermission tree = findPermissionTreeLP(bp.name);
12306 if (tree != null && tree.perm != null) {
12307 bp.packageSetting = tree.packageSetting;
12308 bp.perm = new PackageParser.Permission(tree.perm.owner,
12309 new PermissionInfo(bp.pendingInfo));
12310 bp.perm.info.packageName = tree.perm.info.packageName;
12311 bp.perm.info.name = bp.name;
12316 if (bp.packageSetting == null) {
12317 // We may not yet have parsed the package, so just see if
12318 // we still know about its settings.
12319 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12321 if (bp.packageSetting == null) {
12322 Slog.w(TAG, "Removing dangling permission: " + bp.name
12323 + " from package " + bp.sourcePackage);
12325 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12326 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12327 Slog.i(TAG, "Removing old permission: " + bp.name
12328 + " from package " + bp.sourcePackage);
12329 flags |= UPDATE_PERMISSIONS_ALL;
12335 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12336 // Now update the permissions for all packages, in particular
12337 // replace the granted permissions of the system packages.
12338 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12339 for (PackageParser.Package pkg : mPackages.values()) {
12340 if (pkg != pkgInfo) {
12341 // Only replace for packages on requested volume
12342 final String volumeUuid = getVolumeUuidForPackage(pkg);
12343 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12344 && Objects.equals(replaceVolumeUuid, volumeUuid);
12345 grantPermissionsLPw(pkg, replace, changingPkg);
12350 if (pkgInfo != null) {
12351 // Only replace for packages on requested volume
12352 final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12353 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12354 && Objects.equals(replaceVolumeUuid, volumeUuid);
12355 grantPermissionsLPw(pkgInfo, replace, changingPkg);
12357 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12360 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12361 String packageOfInterest) {
12362 // IMPORTANT: There are two types of permissions: install and runtime.
12363 // Install time permissions are granted when the app is installed to
12364 // all device users and users added in the future. Runtime permissions
12365 // are granted at runtime explicitly to specific users. Normal and signature
12366 // protected permissions are install time permissions. Dangerous permissions
12367 // are install permissions if the app's target SDK is Lollipop MR1 or older,
12368 // otherwise they are runtime permissions. This function does not manage
12369 // runtime permissions except for the case an app targeting Lollipop MR1
12370 // being upgraded to target a newer SDK, in which case dangerous permissions
12371 // are transformed from install time to runtime ones.
12373 final PackageSetting ps = (PackageSetting) pkg.mExtras;
12378 PermissionsState permissionsState = ps.getPermissionsState();
12379 PermissionsState origPermissions = permissionsState;
12381 final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12383 boolean runtimePermissionsRevoked = false;
12384 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12386 boolean changedInstallPermission = false;
12389 ps.installPermissionsFixed = false;
12390 if (!ps.isSharedUser()) {
12391 origPermissions = new PermissionsState(permissionsState);
12392 permissionsState.reset();
12394 // We need to know only about runtime permission changes since the
12395 // calling code always writes the install permissions state but
12396 // the runtime ones are written only if changed. The only cases of
12397 // changed runtime permissions here are promotion of an install to
12398 // runtime and revocation of a runtime from a shared user.
12399 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12400 ps.sharedUser, UserManagerService.getInstance().getUserIds());
12401 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12402 runtimePermissionsRevoked = true;
12407 permissionsState.setGlobalGids(mGlobalGids);
12409 final int N = pkg.requestedPermissions.size();
12410 for (int i=0; i<N; i++) {
12411 final String name = pkg.requestedPermissions.get(i);
12412 final BasePermission bp = mSettings.mPermissions.get(name);
12413 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12414 >= Build.VERSION_CODES.M;
12416 if (DEBUG_INSTALL) {
12417 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12420 if (bp == null || bp.packageSetting == null) {
12421 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12422 if (DEBUG_PERMISSIONS) {
12423 Slog.i(TAG, "Unknown permission " + name
12424 + " in package " + pkg.packageName);
12431 // Limit ephemeral apps to ephemeral allowed permissions.
12432 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12433 if (DEBUG_PERMISSIONS) {
12434 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12435 + pkg.packageName);
12440 if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12441 if (DEBUG_PERMISSIONS) {
12442 Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12443 + pkg.packageName);
12448 final String perm = bp.name;
12449 boolean allowedSig = false;
12450 int grant = GRANT_DENIED;
12452 // Keep track of app op permissions.
12453 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12454 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12455 if (pkgs == null) {
12456 pkgs = new ArraySet<>();
12457 mAppOpPermissionPackages.put(bp.name, pkgs);
12459 pkgs.add(pkg.packageName);
12462 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12464 case PermissionInfo.PROTECTION_NORMAL: {
12465 // For all apps normal permissions are install time ones.
12466 grant = GRANT_INSTALL;
12469 case PermissionInfo.PROTECTION_DANGEROUS: {
12470 // If a permission review is required for legacy apps we represent
12471 // their permissions as always granted runtime ones since we need
12472 // to keep the review required permission flag per user while an
12473 // install permission's state is shared across all users.
12474 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12475 // For legacy apps dangerous permissions are install time ones.
12476 grant = GRANT_INSTALL;
12477 } else if (origPermissions.hasInstallPermission(bp.name)) {
12478 // For legacy apps that became modern, install becomes runtime.
12479 grant = GRANT_UPGRADE;
12480 } else if (mPromoteSystemApps
12482 && mExistingSystemPackages.contains(ps.name)) {
12483 // For legacy system apps, install becomes runtime.
12484 // We cannot check hasInstallPermission() for system apps since those
12485 // permissions were granted implicitly and not persisted pre-M.
12486 grant = GRANT_UPGRADE;
12488 // For modern apps keep runtime permissions unchanged.
12489 grant = GRANT_RUNTIME;
12493 case PermissionInfo.PROTECTION_SIGNATURE: {
12494 // For all apps signature permissions are install time ones.
12495 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12497 grant = GRANT_INSTALL;
12502 if (DEBUG_PERMISSIONS) {
12503 Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12506 if (grant != GRANT_DENIED) {
12507 if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12508 // If this is an existing, non-system package, then
12509 // we can't add any new permissions to it.
12510 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12511 // Except... if this is a permission that was added
12512 // to the platform (note: need to only do this when
12513 // updating the platform).
12514 if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12515 grant = GRANT_DENIED;
12521 case GRANT_INSTALL: {
12522 // Revoke this as runtime permission to handle the case of
12523 // a runtime permission being downgraded to an install one.
12524 // Also in permission review mode we keep dangerous permissions
12526 for (int userId : UserManagerService.getInstance().getUserIds()) {
12527 if (origPermissions.getRuntimePermissionState(
12528 bp.name, userId) != null) {
12529 // Revoke the runtime permission and clear the flags.
12530 origPermissions.revokeRuntimePermission(bp, userId);
12531 origPermissions.updatePermissionFlags(bp, userId,
12532 PackageManager.MASK_PERMISSION_FLAGS, 0);
12533 // If we revoked a permission permission, we have to write.
12534 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12535 changedRuntimePermissionUserIds, userId);
12538 // Grant an install permission.
12539 if (permissionsState.grantInstallPermission(bp) !=
12540 PermissionsState.PERMISSION_OPERATION_FAILURE) {
12541 changedInstallPermission = true;
12545 case GRANT_RUNTIME: {
12546 // Grant previously granted runtime permissions.
12547 for (int userId : UserManagerService.getInstance().getUserIds()) {
12548 PermissionState permissionState = origPermissions
12549 .getRuntimePermissionState(bp.name, userId);
12550 int flags = permissionState != null
12551 ? permissionState.getFlags() : 0;
12552 if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12553 // Don't propagate the permission in a permission review mode if
12554 // the former was revoked, i.e. marked to not propagate on upgrade.
12555 // Note that in a permission review mode install permissions are
12556 // represented as constantly granted runtime ones since we need to
12557 // keep a per user state associated with the permission. Also the
12558 // revoke on upgrade flag is no longer applicable and is reset.
12559 final boolean revokeOnUpgrade = (flags & PackageManager
12560 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12561 if (revokeOnUpgrade) {
12562 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12563 // Since we changed the flags, we have to write.
12564 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12565 changedRuntimePermissionUserIds, userId);
12567 if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12568 if (permissionsState.grantRuntimePermission(bp, userId) ==
12569 PermissionsState.PERMISSION_OPERATION_FAILURE) {
12570 // If we cannot put the permission as it was,
12571 // we have to write.
12572 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12573 changedRuntimePermissionUserIds, userId);
12577 // If the app supports runtime permissions no need for a review.
12578 if (mPermissionReviewRequired
12579 && appSupportsRuntimePermissions
12580 && (flags & PackageManager
12581 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12582 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12583 // Since we changed the flags, we have to write.
12584 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12585 changedRuntimePermissionUserIds, userId);
12587 } else if (mPermissionReviewRequired
12588 && !appSupportsRuntimePermissions) {
12589 // For legacy apps that need a permission review, every new
12590 // runtime permission is granted but it is pending a review.
12591 // We also need to review only platform defined runtime
12592 // permissions as these are the only ones the platform knows
12593 // how to disable the API to simulate revocation as legacy
12594 // apps don't expect to run with revoked permissions.
12595 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12596 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12597 flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12598 // We changed the flags, hence have to write.
12599 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12600 changedRuntimePermissionUserIds, userId);
12603 if (permissionsState.grantRuntimePermission(bp, userId)
12604 != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12605 // We changed the permission, hence have to write.
12606 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12607 changedRuntimePermissionUserIds, userId);
12610 // Propagate the permission flags.
12611 permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12615 case GRANT_UPGRADE: {
12616 // Grant runtime permissions for a previously held install permission.
12617 PermissionState permissionState = origPermissions
12618 .getInstallPermissionState(bp.name);
12619 final int flags = permissionState != null ? permissionState.getFlags() : 0;
12621 if (origPermissions.revokeInstallPermission(bp)
12622 != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12623 // We will be transferring the permission flags, so clear them.
12624 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12625 PackageManager.MASK_PERMISSION_FLAGS, 0);
12626 changedInstallPermission = true;
12629 // If the permission is not to be promoted to runtime we ignore it and
12630 // also its other flags as they are not applicable to install permissions.
12631 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12632 for (int userId : currentUserIds) {
12633 if (permissionsState.grantRuntimePermission(bp, userId) !=
12634 PermissionsState.PERMISSION_OPERATION_FAILURE) {
12635 // Transfer the permission flags.
12636 permissionsState.updatePermissionFlags(bp, userId,
12638 // If we granted the permission, we have to write.
12639 changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12640 changedRuntimePermissionUserIds, userId);
12647 if (packageOfInterest == null
12648 || packageOfInterest.equals(pkg.packageName)) {
12649 if (DEBUG_PERMISSIONS) {
12650 Slog.i(TAG, "Not granting permission " + perm
12651 + " to package " + pkg.packageName
12652 + " because it was previously installed without");
12658 if (permissionsState.revokeInstallPermission(bp) !=
12659 PermissionsState.PERMISSION_OPERATION_FAILURE) {
12660 // Also drop the permission flags.
12661 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12662 PackageManager.MASK_PERMISSION_FLAGS, 0);
12663 changedInstallPermission = true;
12664 Slog.i(TAG, "Un-granting permission " + perm
12665 + " from package " + pkg.packageName
12666 + " (protectionLevel=" + bp.protectionLevel
12667 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12669 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12670 // Don't print warning for app op permissions, since it is fine for them
12671 // not to be granted, there is a UI for the user to decide.
12672 if (DEBUG_PERMISSIONS
12673 && (packageOfInterest == null
12674 || packageOfInterest.equals(pkg.packageName))) {
12675 Slog.i(TAG, "Not granting permission " + perm
12676 + " to package " + pkg.packageName
12677 + " (protectionLevel=" + bp.protectionLevel
12678 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12685 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12686 !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12687 // This is the first that we have heard about this package, so the
12688 // permissions we have now selected are fixed until explicitly
12690 ps.installPermissionsFixed = true;
12693 // Persist the runtime permissions state for users with changes. If permissions
12694 // were revoked because no app in the shared user declares them we have to
12695 // write synchronously to avoid losing runtime permissions state.
12696 for (int userId : changedRuntimePermissionUserIds) {
12697 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12701 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12702 boolean allowed = false;
12703 final int NP = PackageParser.NEW_PERMISSIONS.length;
12704 for (int ip=0; ip<NP; ip++) {
12705 final PackageParser.NewPermissionInfo npi
12706 = PackageParser.NEW_PERMISSIONS[ip];
12707 if (npi.name.equals(perm)
12708 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12710 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12711 + pkg.packageName);
12718 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12719 BasePermission bp, PermissionsState origPermissions) {
12720 boolean privilegedPermission = (bp.protectionLevel
12721 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12722 boolean privappPermissionsDisable =
12723 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12724 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12725 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12726 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12727 && !platformPackage && platformPermission) {
12728 ArraySet<String> wlPermissions = SystemConfig.getInstance()
12729 .getPrivAppPermissions(pkg.packageName);
12730 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12731 if (!whitelisted) {
12732 Slog.w(TAG, "Privileged permission " + perm + " for package "
12733 + pkg.packageName + " - not in privapp-permissions whitelist");
12734 // Only report violations for apps on system image
12735 if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12736 if (mPrivappPermissionsViolations == null) {
12737 mPrivappPermissionsViolations = new ArraySet<>();
12739 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12741 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12746 boolean allowed = (compareSignatures(
12747 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12748 == PackageManager.SIGNATURE_MATCH)
12749 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12750 == PackageManager.SIGNATURE_MATCH);
12751 if (!allowed && privilegedPermission) {
12752 if (isSystemApp(pkg)) {
12753 // For updated system applications, a system permission
12754 // is granted only if it had been defined by the original application.
12755 if (pkg.isUpdatedSystemApp()) {
12756 final PackageSetting sysPs = mSettings
12757 .getDisabledSystemPkgLPr(pkg.packageName);
12758 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12759 // If the original was granted this permission, we take
12760 // that grant decision as read and propagate it to the
12762 if (sysPs.isPrivileged()) {
12766 // The system apk may have been updated with an older
12767 // version of the one on the data partition, but which
12768 // granted a new system permission that it didn't have
12769 // before. In this case we do want to allow the app to
12770 // now get the new permission if the ancestral apk is
12771 // privileged to get it.
12772 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12773 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12774 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12780 // Also if a privileged parent package on the system image or any of
12781 // its children requested a privileged permission, the updated child
12782 // packages can also get the permission.
12783 if (pkg.parentPackage != null) {
12784 final PackageSetting disabledSysParentPs = mSettings
12785 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12786 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12787 && disabledSysParentPs.isPrivileged()) {
12788 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12790 } else if (disabledSysParentPs.pkg.childPackages != null) {
12791 final int count = disabledSysParentPs.pkg.childPackages.size();
12792 for (int i = 0; i < count; i++) {
12793 PackageParser.Package disabledSysChildPkg =
12794 disabledSysParentPs.pkg.childPackages.get(i);
12795 if (isPackageRequestingPermission(disabledSysChildPkg,
12806 allowed = isPrivilegedApp(pkg);
12811 if (!allowed && (bp.protectionLevel
12812 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12813 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12814 // If this was a previously normal/dangerous permission that got moved
12815 // to a system permission as part of the runtime permission redesign, then
12816 // we still want to blindly grant it to old apps.
12819 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12820 && pkg.packageName.equals(mRequiredInstallerPackage)) {
12821 // If this permission is to be granted to the system installer and
12822 // this app is an installer, then it gets the permission.
12825 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12826 && pkg.packageName.equals(mRequiredVerifierPackage)) {
12827 // If this permission is to be granted to the system verifier and
12828 // this app is a verifier, then it gets the permission.
12831 if (!allowed && (bp.protectionLevel
12832 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12833 && isSystemApp(pkg)) {
12834 // Any pre-installed system app is allowed to get this permission.
12837 if (!allowed && (bp.protectionLevel
12838 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12839 // For development permissions, a development permission
12840 // is granted only if it was already granted.
12841 allowed = origPermissions.hasInstallPermission(perm);
12843 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12844 && pkg.packageName.equals(mSetupWizardPackage)) {
12845 // If this permission is to be granted to the system setup wizard and
12846 // this app is a setup wizard, then it gets the permission.
12853 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12854 final int permCount = pkg.requestedPermissions.size();
12855 for (int j = 0; j < permCount; j++) {
12856 String requestedPermission = pkg.requestedPermissions.get(j);
12857 if (permission.equals(requestedPermission)) {
12864 final class ActivityIntentResolver
12865 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12866 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12867 boolean defaultOnly, int userId) {
12868 if (!sUserManager.exists(userId)) return null;
12869 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12870 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12873 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12875 if (!sUserManager.exists(userId)) return null;
12877 return super.queryIntent(intent, resolvedType,
12878 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12882 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12883 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12884 if (!sUserManager.exists(userId)) return null;
12885 if (packageActivities == null) {
12889 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12890 final int N = packageActivities.size();
12891 ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12892 new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12894 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12895 for (int i = 0; i < N; ++i) {
12896 intentFilters = packageActivities.get(i).intents;
12897 if (intentFilters != null && intentFilters.size() > 0) {
12898 PackageParser.ActivityIntentInfo[] array =
12899 new PackageParser.ActivityIntentInfo[intentFilters.size()];
12900 intentFilters.toArray(array);
12901 listCut.add(array);
12904 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12908 * Finds a privileged activity that matches the specified activity names.
12910 private PackageParser.Activity findMatchingActivity(
12911 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12912 for (PackageParser.Activity sysActivity : activityList) {
12913 if (sysActivity.info.name.equals(activityInfo.name)) {
12914 return sysActivity;
12916 if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12917 return sysActivity;
12919 if (sysActivity.info.targetActivity != null) {
12920 if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12921 return sysActivity;
12923 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12924 return sysActivity;
12931 public class IterGenerator<E> {
12932 public Iterator<E> generate(ActivityIntentInfo info) {
12937 public class ActionIterGenerator extends IterGenerator<String> {
12939 public Iterator<String> generate(ActivityIntentInfo info) {
12940 return info.actionsIterator();
12944 public class CategoriesIterGenerator extends IterGenerator<String> {
12946 public Iterator<String> generate(ActivityIntentInfo info) {
12947 return info.categoriesIterator();
12951 public class SchemesIterGenerator extends IterGenerator<String> {
12953 public Iterator<String> generate(ActivityIntentInfo info) {
12954 return info.schemesIterator();
12958 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12960 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12961 return info.authoritiesIterator();
12966 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12967 * MODIFIED. Do not pass in a list that should not be changed.
12969 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12970 IterGenerator<T> generator, Iterator<T> searchIterator) {
12971 // loop through the set of actions; every one must be found in the intent filter
12972 while (searchIterator.hasNext()) {
12973 // we must have at least one filter in the list to consider a match
12974 if (intentList.size() == 0) {
12978 final T searchAction = searchIterator.next();
12980 // loop through the set of intent filters
12981 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12982 while (intentIter.hasNext()) {
12983 final ActivityIntentInfo intentInfo = intentIter.next();
12984 boolean selectionFound = false;
12986 // loop through the intent filter's selection criteria; at least one
12987 // of them must match the searched criteria
12988 final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12989 while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12990 final T intentSelection = intentSelectionIter.next();
12991 if (intentSelection != null && intentSelection.equals(searchAction)) {
12992 selectionFound = true;
12997 // the selection criteria wasn't found in this filter's set; this filter
12998 // is not a potential match
12999 if (!selectionFound) {
13000 intentIter.remove();
13006 private boolean isProtectedAction(ActivityIntentInfo filter) {
13007 final Iterator<String> actionsIter = filter.actionsIterator();
13008 while (actionsIter != null && actionsIter.hasNext()) {
13009 final String filterAction = actionsIter.next();
13010 if (PROTECTED_ACTIONS.contains(filterAction)) {
13018 * Adjusts the priority of the given intent filter according to policy.
13021 * <li>The priority for non privileged applications is capped to '0'</li>
13022 * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13023 * <li>The priority for unbundled updates to privileged applications is capped to the
13024 * priority defined on the system partition</li>
13027 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13028 * allowed to obtain any priority on any action.
13030 private void adjustPriority(
13031 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13032 // nothing to do; priority is fine as-is
13033 if (intent.getPriority() <= 0) {
13037 final ActivityInfo activityInfo = intent.activity.info;
13038 final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13040 final boolean privilegedApp =
13041 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13042 if (!privilegedApp) {
13043 // non-privileged applications can never define a priority >0
13044 if (DEBUG_FILTERS) {
13045 Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13046 + " package: " + applicationInfo.packageName
13047 + " activity: " + intent.activity.className
13048 + " origPrio: " + intent.getPriority());
13050 intent.setPriority(0);
13054 if (systemActivities == null) {
13055 // the system package is not disabled; we're parsing the system partition
13056 if (isProtectedAction(intent)) {
13057 if (mDeferProtectedFilters) {
13058 // We can't deal with these just yet. No component should ever obtain a
13059 // >0 priority for a protected actions, with ONE exception -- the setup
13060 // wizard. The setup wizard, however, cannot be known until we're able to
13061 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13062 // until all intent filters have been processed. Chicken, meet egg.
13063 // Let the filter temporarily have a high priority and rectify the
13064 // priorities after all system packages have been scanned.
13065 mProtectedFilters.add(intent);
13066 if (DEBUG_FILTERS) {
13067 Slog.i(TAG, "Protected action; save for later;"
13068 + " package: " + applicationInfo.packageName
13069 + " activity: " + intent.activity.className
13070 + " origPrio: " + intent.getPriority());
13074 if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13075 Slog.i(TAG, "No setup wizard;"
13076 + " All protected intents capped to priority 0");
13078 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13079 if (DEBUG_FILTERS) {
13080 Slog.i(TAG, "Found setup wizard;"
13081 + " allow priority " + intent.getPriority() + ";"
13082 + " package: " + intent.activity.info.packageName
13083 + " activity: " + intent.activity.className
13084 + " priority: " + intent.getPriority());
13086 // setup wizard gets whatever it wants
13089 if (DEBUG_FILTERS) {
13090 Slog.i(TAG, "Protected action; cap priority to 0;"
13091 + " package: " + intent.activity.info.packageName
13092 + " activity: " + intent.activity.className
13093 + " origPrio: " + intent.getPriority());
13095 intent.setPriority(0);
13099 // privileged apps on the system image get whatever priority they request
13103 // privileged app unbundled update ... try to find the same activity
13104 final PackageParser.Activity foundActivity =
13105 findMatchingActivity(systemActivities, activityInfo);
13106 if (foundActivity == null) {
13107 // this is a new activity; it cannot obtain >0 priority
13108 if (DEBUG_FILTERS) {
13109 Slog.i(TAG, "New activity; cap priority to 0;"
13110 + " package: " + applicationInfo.packageName
13111 + " activity: " + intent.activity.className
13112 + " origPrio: " + intent.getPriority());
13114 intent.setPriority(0);
13118 // found activity, now check for filter equivalence
13120 // a shallow copy is enough; we modify the list, not its contents
13121 final List<ActivityIntentInfo> intentListCopy =
13122 new ArrayList<>(foundActivity.intents);
13123 final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13125 // find matching action subsets
13126 final Iterator<String> actionsIterator = intent.actionsIterator();
13127 if (actionsIterator != null) {
13128 getIntentListSubset(
13129 intentListCopy, new ActionIterGenerator(), actionsIterator);
13130 if (intentListCopy.size() == 0) {
13131 // no more intents to match; we're not equivalent
13132 if (DEBUG_FILTERS) {
13133 Slog.i(TAG, "Mismatched action; cap priority to 0;"
13134 + " package: " + applicationInfo.packageName
13135 + " activity: " + intent.activity.className
13136 + " origPrio: " + intent.getPriority());
13138 intent.setPriority(0);
13143 // find matching category subsets
13144 final Iterator<String> categoriesIterator = intent.categoriesIterator();
13145 if (categoriesIterator != null) {
13146 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13147 categoriesIterator);
13148 if (intentListCopy.size() == 0) {
13149 // no more intents to match; we're not equivalent
13150 if (DEBUG_FILTERS) {
13151 Slog.i(TAG, "Mismatched category; cap priority to 0;"
13152 + " package: " + applicationInfo.packageName
13153 + " activity: " + intent.activity.className
13154 + " origPrio: " + intent.getPriority());
13156 intent.setPriority(0);
13161 // find matching schemes subsets
13162 final Iterator<String> schemesIterator = intent.schemesIterator();
13163 if (schemesIterator != null) {
13164 getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13166 if (intentListCopy.size() == 0) {
13167 // no more intents to match; we're not equivalent
13168 if (DEBUG_FILTERS) {
13169 Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13170 + " package: " + applicationInfo.packageName
13171 + " activity: " + intent.activity.className
13172 + " origPrio: " + intent.getPriority());
13174 intent.setPriority(0);
13179 // find matching authorities subsets
13180 final Iterator<IntentFilter.AuthorityEntry>
13181 authoritiesIterator = intent.authoritiesIterator();
13182 if (authoritiesIterator != null) {
13183 getIntentListSubset(intentListCopy,
13184 new AuthoritiesIterGenerator(),
13185 authoritiesIterator);
13186 if (intentListCopy.size() == 0) {
13187 // no more intents to match; we're not equivalent
13188 if (DEBUG_FILTERS) {
13189 Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13190 + " package: " + applicationInfo.packageName
13191 + " activity: " + intent.activity.className
13192 + " origPrio: " + intent.getPriority());
13194 intent.setPriority(0);
13199 // we found matching filter(s); app gets the max priority of all intents
13200 int cappedPriority = 0;
13201 for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13202 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13204 if (intent.getPriority() > cappedPriority) {
13205 if (DEBUG_FILTERS) {
13206 Slog.i(TAG, "Found matching filter(s);"
13207 + " cap priority to " + cappedPriority + ";"
13208 + " package: " + applicationInfo.packageName
13209 + " activity: " + intent.activity.className
13210 + " origPrio: " + intent.getPriority());
13212 intent.setPriority(cappedPriority);
13215 // all this for nothing; the requested priority was <= what was on the system
13218 public final void addActivity(PackageParser.Activity a, String type) {
13219 mActivities.put(a.getComponentName(), a);
13220 if (DEBUG_SHOW_INFO)
13222 TAG, " " + type + " " +
13223 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13224 if (DEBUG_SHOW_INFO)
13225 Log.v(TAG, " Class=" + a.info.name);
13226 final int NI = a.intents.size();
13227 for (int j=0; j<NI; j++) {
13228 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13229 if ("activity".equals(type)) {
13230 final PackageSetting ps =
13231 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13232 final List<PackageParser.Activity> systemActivities =
13233 ps != null && ps.pkg != null ? ps.pkg.activities : null;
13234 adjustPriority(systemActivities, intent);
13236 if (DEBUG_SHOW_INFO) {
13237 Log.v(TAG, " IntentFilter:");
13238 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
13240 if (!intent.debugCheck()) {
13241 Log.w(TAG, "==> For Activity " + a.info.name);
13247 public final void removeActivity(PackageParser.Activity a, String type) {
13248 mActivities.remove(a.getComponentName());
13249 if (DEBUG_SHOW_INFO) {
13250 Log.v(TAG, " " + type + " "
13251 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13252 : a.info.name) + ":");
13253 Log.v(TAG, " Class=" + a.info.name);
13255 final int NI = a.intents.size();
13256 for (int j=0; j<NI; j++) {
13257 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13258 if (DEBUG_SHOW_INFO) {
13259 Log.v(TAG, " IntentFilter:");
13260 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
13262 removeFilter(intent);
13267 protected boolean allowFilterResult(
13268 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13269 ActivityInfo filterAi = filter.activity.info;
13270 for (int i=dest.size()-1; i>=0; i--) {
13271 ActivityInfo destAi = dest.get(i).activityInfo;
13272 if (destAi.name == filterAi.name
13273 && destAi.packageName == filterAi.packageName) {
13281 protected ActivityIntentInfo[] newArray(int size) {
13282 return new ActivityIntentInfo[size];
13286 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13287 if (!sUserManager.exists(userId)) return true;
13288 PackageParser.Package p = filter.activity.owner;
13290 PackageSetting ps = (PackageSetting)p.mExtras;
13292 // System apps are never considered stopped for purposes of
13293 // filtering, because there may be no way for the user to
13294 // actually re-launch them.
13295 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13296 && ps.getStopped(userId);
13303 protected boolean isPackageForFilter(String packageName,
13304 PackageParser.ActivityIntentInfo info) {
13305 return packageName.equals(info.activity.owner.packageName);
13309 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13310 int match, int userId) {
13311 if (!sUserManager.exists(userId)) return null;
13312 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13315 final PackageParser.Activity activity = info.activity;
13316 PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13320 final PackageUserState userState = ps.readUserState(userId);
13322 PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13326 final boolean matchExplicitlyVisibleOnly =
13327 (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13328 final boolean matchVisibleToInstantApp =
13329 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13330 final boolean componentVisible =
13331 matchVisibleToInstantApp
13332 && info.isVisibleToInstantApp()
13333 && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13334 final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13335 // throw out filters that aren't visible to ephemeral apps
13336 if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13339 // throw out instant app filters if we're not explicitly requesting them
13340 if (!matchInstantApp && userState.instantApp) {
13343 // throw out instant app filters if updates are available; will trigger
13344 // instant app resolution
13345 if (userState.instantApp && ps.isUpdateAvailable()) {
13348 final ResolveInfo res = new ResolveInfo();
13349 res.activityInfo = ai;
13350 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13353 if (info != null) {
13354 res.handleAllWebDataURI = info.handleAllWebDataURI();
13356 res.priority = info.getPriority();
13357 res.preferredOrder = activity.owner.mPreferredOrder;
13358 //System.out.println("Result: " + res.activityInfo.className +
13359 // " = " + res.priority);
13361 res.isDefault = info.hasDefault;
13362 res.labelRes = info.labelRes;
13363 res.nonLocalizedLabel = info.nonLocalizedLabel;
13364 if (userNeedsBadging(userId)) {
13365 res.noResourceId = true;
13367 res.icon = info.icon;
13369 res.iconResourceId = info.icon;
13370 res.system = res.activityInfo.applicationInfo.isSystemApp();
13371 res.isInstantAppAvailable = userState.instantApp;
13376 protected void sortResults(List<ResolveInfo> results) {
13377 Collections.sort(results, mResolvePrioritySorter);
13381 protected void dumpFilter(PrintWriter out, String prefix,
13382 PackageParser.ActivityIntentInfo filter) {
13383 out.print(prefix); out.print(
13384 Integer.toHexString(System.identityHashCode(filter.activity)));
13386 filter.activity.printComponentShortName(out);
13387 out.print(" filter ");
13388 out.println(Integer.toHexString(System.identityHashCode(filter)));
13392 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13393 return filter.activity;
13396 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13397 PackageParser.Activity activity = (PackageParser.Activity)label;
13398 out.print(prefix); out.print(
13399 Integer.toHexString(System.identityHashCode(activity)));
13401 activity.printComponentShortName(out);
13403 out.print(" ("); out.print(count); out.print(" filters)");
13408 // Keys are String (activity class name), values are Activity.
13409 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13410 = new ArrayMap<ComponentName, PackageParser.Activity>();
13411 private int mFlags;
13414 private final class ServiceIntentResolver
13415 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13416 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13417 boolean defaultOnly, int userId) {
13418 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13419 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13422 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13424 if (!sUserManager.exists(userId)) return null;
13426 return super.queryIntent(intent, resolvedType,
13427 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13431 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13432 int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13433 if (!sUserManager.exists(userId)) return null;
13434 if (packageServices == null) {
13438 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13439 final int N = packageServices.size();
13440 ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13441 new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13443 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13444 for (int i = 0; i < N; ++i) {
13445 intentFilters = packageServices.get(i).intents;
13446 if (intentFilters != null && intentFilters.size() > 0) {
13447 PackageParser.ServiceIntentInfo[] array =
13448 new PackageParser.ServiceIntentInfo[intentFilters.size()];
13449 intentFilters.toArray(array);
13450 listCut.add(array);
13453 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13456 public final void addService(PackageParser.Service s) {
13457 mServices.put(s.getComponentName(), s);
13458 if (DEBUG_SHOW_INFO) {
13460 + (s.info.nonLocalizedLabel != null
13461 ? s.info.nonLocalizedLabel : s.info.name) + ":");
13462 Log.v(TAG, " Class=" + s.info.name);
13464 final int NI = s.intents.size();
13466 for (j=0; j<NI; j++) {
13467 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13468 if (DEBUG_SHOW_INFO) {
13469 Log.v(TAG, " IntentFilter:");
13470 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
13472 if (!intent.debugCheck()) {
13473 Log.w(TAG, "==> For Service " + s.info.name);
13479 public final void removeService(PackageParser.Service s) {
13480 mServices.remove(s.getComponentName());
13481 if (DEBUG_SHOW_INFO) {
13482 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null
13483 ? s.info.nonLocalizedLabel : s.info.name) + ":");
13484 Log.v(TAG, " Class=" + s.info.name);
13486 final int NI = s.intents.size();
13488 for (j=0; j<NI; j++) {
13489 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13490 if (DEBUG_SHOW_INFO) {
13491 Log.v(TAG, " IntentFilter:");
13492 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
13494 removeFilter(intent);
13499 protected boolean allowFilterResult(
13500 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13501 ServiceInfo filterSi = filter.service.info;
13502 for (int i=dest.size()-1; i>=0; i--) {
13503 ServiceInfo destAi = dest.get(i).serviceInfo;
13504 if (destAi.name == filterSi.name
13505 && destAi.packageName == filterSi.packageName) {
13513 protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13514 return new PackageParser.ServiceIntentInfo[size];
13518 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13519 if (!sUserManager.exists(userId)) return true;
13520 PackageParser.Package p = filter.service.owner;
13522 PackageSetting ps = (PackageSetting)p.mExtras;
13524 // System apps are never considered stopped for purposes of
13525 // filtering, because there may be no way for the user to
13526 // actually re-launch them.
13527 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13528 && ps.getStopped(userId);
13535 protected boolean isPackageForFilter(String packageName,
13536 PackageParser.ServiceIntentInfo info) {
13537 return packageName.equals(info.service.owner.packageName);
13541 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13542 int match, int userId) {
13543 if (!sUserManager.exists(userId)) return null;
13544 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13545 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13548 final PackageParser.Service service = info.service;
13549 PackageSetting ps = (PackageSetting) service.owner.mExtras;
13553 final PackageUserState userState = ps.readUserState(userId);
13554 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13555 userState, userId);
13559 final boolean matchVisibleToInstantApp =
13560 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13561 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13562 // throw out filters that aren't visible to ephemeral apps
13563 if (matchVisibleToInstantApp
13564 && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13567 // throw out ephemeral filters if we're not explicitly requesting them
13568 if (!isInstantApp && userState.instantApp) {
13571 // throw out instant app filters if updates are available; will trigger
13572 // instant app resolution
13573 if (userState.instantApp && ps.isUpdateAvailable()) {
13576 final ResolveInfo res = new ResolveInfo();
13577 res.serviceInfo = si;
13578 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13579 res.filter = filter;
13581 res.priority = info.getPriority();
13582 res.preferredOrder = service.owner.mPreferredOrder;
13584 res.isDefault = info.hasDefault;
13585 res.labelRes = info.labelRes;
13586 res.nonLocalizedLabel = info.nonLocalizedLabel;
13587 res.icon = info.icon;
13588 res.system = res.serviceInfo.applicationInfo.isSystemApp();
13593 protected void sortResults(List<ResolveInfo> results) {
13594 Collections.sort(results, mResolvePrioritySorter);
13598 protected void dumpFilter(PrintWriter out, String prefix,
13599 PackageParser.ServiceIntentInfo filter) {
13600 out.print(prefix); out.print(
13601 Integer.toHexString(System.identityHashCode(filter.service)));
13603 filter.service.printComponentShortName(out);
13604 out.print(" filter ");
13605 out.println(Integer.toHexString(System.identityHashCode(filter)));
13609 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13610 return filter.service;
13613 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13614 PackageParser.Service service = (PackageParser.Service)label;
13615 out.print(prefix); out.print(
13616 Integer.toHexString(System.identityHashCode(service)));
13618 service.printComponentShortName(out);
13620 out.print(" ("); out.print(count); out.print(" filters)");
13625 // List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13626 // final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13627 // final List<ResolveInfo> retList = Lists.newArrayList();
13628 // while (i.hasNext()) {
13629 // final ResolveInfo resolveInfo = (ResolveInfo) i;
13630 // if (isEnabledLP(resolveInfo.serviceInfo)) {
13631 // retList.add(resolveInfo);
13637 // Keys are String (activity class name), values are Activity.
13638 private final ArrayMap<ComponentName, PackageParser.Service> mServices
13639 = new ArrayMap<ComponentName, PackageParser.Service>();
13640 private int mFlags;
13643 private final class ProviderIntentResolver
13644 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13645 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13646 boolean defaultOnly, int userId) {
13647 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13648 return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13651 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13653 if (!sUserManager.exists(userId))
13656 return super.queryIntent(intent, resolvedType,
13657 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13661 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13662 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13663 if (!sUserManager.exists(userId))
13665 if (packageProviders == null) {
13669 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13670 final int N = packageProviders.size();
13671 ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13672 new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13674 ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13675 for (int i = 0; i < N; ++i) {
13676 intentFilters = packageProviders.get(i).intents;
13677 if (intentFilters != null && intentFilters.size() > 0) {
13678 PackageParser.ProviderIntentInfo[] array =
13679 new PackageParser.ProviderIntentInfo[intentFilters.size()];
13680 intentFilters.toArray(array);
13681 listCut.add(array);
13684 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13687 public final void addProvider(PackageParser.Provider p) {
13688 if (mProviders.containsKey(p.getComponentName())) {
13689 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13693 mProviders.put(p.getComponentName(), p);
13694 if (DEBUG_SHOW_INFO) {
13696 + (p.info.nonLocalizedLabel != null
13697 ? p.info.nonLocalizedLabel : p.info.name) + ":");
13698 Log.v(TAG, " Class=" + p.info.name);
13700 final int NI = p.intents.size();
13702 for (j = 0; j < NI; j++) {
13703 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13704 if (DEBUG_SHOW_INFO) {
13705 Log.v(TAG, " IntentFilter:");
13706 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
13708 if (!intent.debugCheck()) {
13709 Log.w(TAG, "==> For Provider " + p.info.name);
13715 public final void removeProvider(PackageParser.Provider p) {
13716 mProviders.remove(p.getComponentName());
13717 if (DEBUG_SHOW_INFO) {
13718 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null
13719 ? p.info.nonLocalizedLabel : p.info.name) + ":");
13720 Log.v(TAG, " Class=" + p.info.name);
13722 final int NI = p.intents.size();
13724 for (j = 0; j < NI; j++) {
13725 PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13726 if (DEBUG_SHOW_INFO) {
13727 Log.v(TAG, " IntentFilter:");
13728 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
13730 removeFilter(intent);
13735 protected boolean allowFilterResult(
13736 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13737 ProviderInfo filterPi = filter.provider.info;
13738 for (int i = dest.size() - 1; i >= 0; i--) {
13739 ProviderInfo destPi = dest.get(i).providerInfo;
13740 if (destPi.name == filterPi.name
13741 && destPi.packageName == filterPi.packageName) {
13749 protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13750 return new PackageParser.ProviderIntentInfo[size];
13754 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13755 if (!sUserManager.exists(userId))
13757 PackageParser.Package p = filter.provider.owner;
13759 PackageSetting ps = (PackageSetting) p.mExtras;
13761 // System apps are never considered stopped for purposes of
13762 // filtering, because there may be no way for the user to
13763 // actually re-launch them.
13764 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13765 && ps.getStopped(userId);
13772 protected boolean isPackageForFilter(String packageName,
13773 PackageParser.ProviderIntentInfo info) {
13774 return packageName.equals(info.provider.owner.packageName);
13778 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13779 int match, int userId) {
13780 if (!sUserManager.exists(userId))
13782 final PackageParser.ProviderIntentInfo info = filter;
13783 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13786 final PackageParser.Provider provider = info.provider;
13787 PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13791 final PackageUserState userState = ps.readUserState(userId);
13792 final boolean matchVisibleToInstantApp =
13793 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13794 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13795 // throw out filters that aren't visible to instant applications
13796 if (matchVisibleToInstantApp
13797 && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13800 // throw out instant application filters if we're not explicitly requesting them
13801 if (!isInstantApp && userState.instantApp) {
13804 // throw out instant application filters if updates are available; will trigger
13805 // instant application resolution
13806 if (userState.instantApp && ps.isUpdateAvailable()) {
13809 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13810 userState, userId);
13814 final ResolveInfo res = new ResolveInfo();
13815 res.providerInfo = pi;
13816 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13817 res.filter = filter;
13819 res.priority = info.getPriority();
13820 res.preferredOrder = provider.owner.mPreferredOrder;
13822 res.isDefault = info.hasDefault;
13823 res.labelRes = info.labelRes;
13824 res.nonLocalizedLabel = info.nonLocalizedLabel;
13825 res.icon = info.icon;
13826 res.system = res.providerInfo.applicationInfo.isSystemApp();
13831 protected void sortResults(List<ResolveInfo> results) {
13832 Collections.sort(results, mResolvePrioritySorter);
13836 protected void dumpFilter(PrintWriter out, String prefix,
13837 PackageParser.ProviderIntentInfo filter) {
13840 Integer.toHexString(System.identityHashCode(filter.provider)));
13842 filter.provider.printComponentShortName(out);
13843 out.print(" filter ");
13844 out.println(Integer.toHexString(System.identityHashCode(filter)));
13848 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13849 return filter.provider;
13852 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13853 PackageParser.Provider provider = (PackageParser.Provider)label;
13854 out.print(prefix); out.print(
13855 Integer.toHexString(System.identityHashCode(provider)));
13857 provider.printComponentShortName(out);
13859 out.print(" ("); out.print(count); out.print(" filters)");
13864 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13865 = new ArrayMap<ComponentName, PackageParser.Provider>();
13866 private int mFlags;
13869 static final class EphemeralIntentResolver
13870 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13872 * The result that has the highest defined order. Ordering applies on a
13873 * per-package basis. Mapping is from package name to Pair of order and
13874 * EphemeralResolveInfo.
13876 * NOTE: This is implemented as a field variable for convenience and efficiency.
13877 * By having a field variable, we're able to track filter ordering as soon as
13878 * a non-zero order is defined. Otherwise, multiple loops across the result set
13879 * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13880 * this needs to be contained entirely within {@link #filterResults}.
13882 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13885 protected AuxiliaryResolveInfo[] newArray(int size) {
13886 return new AuxiliaryResolveInfo[size];
13890 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13895 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13897 if (!sUserManager.exists(userId)) {
13900 final String packageName = responseObj.resolveInfo.getPackageName();
13901 final Integer order = responseObj.getOrder();
13902 final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13903 mOrderResult.get(packageName);
13904 // ordering is enabled and this item's order isn't high enough
13905 if (lastOrderResult != null && lastOrderResult.first >= order) {
13908 final InstantAppResolveInfo res = responseObj.resolveInfo;
13910 // non-zero order, enable ordering
13911 mOrderResult.put(packageName, new Pair<>(order, res));
13913 return responseObj;
13917 protected void filterResults(List<AuxiliaryResolveInfo> results) {
13918 // only do work if ordering is enabled [most of the time it won't be]
13919 if (mOrderResult.size() == 0) {
13922 int resultSize = results.size();
13923 for (int i = 0; i < resultSize; i++) {
13924 final InstantAppResolveInfo info = results.get(i).resolveInfo;
13925 final String packageName = info.getPackageName();
13926 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13927 if (savedInfo == null) {
13928 // package doesn't having ordering
13931 if (savedInfo.second == info) {
13932 // circled back to the highest ordered item; remove from order list
13933 mOrderResult.remove(savedInfo);
13934 if (mOrderResult.size() == 0) {
13935 // no more ordered items
13940 // item has a worse order, remove it from the result list
13948 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13949 new Comparator<ResolveInfo>() {
13950 public int compare(ResolveInfo r1, ResolveInfo r2) {
13951 int v1 = r1.priority;
13952 int v2 = r2.priority;
13953 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13955 return (v1 > v2) ? -1 : 1;
13957 v1 = r1.preferredOrder;
13958 v2 = r2.preferredOrder;
13960 return (v1 > v2) ? -1 : 1;
13962 if (r1.isDefault != r2.isDefault) {
13963 return r1.isDefault ? -1 : 1;
13967 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13969 return (v1 > v2) ? -1 : 1;
13971 if (r1.system != r2.system) {
13972 return r1.system ? -1 : 1;
13974 if (r1.activityInfo != null) {
13975 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13977 if (r1.serviceInfo != null) {
13978 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13980 if (r1.providerInfo != null) {
13981 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13987 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13988 new Comparator<ProviderInfo>() {
13989 public int compare(ProviderInfo p1, ProviderInfo p2) {
13990 final int v1 = p1.initOrder;
13991 final int v2 = p2.initOrder;
13992 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13996 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13997 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13998 final int[] userIds) {
13999 mHandler.post(new Runnable() {
14001 public void run() {
14003 final IActivityManager am = ActivityManager.getService();
14004 if (am == null) return;
14005 final int[] resolvedUserIds;
14006 if (userIds == null) {
14007 resolvedUserIds = am.getRunningUserIds();
14009 resolvedUserIds = userIds;
14011 for (int id : resolvedUserIds) {
14012 final Intent intent = new Intent(action,
14013 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14014 if (extras != null) {
14015 intent.putExtras(extras);
14017 if (targetPkg != null) {
14018 intent.setPackage(targetPkg);
14020 // Modify the UID when posting to other users
14021 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14022 if (uid > 0 && UserHandle.getUserId(uid) != id) {
14023 uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14024 intent.putExtra(Intent.EXTRA_UID, uid);
14026 intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14027 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14028 if (DEBUG_BROADCASTS) {
14029 RuntimeException here = new RuntimeException("here");
14030 here.fillInStackTrace();
14031 Slog.d(TAG, "Sending to user " + id + ": "
14032 + intent.toShortString(false, true, false, false)
14033 + " " + intent.getExtras(), here);
14035 am.broadcastIntent(null, intent, null, finishedReceiver,
14036 0, null, null, null, android.app.AppOpsManager.OP_NONE,
14037 null, finishedReceiver != null, false, id);
14039 } catch (RemoteException ex) {
14046 * Check if the external storage media is available. This is true if there
14047 * is a mounted external storage medium or if the external storage is
14050 private boolean isExternalMediaAvailable() {
14051 return mMediaMounted || Environment.isExternalStorageEmulated();
14055 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14056 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14060 synchronized (mPackages) {
14061 if (!isExternalMediaAvailable()) {
14062 // If the external storage is no longer mounted at this point,
14063 // the caller may not have been able to delete all of this
14064 // packages files and can not delete any more. Bail.
14067 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14068 if (lastPackage != null) {
14069 pkgs.remove(lastPackage);
14071 if (pkgs.size() > 0) {
14072 return pkgs.get(0);
14078 void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14079 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14080 userId, andCode ? 1 : 0, packageName);
14081 if (mSystemReady) {
14082 msg.sendToTarget();
14084 if (mPostSystemReadyMessages == null) {
14085 mPostSystemReadyMessages = new ArrayList<>();
14087 mPostSystemReadyMessages.add(msg);
14091 void startCleaningPackages() {
14093 if (!isExternalMediaAvailable()) {
14096 synchronized (mPackages) {
14097 if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14101 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14102 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14103 IActivityManager am = ActivityManager.getService();
14106 synchronized (mPackages) {
14107 if (!mDefaultContainerWhitelisted) {
14108 mDefaultContainerWhitelisted = true;
14109 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14110 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14115 am.backgroundWhitelistUid(dcsUid);
14117 am.startService(null, intent, null, false, mContext.getOpPackageName(),
14118 UserHandle.USER_SYSTEM);
14119 } catch (RemoteException e) {
14125 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14126 int installFlags, String installerPackageName, int userId) {
14127 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14129 final int callingUid = Binder.getCallingUid();
14130 enforceCrossUserPermission(callingUid, userId,
14131 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14133 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14135 if (observer != null) {
14136 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14138 } catch (RemoteException re) {
14143 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14144 installFlags |= PackageManager.INSTALL_FROM_ADB;
14147 // Caller holds INSTALL_PACKAGES permission, so we're less strict
14148 // about installerPackageName.
14150 installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14151 installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14155 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14156 user = UserHandle.ALL;
14158 user = new UserHandle(userId);
14161 // Only system components can circumvent runtime permissions when installing.
14162 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14163 && mContext.checkCallingOrSelfPermission(Manifest.permission
14164 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14165 throw new SecurityException("You need the "
14166 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14167 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14170 if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14171 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14172 throw new IllegalArgumentException(
14173 "New installs into ASEC containers no longer supported");
14176 final File originFile = new File(originPath);
14177 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14179 final Message msg = mHandler.obtainMessage(INIT_COPY);
14180 final VerificationInfo verificationInfo = new VerificationInfo(
14181 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14182 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14183 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14184 null /*packageAbiOverride*/, null /*grantedPermissions*/,
14185 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14186 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14189 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14190 System.identityHashCode(msg.obj));
14191 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14192 System.identityHashCode(msg.obj));
14194 mHandler.sendMessage(msg);
14199 * Ensure that the install reason matches what we know about the package installer (e.g. whether
14200 * it is acting on behalf on an enterprise or the user).
14202 * Note that the ordering of the conditionals in this method is important. The checks we perform
14203 * are as follows, in this order:
14205 * 1) If the install is being performed by a system app, we can trust the app to have set the
14206 * install reason correctly. Thus, we pass through the install reason unchanged, no matter
14208 * 2) If the install is being performed by a device or profile owner app, the install reason
14209 * should be enterprise policy. However, we cannot be sure that the device or profile owner
14210 * set the install reason correctly. If the app targets an older SDK version where install
14211 * reasons did not exist yet, or if the app author simply forgot, the install reason may be
14212 * unset or wrong. Thus, we force the install reason to be enterprise policy.
14213 * 3) In all other cases, the install is being performed by a regular app that is neither part
14214 * of the system nor a device or profile owner. We have no reason to believe that this app is
14215 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14216 * set to enterprise policy and if so, change it to unknown instead.
14218 private int fixUpInstallReason(String installerPackageName, int installerUid,
14219 int installReason) {
14220 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14221 == PERMISSION_GRANTED) {
14222 // If the install is being performed by a system app, we trust that app to have set the
14223 // install reason correctly.
14224 return installReason;
14227 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14228 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14230 ComponentName owner = null;
14232 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14233 if (owner == null) {
14234 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14236 } catch (RemoteException e) {
14238 if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14239 // If the install is being performed by a device or profile owner, the install
14240 // reason should be enterprise policy.
14241 return PackageManager.INSTALL_REASON_POLICY;
14245 if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14246 // If the install is being performed by a regular app (i.e. neither system app nor
14247 // device or profile owner), we have no reason to believe that the app is acting on
14248 // behalf of an enterprise. If the app set the install reason to enterprise policy,
14249 // change it to unknown instead.
14250 return PackageManager.INSTALL_REASON_UNKNOWN;
14253 // If the install is being performed by a regular app and the install reason was set to any
14254 // value but enterprise policy, leave the install reason unchanged.
14255 return installReason;
14258 void installStage(String packageName, File stagedDir, String stagedCid,
14259 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14260 String installerPackageName, int installerUid, UserHandle user,
14261 Certificate[][] certificates) {
14262 if (DEBUG_EPHEMERAL) {
14263 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14264 Slog.d(TAG, "Ephemeral install of " + packageName);
14267 final VerificationInfo verificationInfo = new VerificationInfo(
14268 sessionParams.originatingUri, sessionParams.referrerUri,
14269 sessionParams.originatingUid, installerUid);
14271 final OriginInfo origin;
14272 if (stagedDir != null) {
14273 origin = OriginInfo.fromStagedFile(stagedDir);
14275 origin = OriginInfo.fromStagedContainer(stagedCid);
14278 final Message msg = mHandler.obtainMessage(INIT_COPY);
14279 final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14280 sessionParams.installReason);
14281 final InstallParams params = new InstallParams(origin, null, observer,
14282 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14283 verificationInfo, user, sessionParams.abiOverride,
14284 sessionParams.grantedRuntimePermissions, certificates, installReason);
14285 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14288 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14289 System.identityHashCode(msg.obj));
14290 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14291 System.identityHashCode(msg.obj));
14293 mHandler.sendMessage(msg);
14296 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14298 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14299 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14301 // Send a session commit broadcast
14302 final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14303 info.installReason = pkgSetting.getInstallReason(userId);
14304 info.appPackageName = packageName;
14305 sendSessionCommitBroadcast(info, userId);
14308 public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14309 if (ArrayUtils.isEmpty(userIds)) {
14312 Bundle extras = new Bundle(1);
14313 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14314 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14316 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14317 packageName, extras, 0, null, null, userIds);
14319 mHandler.post(() -> {
14320 for (int userId : userIds) {
14321 sendBootCompletedBroadcastToSystemApp(packageName, userId);
14329 * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14330 * automatically without needing an explicit launch.
14331 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14333 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14334 // If user is not running, the app didn't miss any broadcast
14335 if (!mUserManagerInternal.isUserRunning(userId)) {
14338 final IActivityManager am = ActivityManager.getService();
14340 // Deliver LOCKED_BOOT_COMPLETED first
14341 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14342 .setPackage(packageName);
14343 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14344 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14345 android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14347 // Deliver BOOT_COMPLETED only if user is unlocked
14348 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14349 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14350 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14351 android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14353 } catch (RemoteException e) {
14354 throw e.rethrowFromSystemServer();
14359 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14361 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14362 PackageSetting pkgSetting;
14363 final int callingUid = Binder.getCallingUid();
14364 enforceCrossUserPermission(callingUid, userId,
14365 true /* requireFullPermission */, true /* checkShell */,
14366 "setApplicationHiddenSetting for user " + userId);
14368 if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14369 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14373 long callingId = Binder.clearCallingIdentity();
14375 boolean sendAdded = false;
14376 boolean sendRemoved = false;
14378 synchronized (mPackages) {
14379 pkgSetting = mSettings.mPackages.get(packageName);
14380 if (pkgSetting == null) {
14383 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14386 // Do not allow "android" is being disabled
14387 if ("android".equals(packageName)) {
14388 Slog.w(TAG, "Cannot hide package: android");
14391 // Cannot hide static shared libs as they are considered
14392 // a part of the using app (emulating static linking). Also
14393 // static libs are installed always on internal storage.
14394 PackageParser.Package pkg = mPackages.get(packageName);
14395 if (pkg != null && pkg.staticSharedLibName != null) {
14396 Slog.w(TAG, "Cannot hide package: " + packageName
14397 + " providing static shared library: "
14398 + pkg.staticSharedLibName);
14401 // Only allow protected packages to hide themselves.
14402 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14403 && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14404 Slog.w(TAG, "Not hiding protected package: " + packageName);
14408 if (pkgSetting.getHidden(userId) != hidden) {
14409 pkgSetting.setHidden(hidden, userId);
14410 mSettings.writePackageRestrictionsLPr(userId);
14412 sendRemoved = true;
14419 sendPackageAddedForUser(packageName, pkgSetting, userId);
14423 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14425 sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14429 Binder.restoreCallingIdentity(callingId);
14434 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14436 final PackageRemovedInfo info = new PackageRemovedInfo(this);
14437 info.removedPackage = packageName;
14438 info.installerPackageName = pkgSetting.installerPackageName;
14439 info.removedUsers = new int[] {userId};
14440 info.broadcastUsers = new int[] {userId};
14441 info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14442 info.sendPackageRemovedBroadcasts(true /*killApp*/);
14445 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14446 if (pkgList.length > 0) {
14447 Bundle extras = new Bundle(1);
14448 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14450 sendPackageBroadcast(
14451 suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14452 : Intent.ACTION_PACKAGES_UNSUSPENDED,
14453 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14454 new int[] {userId});
14459 * Returns true if application is not found or there was an error. Otherwise it returns
14460 * the hidden state of the package for the given user.
14463 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14464 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14465 final int callingUid = Binder.getCallingUid();
14466 enforceCrossUserPermission(callingUid, userId,
14467 true /* requireFullPermission */, false /* checkShell */,
14468 "getApplicationHidden for user " + userId);
14470 long callingId = Binder.clearCallingIdentity();
14473 synchronized (mPackages) {
14474 ps = mSettings.mPackages.get(packageName);
14478 if (filterAppAccessLPr(ps, callingUid, userId)) {
14481 return ps.getHidden(userId);
14484 Binder.restoreCallingIdentity(callingId);
14492 public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14493 int installReason) {
14494 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14496 PackageSetting pkgSetting;
14497 final int callingUid = Binder.getCallingUid();
14498 enforceCrossUserPermission(callingUid, userId,
14499 true /* requireFullPermission */, true /* checkShell */,
14500 "installExistingPackage for user " + userId);
14501 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14502 return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14505 long callingId = Binder.clearCallingIdentity();
14507 boolean installed = false;
14508 final boolean instantApp =
14509 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14510 final boolean fullApp =
14511 (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14514 synchronized (mPackages) {
14515 pkgSetting = mSettings.mPackages.get(packageName);
14516 if (pkgSetting == null) {
14517 return PackageManager.INSTALL_FAILED_INVALID_URI;
14519 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14520 // only allow the existing package to be used if it's installed as a full
14521 // application for at least one user
14522 boolean installAllowed = false;
14523 for (int checkUserId : sUserManager.getUserIds()) {
14524 installAllowed = !pkgSetting.getInstantApp(checkUserId);
14525 if (installAllowed) {
14529 if (!installAllowed) {
14530 return PackageManager.INSTALL_FAILED_INVALID_URI;
14533 if (!pkgSetting.getInstalled(userId)) {
14534 pkgSetting.setInstalled(true, userId);
14535 pkgSetting.setHidden(false, userId);
14536 pkgSetting.setInstallReason(installReason, userId);
14537 mSettings.writePackageRestrictionsLPr(userId);
14538 mSettings.writeKernelMappingLPr(pkgSetting);
14540 } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14541 // upgrade app from instant to full; we don't allow app downgrade
14544 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14548 if (pkgSetting.pkg != null) {
14549 synchronized (mInstallLock) {
14550 // We don't need to freeze for a brand new install
14551 prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14554 sendPackageAddedForUser(packageName, pkgSetting, userId);
14555 synchronized (mPackages) {
14556 updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14560 Binder.restoreCallingIdentity(callingId);
14563 return PackageManager.INSTALL_SUCCEEDED;
14566 void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14567 boolean instantApp, boolean fullApp) {
14568 // no state specified; do nothing
14569 if (!instantApp && !fullApp) {
14572 if (userId != UserHandle.USER_ALL) {
14573 if (instantApp && !pkgSetting.getInstantApp(userId)) {
14574 pkgSetting.setInstantApp(true /*instantApp*/, userId);
14575 } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14576 pkgSetting.setInstantApp(false /*instantApp*/, userId);
14579 for (int currentUserId : sUserManager.getUserIds()) {
14580 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14581 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14582 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14583 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14589 boolean isUserRestricted(int userId, String restrictionKey) {
14590 Bundle restrictions = sUserManager.getUserRestrictions(userId);
14591 if (restrictions.getBoolean(restrictionKey, false)) {
14592 Log.w(TAG, "User is restricted: " + restrictionKey);
14599 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14601 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14602 final int callingUid = Binder.getCallingUid();
14603 enforceCrossUserPermission(callingUid, userId,
14604 true /* requireFullPermission */, true /* checkShell */,
14605 "setPackagesSuspended for user " + userId);
14607 if (ArrayUtils.isEmpty(packageNames)) {
14608 return packageNames;
14611 // List of package names for whom the suspended state has changed.
14612 List<String> changedPackages = new ArrayList<>(packageNames.length);
14613 // List of package names for whom the suspended state is not set as requested in this
14615 List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14616 long callingId = Binder.clearCallingIdentity();
14618 for (int i = 0; i < packageNames.length; i++) {
14619 String packageName = packageNames[i];
14620 boolean changed = false;
14622 synchronized (mPackages) {
14623 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14624 if (pkgSetting == null
14625 || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14626 Slog.w(TAG, "Could not find package setting for package \"" + packageName
14627 + "\". Skipping suspending/un-suspending.");
14628 unactionedPackages.add(packageName);
14631 appId = pkgSetting.appId;
14632 if (pkgSetting.getSuspended(userId) != suspended) {
14633 if (!canSuspendPackageForUserLocked(packageName, userId)) {
14634 unactionedPackages.add(packageName);
14637 pkgSetting.setSuspended(suspended, userId);
14638 mSettings.writePackageRestrictionsLPr(userId);
14640 changedPackages.add(packageName);
14644 if (changed && suspended) {
14645 killApplication(packageName, UserHandle.getUid(userId, appId),
14646 "suspending package");
14650 Binder.restoreCallingIdentity(callingId);
14653 if (!changedPackages.isEmpty()) {
14654 sendPackagesSuspendedForUser(changedPackages.toArray(
14655 new String[changedPackages.size()]), userId, suspended);
14658 return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14662 public boolean isPackageSuspendedForUser(String packageName, int userId) {
14663 final int callingUid = Binder.getCallingUid();
14664 enforceCrossUserPermission(callingUid, userId,
14665 true /* requireFullPermission */, false /* checkShell */,
14666 "isPackageSuspendedForUser for user " + userId);
14667 synchronized (mPackages) {
14668 final PackageSetting ps = mSettings.mPackages.get(packageName);
14669 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14670 throw new IllegalArgumentException("Unknown target package: " + packageName);
14672 return ps.getSuspended(userId);
14676 private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14677 if (isPackageDeviceAdmin(packageName, userId)) {
14678 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14679 + "\": has an active device admin");
14683 String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14684 if (packageName.equals(activeLauncherPackageName)) {
14685 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14686 + "\": contains the active launcher");
14690 if (packageName.equals(mRequiredInstallerPackage)) {
14691 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14692 + "\": required for package installation");
14696 if (packageName.equals(mRequiredUninstallerPackage)) {
14697 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14698 + "\": required for package uninstallation");
14702 if (packageName.equals(mRequiredVerifierPackage)) {
14703 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14704 + "\": required for package verification");
14708 if (packageName.equals(getDefaultDialerPackageName(userId))) {
14709 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14710 + "\": is the default dialer");
14714 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14715 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14716 + "\": protected package");
14720 // Cannot suspend static shared libs as they are considered
14721 // a part of the using app (emulating static linking). Also
14722 // static libs are installed always on internal storage.
14723 PackageParser.Package pkg = mPackages.get(packageName);
14724 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14725 Slog.w(TAG, "Cannot suspend package: " + packageName
14726 + " providing static shared library: "
14727 + pkg.staticSharedLibName);
14734 private String getActiveLauncherPackageName(int userId) {
14735 Intent intent = new Intent(Intent.ACTION_MAIN);
14736 intent.addCategory(Intent.CATEGORY_HOME);
14737 ResolveInfo resolveInfo = resolveIntent(
14739 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14740 PackageManager.MATCH_DEFAULT_ONLY,
14743 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14746 private String getDefaultDialerPackageName(int userId) {
14747 synchronized (mPackages) {
14748 return mSettings.getDefaultDialerPackageNameLPw(userId);
14753 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14754 mContext.enforceCallingOrSelfPermission(
14755 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14756 "Only package verification agents can verify applications");
14758 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14759 final PackageVerificationResponse response = new PackageVerificationResponse(
14760 verificationCode, Binder.getCallingUid());
14762 msg.obj = response;
14763 mHandler.sendMessage(msg);
14767 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14768 long millisecondsToDelay) {
14769 mContext.enforceCallingOrSelfPermission(
14770 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14771 "Only package verification agents can extend verification timeouts");
14773 final PackageVerificationState state = mPendingVerification.get(id);
14774 final PackageVerificationResponse response = new PackageVerificationResponse(
14775 verificationCodeAtTimeout, Binder.getCallingUid());
14777 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14778 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14780 if (millisecondsToDelay < 0) {
14781 millisecondsToDelay = 0;
14783 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14784 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14785 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14788 if ((state != null) && !state.timeoutExtended()) {
14789 state.extendTimeout();
14791 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14793 msg.obj = response;
14794 mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14798 private void broadcastPackageVerified(int verificationId, Uri packageUri,
14799 int verificationCode, UserHandle user) {
14800 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14801 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14802 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14803 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14804 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14806 mContext.sendBroadcastAsUser(intent, user,
14807 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14810 private ComponentName matchComponentForVerifier(String packageName,
14811 List<ResolveInfo> receivers) {
14812 ActivityInfo targetReceiver = null;
14814 final int NR = receivers.size();
14815 for (int i = 0; i < NR; i++) {
14816 final ResolveInfo info = receivers.get(i);
14817 if (info.activityInfo == null) {
14821 if (packageName.equals(info.activityInfo.packageName)) {
14822 targetReceiver = info.activityInfo;
14827 if (targetReceiver == null) {
14831 return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14834 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14835 List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14836 if (pkgInfo.verifiers.length == 0) {
14840 final int N = pkgInfo.verifiers.length;
14841 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14842 for (int i = 0; i < N; i++) {
14843 final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14845 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14847 if (comp == null) {
14851 final int verifierUid = getUidForVerifier(verifierInfo);
14852 if (verifierUid == -1) {
14856 if (DEBUG_VERIFY) {
14857 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14858 + " with the correct signature");
14860 sufficientVerifiers.add(comp);
14861 verificationState.addSufficientVerifier(verifierUid);
14864 return sufficientVerifiers;
14867 private int getUidForVerifier(VerifierInfo verifierInfo) {
14868 synchronized (mPackages) {
14869 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14872 } else if (pkg.mSignatures.length != 1) {
14873 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14874 + " has more than one signature; ignoring");
14879 * If the public key of the package's signature does not match
14880 * our expected public key, then this is a different package and
14884 final byte[] expectedPublicKey;
14886 final Signature verifierSig = pkg.mSignatures[0];
14887 final PublicKey publicKey = verifierSig.getPublicKey();
14888 expectedPublicKey = publicKey.getEncoded();
14889 } catch (CertificateException e) {
14893 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14895 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14896 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14897 + " does not have the expected public key; ignoring");
14901 return pkg.applicationInfo.uid;
14906 public void finishPackageInstall(int token, boolean didLaunch) {
14907 enforceSystemOrRoot("Only the system is allowed to finish installs");
14909 if (DEBUG_INSTALL) {
14910 Slog.v(TAG, "BM finishing package install for " + token);
14912 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14914 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14915 mHandler.sendMessage(msg);
14919 * Get the verification agent timeout. Used for both the APK verifier and the
14920 * intent filter verifier.
14922 * @return verification timeout in milliseconds
14924 private long getVerificationTimeout() {
14925 return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14926 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14927 DEFAULT_VERIFICATION_TIMEOUT);
14931 * Get the default verification agent response code.
14933 * @return default verification response code
14935 private int getDefaultVerificationResponse(UserHandle user) {
14936 if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14937 return PackageManager.VERIFICATION_REJECT;
14939 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14940 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14941 DEFAULT_VERIFICATION_RESPONSE);
14945 * Check whether or not package verification has been enabled.
14947 * @return true if verification should be performed
14949 private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14950 if (!DEFAULT_VERIFY_ENABLE) {
14954 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14956 // Check if installing from ADB
14957 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14958 // Do not run verification in a test harness environment
14959 if (ActivityManager.isRunningInTestHarness()) {
14962 if (ensureVerifyAppsEnabled) {
14965 // Check if the developer does not want package verification for ADB installs
14966 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14967 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14971 // only when not installed from ADB, skip verification for instant apps when
14972 // the installer and verifier are the same.
14973 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14974 if (mInstantAppInstallerActivity != null
14975 && mInstantAppInstallerActivity.packageName.equals(
14976 mRequiredVerifierPackage)) {
14978 mContext.getSystemService(AppOpsManager.class)
14979 .checkPackage(installerUid, mRequiredVerifierPackage);
14980 if (DEBUG_VERIFY) {
14981 Slog.i(TAG, "disable verification for instant app");
14984 } catch (SecurityException ignore) { }
14989 if (ensureVerifyAppsEnabled) {
14993 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14994 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14998 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14999 throws RemoteException {
15000 mContext.enforceCallingOrSelfPermission(
15001 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15002 "Only intentfilter verification agents can verify applications");
15004 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15005 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15006 Binder.getCallingUid(), verificationCode, failedDomains);
15008 msg.obj = response;
15009 mHandler.sendMessage(msg);
15013 public int getIntentVerificationStatus(String packageName, int userId) {
15014 final int callingUid = Binder.getCallingUid();
15015 if (getInstantAppPackageName(callingUid) != null) {
15016 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15018 synchronized (mPackages) {
15019 final PackageSetting ps = mSettings.mPackages.get(packageName);
15021 || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15022 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15024 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15029 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15030 mContext.enforceCallingOrSelfPermission(
15031 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15033 boolean result = false;
15034 synchronized (mPackages) {
15035 final PackageSetting ps = mSettings.mPackages.get(packageName);
15036 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15039 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15042 scheduleWritePackageRestrictionsLocked(userId);
15048 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15049 String packageName) {
15050 final int callingUid = Binder.getCallingUid();
15051 if (getInstantAppPackageName(callingUid) != null) {
15052 return ParceledListSlice.emptyList();
15054 synchronized (mPackages) {
15055 final PackageSetting ps = mSettings.mPackages.get(packageName);
15056 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15057 return ParceledListSlice.emptyList();
15059 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15064 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15065 if (TextUtils.isEmpty(packageName)) {
15066 return ParceledListSlice.emptyList();
15068 final int callingUid = Binder.getCallingUid();
15069 final int callingUserId = UserHandle.getUserId(callingUid);
15070 synchronized (mPackages) {
15071 PackageParser.Package pkg = mPackages.get(packageName);
15072 if (pkg == null || pkg.activities == null) {
15073 return ParceledListSlice.emptyList();
15075 if (pkg.mExtras == null) {
15076 return ParceledListSlice.emptyList();
15078 final PackageSetting ps = (PackageSetting) pkg.mExtras;
15079 if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15080 return ParceledListSlice.emptyList();
15082 final int count = pkg.activities.size();
15083 ArrayList<IntentFilter> result = new ArrayList<>();
15084 for (int n=0; n<count; n++) {
15085 PackageParser.Activity activity = pkg.activities.get(n);
15086 if (activity.intents != null && activity.intents.size() > 0) {
15087 result.addAll(activity.intents);
15090 return new ParceledListSlice<>(result);
15095 public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15096 mContext.enforceCallingOrSelfPermission(
15097 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15099 synchronized (mPackages) {
15100 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15101 if (packageName != null) {
15102 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15103 packageName, userId);
15110 public String getDefaultBrowserPackageName(int userId) {
15111 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15114 synchronized (mPackages) {
15115 return mSettings.getDefaultBrowserPackageNameLPw(userId);
15120 * Get the "allow unknown sources" setting.
15122 * @return the current "allow unknown sources" setting
15124 private int getUnknownSourcesSettings() {
15125 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15126 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15131 public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15132 final int callingUid = Binder.getCallingUid();
15133 if (getInstantAppPackageName(callingUid) != null) {
15137 synchronized (mPackages) {
15138 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15139 if (targetPackageSetting == null
15140 || filterAppAccessLPr(
15141 targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15142 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15145 PackageSetting installerPackageSetting;
15146 if (installerPackageName != null) {
15147 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15148 if (installerPackageSetting == null) {
15149 throw new IllegalArgumentException("Unknown installer package: "
15150 + installerPackageName);
15153 installerPackageSetting = null;
15156 Signature[] callerSignature;
15157 Object obj = mSettings.getUserIdLPr(callingUid);
15159 if (obj instanceof SharedUserSetting) {
15160 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15161 } else if (obj instanceof PackageSetting) {
15162 callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15164 throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15167 throw new SecurityException("Unknown calling UID: " + callingUid);
15170 // Verify: can't set installerPackageName to a package that is
15171 // not signed with the same cert as the caller.
15172 if (installerPackageSetting != null) {
15173 if (compareSignatures(callerSignature,
15174 installerPackageSetting.signatures.mSignatures)
15175 != PackageManager.SIGNATURE_MATCH) {
15176 throw new SecurityException(
15177 "Caller does not have same cert as new installer package "
15178 + installerPackageName);
15182 // Verify: if target already has an installer package, it must
15183 // be signed with the same cert as the caller.
15184 if (targetPackageSetting.installerPackageName != null) {
15185 PackageSetting setting = mSettings.mPackages.get(
15186 targetPackageSetting.installerPackageName);
15187 // If the currently set package isn't valid, then it's always
15188 // okay to change it.
15189 if (setting != null) {
15190 if (compareSignatures(callerSignature,
15191 setting.signatures.mSignatures)
15192 != PackageManager.SIGNATURE_MATCH) {
15193 throw new SecurityException(
15194 "Caller does not have same cert as old installer package "
15195 + targetPackageSetting.installerPackageName);
15201 targetPackageSetting.installerPackageName = installerPackageName;
15202 if (installerPackageName != null) {
15203 mSettings.mInstallerPackages.add(installerPackageName);
15205 scheduleWriteSettingsLocked();
15210 public void setApplicationCategoryHint(String packageName, int categoryHint,
15211 String callerPackageName) {
15212 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15213 throw new SecurityException("Instant applications don't have access to this method");
15215 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15216 callerPackageName);
15217 synchronized (mPackages) {
15218 PackageSetting ps = mSettings.mPackages.get(packageName);
15220 throw new IllegalArgumentException("Unknown target package " + packageName);
15222 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15223 throw new IllegalArgumentException("Unknown target package " + packageName);
15225 if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15226 throw new IllegalArgumentException("Calling package " + callerPackageName
15227 + " is not installer for " + packageName);
15230 if (ps.categoryHint != categoryHint) {
15231 ps.categoryHint = categoryHint;
15232 scheduleWriteSettingsLocked();
15237 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15238 // Queue up an async operation since the package installation may take a little while.
15239 mHandler.post(new Runnable() {
15240 public void run() {
15241 mHandler.removeCallbacks(this);
15242 // Result object to be returned
15243 PackageInstalledInfo res = new PackageInstalledInfo();
15244 res.setReturnCode(currentStatus);
15247 res.removedInfo = null;
15248 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15249 args.doPreInstall(res.returnCode);
15250 synchronized (mInstallLock) {
15251 installPackageTracedLI(args, res);
15253 args.doPostInstall(res.returnCode, res.uid);
15256 // A restore should be performed at this point if (a) the install
15257 // succeeded, (b) the operation is not an update, and (c) the new
15258 // package has not opted out of backup participation.
15259 final boolean update = res.removedInfo != null
15260 && res.removedInfo.removedPackage != null;
15261 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15262 boolean doRestore = !update
15263 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15265 // Set up the post-install work request bookkeeping. This will be used
15266 // and cleaned up by the post-install event handling regardless of whether
15267 // there's a restore pass performed. Token values are >= 1.
15269 if (mNextInstallToken < 0) mNextInstallToken = 1;
15270 token = mNextInstallToken++;
15272 PostInstallData data = new PostInstallData(args, res);
15273 mRunningInstalls.put(token, data);
15274 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15276 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15277 // Pass responsibility to the Backup Manager. It will perform a
15278 // restore if appropriate, then pass responsibility back to the
15279 // Package Manager to run the post-install observer callbacks
15281 IBackupManager bm = IBackupManager.Stub.asInterface(
15282 ServiceManager.getService(Context.BACKUP_SERVICE));
15284 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15285 + " to BM for possible restore");
15286 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15288 // TODO: http://b/22388012
15289 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15290 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15294 } catch (RemoteException e) {
15295 // can't happen; the backup manager is local
15296 } catch (Exception e) {
15297 Slog.e(TAG, "Exception trying to enqueue restore", e);
15301 Slog.e(TAG, "Backup Manager not found!");
15307 // No restore possible, or the Backup Manager was mysteriously not
15308 // available -- just fire the post-install work request directly.
15309 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15311 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15313 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15314 mHandler.sendMessage(msg);
15321 * Callback from PackageSettings whenever an app is first transitioned out of the
15322 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if
15323 * the app was "launched" for a restoreAtInstall operation. Therefore we check
15324 * here whether the app is the target of an ongoing install, and only send the
15325 * broadcast immediately if it is not in that state. If it *is* undergoing a restore,
15326 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15329 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15330 // Serialize this with the rest of the install-process message chain. In the
15331 // restore-at-install case, this Runnable will necessarily run before the
15332 // POST_INSTALL message is processed, so the contents of mRunningInstalls
15333 // are coherent. In the non-restore case, the app has already completed install
15334 // and been launched through some other means, so it is not in a problematic
15335 // state for observers to see the FIRST_LAUNCH signal.
15336 mHandler.post(new Runnable() {
15338 public void run() {
15339 for (int i = 0; i < mRunningInstalls.size(); i++) {
15340 final PostInstallData data = mRunningInstalls.valueAt(i);
15341 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15344 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15345 // right package; but is it for the right user?
15346 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15347 if (userId == data.res.newUsers[uIndex]) {
15348 if (DEBUG_BACKUP) {
15349 Slog.i(TAG, "Package " + pkgName
15350 + " being restored so deferring FIRST_LAUNCH");
15357 // didn't find it, so not being restored
15358 if (DEBUG_BACKUP) {
15359 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15361 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15366 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15367 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15368 installerPkg, null, userIds);
15371 private abstract class HandlerParams {
15372 private static final int MAX_RETRIES = 4;
15375 * Number of times startCopy() has been attempted and had a non-fatal
15378 private int mRetries = 0;
15380 /** User handle for the user requesting the information or installation. */
15381 private final UserHandle mUser;
15382 String traceMethod;
15385 HandlerParams(UserHandle user) {
15389 UserHandle getUser() {
15393 HandlerParams setTraceMethod(String traceMethod) {
15394 this.traceMethod = traceMethod;
15398 HandlerParams setTraceCookie(int traceCookie) {
15399 this.traceCookie = traceCookie;
15403 final boolean startCopy() {
15406 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15408 if (++mRetries > MAX_RETRIES) {
15409 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15410 mHandler.sendEmptyMessage(MCS_GIVE_UP);
15411 handleServiceError();
15417 } catch (RemoteException e) {
15418 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15419 mHandler.sendEmptyMessage(MCS_RECONNECT);
15422 handleReturnCode();
15426 final void serviceError() {
15427 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15428 handleServiceError();
15429 handleReturnCode();
15432 abstract void handleStartCopy() throws RemoteException;
15433 abstract void handleServiceError();
15434 abstract void handleReturnCode();
15437 private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15438 for (File path : paths) {
15440 mcs.clearDirectory(path.getAbsolutePath());
15441 } catch (RemoteException e) {
15446 static class OriginInfo {
15448 * Location where install is coming from, before it has been
15449 * copied/renamed into place. This could be a single monolithic APK
15450 * file, or a cluster directory. This location may be untrusted.
15456 * Flag indicating that {@link #file} or {@link #cid} has already been
15457 * staged, meaning downstream users don't need to defensively copy the
15460 final boolean staged;
15463 * Flag indicating that {@link #file} or {@link #cid} is an already
15464 * installed app that is being moved.
15466 final boolean existing;
15468 final String resolvedPath;
15469 final File resolvedFile;
15471 static OriginInfo fromNothing() {
15472 return new OriginInfo(null, null, false, false);
15475 static OriginInfo fromUntrustedFile(File file) {
15476 return new OriginInfo(file, null, false, false);
15479 static OriginInfo fromExistingFile(File file) {
15480 return new OriginInfo(file, null, false, true);
15483 static OriginInfo fromStagedFile(File file) {
15484 return new OriginInfo(file, null, true, false);
15487 static OriginInfo fromStagedContainer(String cid) {
15488 return new OriginInfo(null, cid, true, false);
15491 private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15494 this.staged = staged;
15495 this.existing = existing;
15498 resolvedPath = PackageHelper.getSdDir(cid);
15499 resolvedFile = new File(resolvedPath);
15500 } else if (file != null) {
15501 resolvedPath = file.getAbsolutePath();
15502 resolvedFile = file;
15504 resolvedPath = null;
15505 resolvedFile = null;
15510 static class MoveInfo {
15512 final String fromUuid;
15513 final String toUuid;
15514 final String packageName;
15515 final String dataAppName;
15517 final String seinfo;
15518 final int targetSdkVersion;
15520 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15521 String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15522 this.moveId = moveId;
15523 this.fromUuid = fromUuid;
15524 this.toUuid = toUuid;
15525 this.packageName = packageName;
15526 this.dataAppName = dataAppName;
15527 this.appId = appId;
15528 this.seinfo = seinfo;
15529 this.targetSdkVersion = targetSdkVersion;
15533 static class VerificationInfo {
15534 /** A constant used to indicate that a uid value is not present. */
15535 public static final int NO_UID = -1;
15537 /** URI referencing where the package was downloaded from. */
15538 final Uri originatingUri;
15540 /** HTTP referrer URI associated with the originatingURI. */
15541 final Uri referrer;
15543 /** UID of the application that the install request originated from. */
15544 final int originatingUid;
15546 /** UID of application requesting the install */
15547 final int installerUid;
15549 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15550 this.originatingUri = originatingUri;
15551 this.referrer = referrer;
15552 this.originatingUid = originatingUid;
15553 this.installerUid = installerUid;
15557 class InstallParams extends HandlerParams {
15558 final OriginInfo origin;
15559 final MoveInfo move;
15560 final IPackageInstallObserver2 observer;
15562 final String installerPackageName;
15563 final String volumeUuid;
15564 private InstallArgs mArgs;
15566 final String packageAbiOverride;
15567 final String[] grantedRuntimePermissions;
15568 final VerificationInfo verificationInfo;
15569 final Certificate[][] certificates;
15570 final int installReason;
15572 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15573 int installFlags, String installerPackageName, String volumeUuid,
15574 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15575 String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15577 this.origin = origin;
15579 this.observer = observer;
15580 this.installFlags = installFlags;
15581 this.installerPackageName = installerPackageName;
15582 this.volumeUuid = volumeUuid;
15583 this.verificationInfo = verificationInfo;
15584 this.packageAbiOverride = packageAbiOverride;
15585 this.grantedRuntimePermissions = grantedPermissions;
15586 this.certificates = certificates;
15587 this.installReason = installReason;
15591 public String toString() {
15592 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15593 + " file=" + origin.file + " cid=" + origin.cid + "}";
15596 private int installLocationPolicy(PackageInfoLite pkgLite) {
15597 String packageName = pkgLite.packageName;
15598 int installLocation = pkgLite.installLocation;
15599 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15601 synchronized (mPackages) {
15602 // Currently installed package which the new package is attempting to replace or
15603 // null if no such package is installed.
15604 PackageParser.Package installedPkg = mPackages.get(packageName);
15605 // Package which currently owns the data which the new package will own if installed.
15606 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15607 // will be null whereas dataOwnerPkg will contain information about the package
15608 // which was uninstalled while keeping its data.
15609 PackageParser.Package dataOwnerPkg = installedPkg;
15610 if (dataOwnerPkg == null) {
15611 PackageSetting ps = mSettings.mPackages.get(packageName);
15613 dataOwnerPkg = ps.pkg;
15617 if (dataOwnerPkg != null) {
15618 // If installed, the package will get access to data left on the device by its
15619 // predecessor. As a security measure, this is permited only if this is not a
15620 // version downgrade or if the predecessor package is marked as debuggable and
15621 // a downgrade is explicitly requested.
15623 // On debuggable platform builds, downgrades are permitted even for
15624 // non-debuggable packages to make testing easier. Debuggable platform builds do
15625 // not offer security guarantees and thus it's OK to disable some security
15626 // mechanisms to make debugging/testing easier on those builds. However, even on
15627 // debuggable builds downgrades of packages are permitted only if requested via
15628 // installFlags. This is because we aim to keep the behavior of debuggable
15629 // platform builds as close as possible to the behavior of non-debuggable
15630 // platform builds.
15631 final boolean downgradeRequested =
15632 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15633 final boolean packageDebuggable =
15634 (dataOwnerPkg.applicationInfo.flags
15635 & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15636 final boolean downgradePermitted =
15637 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15638 if (!downgradePermitted) {
15640 checkDowngrade(dataOwnerPkg, pkgLite);
15641 } catch (PackageManagerException e) {
15642 Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15643 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15648 if (installedPkg != null) {
15649 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15650 // Check for updated system application.
15651 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15653 Slog.w(TAG, "Cannot install update to system app on sdcard");
15654 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15656 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15659 // Install flag overrides everything.
15660 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15662 // If current upgrade specifies particular preference
15663 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15664 // Application explicitly specified internal.
15665 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15666 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15667 // App explictly prefers external. Let policy decide
15669 // Prefer previous location
15670 if (isExternal(installedPkg)) {
15671 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15673 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15677 // Invalid install. Return error code
15678 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15682 // All the special cases have been taken care of.
15683 // Return result based on recommended install location.
15685 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15687 return pkgLite.recommendedInstallLocation;
15691 * Invoke remote method to get package information and install
15692 * location values. Override install location based on default
15693 * policy if needed and then create install arguments based
15694 * on the install location.
15696 public void handleStartCopy() throws RemoteException {
15697 int ret = PackageManager.INSTALL_SUCCEEDED;
15699 // If we're already staged, we've firmly committed to an install location
15700 if (origin.staged) {
15701 if (origin.file != null) {
15702 installFlags |= PackageManager.INSTALL_INTERNAL;
15703 installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15704 } else if (origin.cid != null) {
15705 installFlags |= PackageManager.INSTALL_EXTERNAL;
15706 installFlags &= ~PackageManager.INSTALL_INTERNAL;
15708 throw new IllegalStateException("Invalid stage location");
15712 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15713 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15714 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15715 PackageInfoLite pkgLite = null;
15717 if (onInt && onSd) {
15718 // Check if both bits are set.
15719 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15720 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15721 } else if (onSd && ephemeral) {
15722 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external");
15723 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15725 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15726 packageAbiOverride);
15728 if (DEBUG_EPHEMERAL && ephemeral) {
15729 Slog.v(TAG, "pkgLite for install: " + pkgLite);
15733 * If we have too little free space, try to free cache
15734 * before giving up.
15736 if (!origin.staged && pkgLite.recommendedInstallLocation
15737 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15738 // TODO: focus freeing disk space on the target device
15739 final StorageManager storage = StorageManager.from(mContext);
15740 final long lowThreshold = storage.getStorageLowBytes(
15741 Environment.getDataDirectory());
15743 final long sizeBytes = mContainerService.calculateInstalledSize(
15744 origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15747 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15748 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15749 installFlags, packageAbiOverride);
15750 } catch (InstallerException e) {
15751 Slog.w(TAG, "Failed to free cache", e);
15755 * The cache free must have deleted the file we
15756 * downloaded to install.
15758 * TODO: fix the "freeCache" call to not delete
15759 * the file we care about.
15761 if (pkgLite.recommendedInstallLocation
15762 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15763 pkgLite.recommendedInstallLocation
15764 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15769 if (ret == PackageManager.INSTALL_SUCCEEDED) {
15770 int loc = pkgLite.recommendedInstallLocation;
15771 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15772 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15773 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15774 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15775 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15776 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15777 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15778 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15779 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15780 ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15781 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15782 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15784 // Override with defaults if needed.
15785 loc = installLocationPolicy(pkgLite);
15786 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15787 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15788 } else if (!onSd && !onInt) {
15789 // Override install location with flags
15790 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15791 // Set the flag to install on external media.
15792 installFlags |= PackageManager.INSTALL_EXTERNAL;
15793 installFlags &= ~PackageManager.INSTALL_INTERNAL;
15794 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15795 if (DEBUG_EPHEMERAL) {
15796 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15798 installFlags |= PackageManager.INSTALL_INSTANT_APP;
15799 installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15800 |PackageManager.INSTALL_INTERNAL);
15802 // Make sure the flag for installing on external
15804 installFlags |= PackageManager.INSTALL_INTERNAL;
15805 installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15811 final InstallArgs args = createInstallArgs(this);
15814 if (ret == PackageManager.INSTALL_SUCCEEDED) {
15815 // TODO: http://b/22976637
15816 // Apps installed for "all" users use the device owner to verify the app
15817 UserHandle verifierUser = getUser();
15818 if (verifierUser == UserHandle.ALL) {
15819 verifierUser = UserHandle.SYSTEM;
15823 * Determine if we have any installed package verifiers. If we
15824 * do, then we'll defer to them to verify the packages.
15826 final int requiredUid = mRequiredVerifierPackage == null ? -1
15827 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15828 verifierUser.getIdentifier());
15829 final int installerUid =
15830 verificationInfo == null ? -1 : verificationInfo.installerUid;
15831 if (!origin.existing && requiredUid != -1
15832 && isVerificationEnabled(
15833 verifierUser.getIdentifier(), installFlags, installerUid)) {
15834 final Intent verification = new Intent(
15835 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15836 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15837 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15838 PACKAGE_MIME_TYPE);
15839 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15841 // Query all live verifiers based on current user state
15842 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15843 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15845 if (DEBUG_VERIFY) {
15846 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15847 + verification.toString() + " with " + pkgLite.verifiers.length
15848 + " optional verifiers");
15851 final int verificationId = mPendingVerificationToken++;
15853 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15855 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15856 installerPackageName);
15858 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15861 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15862 pkgLite.packageName);
15864 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15865 pkgLite.versionCode);
15867 if (verificationInfo != null) {
15868 if (verificationInfo.originatingUri != null) {
15869 verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15870 verificationInfo.originatingUri);
15872 if (verificationInfo.referrer != null) {
15873 verification.putExtra(Intent.EXTRA_REFERRER,
15874 verificationInfo.referrer);
15876 if (verificationInfo.originatingUid >= 0) {
15877 verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15878 verificationInfo.originatingUid);
15880 if (verificationInfo.installerUid >= 0) {
15881 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15882 verificationInfo.installerUid);
15886 final PackageVerificationState verificationState = new PackageVerificationState(
15887 requiredUid, args);
15889 mPendingVerification.append(verificationId, verificationState);
15891 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15892 receivers, verificationState);
15894 DeviceIdleController.LocalService idleController = getDeviceIdleController();
15895 final long idleDuration = getVerificationTimeout();
15898 * If any sufficient verifiers were listed in the package
15899 * manifest, attempt to ask them.
15901 if (sufficientVerifiers != null) {
15902 final int N = sufficientVerifiers.size();
15904 Slog.i(TAG, "Additional verifiers required, but none installed.");
15905 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15907 for (int i = 0; i < N; i++) {
15908 final ComponentName verifierComponent = sufficientVerifiers.get(i);
15909 idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15910 verifierComponent.getPackageName(), idleDuration,
15911 verifierUser.getIdentifier(), false, "package verifier");
15913 final Intent sufficientIntent = new Intent(verification);
15914 sufficientIntent.setComponent(verifierComponent);
15915 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15920 final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15921 mRequiredVerifierPackage, receivers);
15922 if (ret == PackageManager.INSTALL_SUCCEEDED
15923 && mRequiredVerifierPackage != null) {
15924 Trace.asyncTraceBegin(
15925 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15927 * Send the intent to the required verification agent,
15928 * but only start the verification timeout after the
15929 * target BroadcastReceivers have run.
15931 verification.setComponent(requiredVerifierComponent);
15932 idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15933 mRequiredVerifierPackage, idleDuration,
15934 verifierUser.getIdentifier(), false, "package verifier");
15935 mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15936 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15937 new BroadcastReceiver() {
15939 public void onReceive(Context context, Intent intent) {
15940 final Message msg = mHandler
15941 .obtainMessage(CHECK_PENDING_VERIFICATION);
15942 msg.arg1 = verificationId;
15943 mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15945 }, null, 0, null, null);
15948 * We don't want the copy to proceed until verification
15949 * succeeds, so null out this field.
15955 * No package verification is enabled, so immediately start
15956 * the remote call to initiate copy using temporary file.
15958 ret = args.copyApk(mContainerService, true);
15966 void handleReturnCode() {
15967 // If mArgs is null, then MCS couldn't be reached. When it
15968 // reconnects, it will try again to install. At that point, this
15970 if (mArgs != null) {
15971 processPendingInstall(mArgs, mRet);
15976 void handleServiceError() {
15977 mArgs = createInstallArgs(this);
15978 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15981 public boolean isForwardLocked() {
15982 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15987 * Used during creation of InstallArgs
15989 * @param installFlags package installation flags
15990 * @return true if should be installed on external storage
15992 private static boolean installOnExternalAsec(int installFlags) {
15993 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
15996 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16003 * Used during creation of InstallArgs
16005 * @param installFlags package installation flags
16006 * @return true if should be installed as forward locked
16008 private static boolean installForwardLocked(int installFlags) {
16009 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16012 private InstallArgs createInstallArgs(InstallParams params) {
16013 if (params.move != null) {
16014 return new MoveInstallArgs(params);
16015 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16016 return new AsecInstallArgs(params);
16018 return new FileInstallArgs(params);
16023 * Create args that describe an existing installed package. Typically used
16024 * when cleaning up old installs, or used as a move source.
16026 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16027 String resourcePath, String[] instructionSets) {
16028 final boolean isInAsec;
16029 if (installOnExternalAsec(installFlags)) {
16030 /* Apps on SD card are always in ASEC containers. */
16032 } else if (installForwardLocked(installFlags)
16033 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16035 * Forward-locked apps are only in ASEC containers if they're the
16044 return new AsecInstallArgs(codePath, instructionSets,
16045 installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16047 return new FileInstallArgs(codePath, resourcePath, instructionSets);
16051 static abstract class InstallArgs {
16052 /** @see InstallParams#origin */
16053 final OriginInfo origin;
16054 /** @see InstallParams#move */
16055 final MoveInfo move;
16057 final IPackageInstallObserver2 observer;
16058 // Always refers to PackageManager flags only
16059 final int installFlags;
16060 final String installerPackageName;
16061 final String volumeUuid;
16062 final UserHandle user;
16063 final String abiOverride;
16064 final String[] installGrantPermissions;
16065 /** If non-null, drop an async trace when the install completes */
16066 final String traceMethod;
16067 final int traceCookie;
16068 final Certificate[][] certificates;
16069 final int installReason;
16071 // The list of instruction sets supported by this app. This is currently
16072 // only used during the rmdex() phase to clean up resources. We can get rid of this
16073 // if we move dex files under the common app path.
16074 /* nullable */ String[] instructionSets;
16076 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16077 int installFlags, String installerPackageName, String volumeUuid,
16078 UserHandle user, String[] instructionSets,
16079 String abiOverride, String[] installGrantPermissions,
16080 String traceMethod, int traceCookie, Certificate[][] certificates,
16081 int installReason) {
16082 this.origin = origin;
16084 this.installFlags = installFlags;
16085 this.observer = observer;
16086 this.installerPackageName = installerPackageName;
16087 this.volumeUuid = volumeUuid;
16089 this.instructionSets = instructionSets;
16090 this.abiOverride = abiOverride;
16091 this.installGrantPermissions = installGrantPermissions;
16092 this.traceMethod = traceMethod;
16093 this.traceCookie = traceCookie;
16094 this.certificates = certificates;
16095 this.installReason = installReason;
16098 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16099 abstract int doPreInstall(int status);
16102 * Rename package into final resting place. All paths on the given
16103 * scanned package should be updated to reflect the rename.
16105 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16106 abstract int doPostInstall(int status, int uid);
16108 /** @see PackageSettingBase#codePathString */
16109 abstract String getCodePath();
16110 /** @see PackageSettingBase#resourcePathString */
16111 abstract String getResourcePath();
16113 // Need installer lock especially for dex file removal.
16114 abstract void cleanUpResourcesLI();
16115 abstract boolean doPostDeleteLI(boolean delete);
16118 * Called before the source arguments are copied. This is used mostly
16119 * for MoveParams when it needs to read the source file to put it in the
16123 return PackageManager.INSTALL_SUCCEEDED;
16127 * Called after the source arguments are copied. This is used mostly for
16128 * MoveParams when it needs to read the source file to put it in the
16131 int doPostCopy(int uid) {
16132 return PackageManager.INSTALL_SUCCEEDED;
16135 protected boolean isFwdLocked() {
16136 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16139 protected boolean isExternalAsec() {
16140 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16143 protected boolean isEphemeral() {
16144 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16147 UserHandle getUser() {
16152 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16153 if (!allCodePaths.isEmpty()) {
16154 if (instructionSets == null) {
16155 throw new IllegalStateException("instructionSet == null");
16157 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16158 for (String codePath : allCodePaths) {
16159 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16161 mInstaller.rmdex(codePath, dexCodeInstructionSet);
16162 } catch (InstallerException ignored) {
16170 * Logic to handle installation of non-ASEC applications, including copying
16171 * and renaming logic.
16173 class FileInstallArgs extends InstallArgs {
16174 private File codeFile;
16175 private File resourceFile;
16177 // Example topology:
16178 // /data/app/com.example/base.apk
16179 // /data/app/com.example/split_foo.apk
16180 // /data/app/com.example/lib/arm/libfoo.so
16181 // /data/app/com.example/lib/arm64/libfoo.so
16182 // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16185 FileInstallArgs(InstallParams params) {
16186 super(params.origin, params.move, params.observer, params.installFlags,
16187 params.installerPackageName, params.volumeUuid,
16188 params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16189 params.grantedRuntimePermissions,
16190 params.traceMethod, params.traceCookie, params.certificates,
16191 params.installReason);
16192 if (isFwdLocked()) {
16193 throw new IllegalArgumentException("Forward locking only supported in ASEC");
16197 /** Existing install */
16198 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16199 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16200 null, null, null, 0, null /*certificates*/,
16201 PackageManager.INSTALL_REASON_UNKNOWN);
16202 this.codeFile = (codePath != null) ? new File(codePath) : null;
16203 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16206 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16207 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16209 return doCopyApk(imcs, temp);
16211 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16215 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16216 if (origin.staged) {
16217 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16218 codeFile = origin.file;
16219 resourceFile = origin.file;
16220 return PackageManager.INSTALL_SUCCEEDED;
16224 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16225 final File tempDir =
16226 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16227 codeFile = tempDir;
16228 resourceFile = tempDir;
16229 } catch (IOException e) {
16230 Slog.w(TAG, "Failed to create copy file: " + e);
16231 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16234 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16236 public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16237 if (!FileUtils.isValidExtFilename(name)) {
16238 throw new IllegalArgumentException("Invalid filename: " + name);
16241 final File file = new File(codeFile, name);
16242 final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16243 O_RDWR | O_CREAT, 0644);
16244 Os.chmod(file.getAbsolutePath(), 0644);
16245 return new ParcelFileDescriptor(fd);
16246 } catch (ErrnoException e) {
16247 throw new RemoteException("Failed to open: " + e.getMessage());
16252 int ret = PackageManager.INSTALL_SUCCEEDED;
16253 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16254 if (ret != PackageManager.INSTALL_SUCCEEDED) {
16255 Slog.e(TAG, "Failed to copy package");
16259 final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16260 NativeLibraryHelper.Handle handle = null;
16262 handle = NativeLibraryHelper.Handle.create(codeFile);
16263 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16265 } catch (IOException e) {
16266 Slog.e(TAG, "Copying native libraries failed", e);
16267 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16269 IoUtils.closeQuietly(handle);
16275 int doPreInstall(int status) {
16276 if (status != PackageManager.INSTALL_SUCCEEDED) {
16282 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16283 if (status != PackageManager.INSTALL_SUCCEEDED) {
16288 final File targetDir = codeFile.getParentFile();
16289 final File beforeCodeFile = codeFile;
16290 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16292 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16294 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16295 } catch (ErrnoException e) {
16296 Slog.w(TAG, "Failed to rename", e);
16300 if (!SELinux.restoreconRecursive(afterCodeFile)) {
16301 Slog.w(TAG, "Failed to restorecon");
16305 // Reflect the rename internally
16306 codeFile = afterCodeFile;
16307 resourceFile = afterCodeFile;
16309 // Reflect the rename in scanned details
16310 pkg.setCodePath(afterCodeFile.getAbsolutePath());
16311 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16312 afterCodeFile, pkg.baseCodePath));
16313 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16314 afterCodeFile, pkg.splitCodePaths));
16316 // Reflect the rename in app info
16317 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16318 pkg.setApplicationInfoCodePath(pkg.codePath);
16319 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16320 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16321 pkg.setApplicationInfoResourcePath(pkg.codePath);
16322 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16323 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16328 int doPostInstall(int status, int uid) {
16329 if (status != PackageManager.INSTALL_SUCCEEDED) {
16336 String getCodePath() {
16337 return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16341 String getResourcePath() {
16342 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16345 private boolean cleanUp() {
16346 if (codeFile == null || !codeFile.exists()) {
16350 removeCodePathLI(codeFile);
16352 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16353 resourceFile.delete();
16359 void cleanUpResourcesLI() {
16360 // Try enumerating all code paths before deleting
16361 List<String> allCodePaths = Collections.EMPTY_LIST;
16362 if (codeFile != null && codeFile.exists()) {
16364 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16365 allCodePaths = pkg.getAllCodePaths();
16366 } catch (PackageParserException e) {
16367 // Ignored; we tried our best
16372 removeDexFiles(allCodePaths, instructionSets);
16375 boolean doPostDeleteLI(boolean delete) {
16376 // XXX err, shouldn't we respect the delete flag?
16377 cleanUpResourcesLI();
16382 private boolean isAsecExternal(String cid) {
16383 final String asecPath = PackageHelper.getSdFilesystem(cid);
16384 return !asecPath.startsWith(mAsecInternalPath);
16387 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16388 PackageManagerException {
16390 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16391 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16392 throw new PackageManagerException(copyRet, message);
16398 * Extract the StorageManagerService "container ID" from the full code path of an
16401 static String cidFromCodePath(String fullCodePath) {
16402 int eidx = fullCodePath.lastIndexOf("/");
16403 String subStr1 = fullCodePath.substring(0, eidx);
16404 int sidx = subStr1.lastIndexOf("/");
16405 return subStr1.substring(sidx+1, eidx);
16409 * Logic to handle installation of ASEC applications, including copying and
16412 class AsecInstallArgs extends InstallArgs {
16413 static final String RES_FILE_NAME = "pkg.apk";
16414 static final String PUBLIC_RES_FILE_NAME = "res.zip";
16417 String packagePath;
16418 String resourcePath;
16421 AsecInstallArgs(InstallParams params) {
16422 super(params.origin, params.move, params.observer, params.installFlags,
16423 params.installerPackageName, params.volumeUuid,
16424 params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16425 params.grantedRuntimePermissions,
16426 params.traceMethod, params.traceCookie, params.certificates,
16427 params.installReason);
16430 /** Existing install */
16431 AsecInstallArgs(String fullCodePath, String[] instructionSets,
16432 boolean isExternal, boolean isForwardLocked) {
16433 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16434 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16435 instructionSets, null, null, null, 0, null /*certificates*/,
16436 PackageManager.INSTALL_REASON_UNKNOWN);
16437 // Hackily pretend we're still looking at a full code path
16438 if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16439 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16442 // Extract cid from fullCodePath
16443 int eidx = fullCodePath.lastIndexOf("/");
16444 String subStr1 = fullCodePath.substring(0, eidx);
16445 int sidx = subStr1.lastIndexOf("/");
16446 cid = subStr1.substring(sidx+1, eidx);
16447 setMountPath(subStr1);
16450 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16451 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16452 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16453 instructionSets, null, null, null, 0, null /*certificates*/,
16454 PackageManager.INSTALL_REASON_UNKNOWN);
16456 setMountPath(PackageHelper.getSdDir(cid));
16459 void createCopyFile() {
16460 cid = mInstallerService.allocateExternalStageCidLegacy();
16463 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16464 if (origin.staged && origin.cid != null) {
16465 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16467 setMountPath(PackageHelper.getSdDir(cid));
16468 return PackageManager.INSTALL_SUCCEEDED;
16475 * Pre-emptively destroy the container since it's destroyed if
16476 * copying fails due to it existing anyway.
16478 PackageHelper.destroySdDir(cid);
16481 final String newMountPath = imcs.copyPackageToContainer(
16482 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16483 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16485 if (newMountPath != null) {
16486 setMountPath(newMountPath);
16487 return PackageManager.INSTALL_SUCCEEDED;
16489 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16494 String getCodePath() {
16495 return packagePath;
16499 String getResourcePath() {
16500 return resourcePath;
16503 int doPreInstall(int status) {
16504 if (status != PackageManager.INSTALL_SUCCEEDED) {
16505 // Destroy container
16506 PackageHelper.destroySdDir(cid);
16508 boolean mounted = PackageHelper.isContainerMounted(cid);
16510 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16511 Process.SYSTEM_UID);
16512 if (newMountPath != null) {
16513 setMountPath(newMountPath);
16515 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16522 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16523 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16524 String newMountPath = null;
16525 if (PackageHelper.isContainerMounted(cid)) {
16526 // Unmount the container
16527 if (!PackageHelper.unMountSdDir(cid)) {
16528 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16532 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16533 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16534 " which might be stale. Will try to clean up.");
16535 // Clean up the stale container and proceed to recreate.
16536 if (!PackageHelper.destroySdDir(newCacheId)) {
16537 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16540 // Successfully cleaned up stale container. Try to rename again.
16541 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16542 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16543 + " inspite of cleaning it up.");
16547 if (!PackageHelper.isContainerMounted(newCacheId)) {
16548 Slog.w(TAG, "Mounting container " + newCacheId);
16549 newMountPath = PackageHelper.mountSdDir(newCacheId,
16550 getEncryptKey(), Process.SYSTEM_UID);
16552 newMountPath = PackageHelper.getSdDir(newCacheId);
16554 if (newMountPath == null) {
16555 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
16558 Log.i(TAG, "Succesfully renamed " + cid +
16559 " to " + newCacheId +
16560 " at new path: " + newMountPath);
16563 final File beforeCodeFile = new File(packagePath);
16564 setMountPath(newMountPath);
16565 final File afterCodeFile = new File(packagePath);
16567 // Reflect the rename in scanned details
16568 pkg.setCodePath(afterCodeFile.getAbsolutePath());
16569 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16570 afterCodeFile, pkg.baseCodePath));
16571 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16572 afterCodeFile, pkg.splitCodePaths));
16574 // Reflect the rename in app info
16575 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16576 pkg.setApplicationInfoCodePath(pkg.codePath);
16577 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16578 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16579 pkg.setApplicationInfoResourcePath(pkg.codePath);
16580 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16581 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16586 private void setMountPath(String mountPath) {
16587 final File mountFile = new File(mountPath);
16589 final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16590 if (monolithicFile.exists()) {
16591 packagePath = monolithicFile.getAbsolutePath();
16592 if (isFwdLocked()) {
16593 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16595 resourcePath = packagePath;
16598 packagePath = mountFile.getAbsolutePath();
16599 resourcePath = packagePath;
16603 int doPostInstall(int status, int uid) {
16604 if (status != PackageManager.INSTALL_SUCCEEDED) {
16607 final int groupOwner;
16608 final String protectedFile;
16609 if (isFwdLocked()) {
16610 groupOwner = UserHandle.getSharedAppGid(uid);
16611 protectedFile = RES_FILE_NAME;
16614 protectedFile = null;
16617 if (uid < Process.FIRST_APPLICATION_UID
16618 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16619 Slog.e(TAG, "Failed to finalize " + cid);
16620 PackageHelper.destroySdDir(cid);
16621 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16624 boolean mounted = PackageHelper.isContainerMounted(cid);
16626 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16632 private void cleanUp() {
16633 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16635 // Destroy secure container
16636 PackageHelper.destroySdDir(cid);
16639 private List<String> getAllCodePaths() {
16640 final File codeFile = new File(getCodePath());
16641 if (codeFile != null && codeFile.exists()) {
16643 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16644 return pkg.getAllCodePaths();
16645 } catch (PackageParserException e) {
16646 // Ignored; we tried our best
16649 return Collections.EMPTY_LIST;
16652 void cleanUpResourcesLI() {
16653 // Enumerate all code paths before deleting
16654 cleanUpResourcesLI(getAllCodePaths());
16657 private void cleanUpResourcesLI(List<String> allCodePaths) {
16659 removeDexFiles(allCodePaths, instructionSets);
16662 String getPackageName() {
16663 return getAsecPackageName(cid);
16666 boolean doPostDeleteLI(boolean delete) {
16667 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16668 final List<String> allCodePaths = getAllCodePaths();
16669 boolean mounted = PackageHelper.isContainerMounted(cid);
16672 if (PackageHelper.unMountSdDir(cid)) {
16676 if (!mounted && delete) {
16677 cleanUpResourcesLI(allCodePaths);
16684 if (isFwdLocked()) {
16685 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16686 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16687 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16691 return PackageManager.INSTALL_SUCCEEDED;
16695 int doPostCopy(int uid) {
16696 if (isFwdLocked()) {
16697 if (uid < Process.FIRST_APPLICATION_UID
16698 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16700 Slog.e(TAG, "Failed to finalize " + cid);
16701 PackageHelper.destroySdDir(cid);
16702 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16706 return PackageManager.INSTALL_SUCCEEDED;
16711 * Logic to handle movement of existing installed applications.
16713 class MoveInstallArgs extends InstallArgs {
16714 private File codeFile;
16715 private File resourceFile;
16718 MoveInstallArgs(InstallParams params) {
16719 super(params.origin, params.move, params.observer, params.installFlags,
16720 params.installerPackageName, params.volumeUuid,
16721 params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16722 params.grantedRuntimePermissions,
16723 params.traceMethod, params.traceCookie, params.certificates,
16724 params.installReason);
16727 int copyApk(IMediaContainerService imcs, boolean temp) {
16728 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16729 + move.fromUuid + " to " + move.toUuid);
16730 synchronized (mInstaller) {
16732 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16733 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16734 } catch (InstallerException e) {
16735 Slog.w(TAG, "Failed to move app", e);
16736 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16740 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16741 resourceFile = codeFile;
16742 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16744 return PackageManager.INSTALL_SUCCEEDED;
16747 int doPreInstall(int status) {
16748 if (status != PackageManager.INSTALL_SUCCEEDED) {
16749 cleanUp(move.toUuid);
16754 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16755 if (status != PackageManager.INSTALL_SUCCEEDED) {
16756 cleanUp(move.toUuid);
16760 // Reflect the move in app info
16761 pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16762 pkg.setApplicationInfoCodePath(pkg.codePath);
16763 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16764 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16765 pkg.setApplicationInfoResourcePath(pkg.codePath);
16766 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16767 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16772 int doPostInstall(int status, int uid) {
16773 if (status == PackageManager.INSTALL_SUCCEEDED) {
16774 cleanUp(move.fromUuid);
16776 cleanUp(move.toUuid);
16782 String getCodePath() {
16783 return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16787 String getResourcePath() {
16788 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16791 private boolean cleanUp(String volumeUuid) {
16792 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16794 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16795 final int[] userIds = sUserManager.getUserIds();
16796 synchronized (mInstallLock) {
16797 // Clean up both app data and code
16798 // All package moves are frozen until finished
16799 for (int userId : userIds) {
16801 mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16802 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16803 } catch (InstallerException e) {
16804 Slog.w(TAG, String.valueOf(e));
16807 removeCodePathLI(codeFile);
16812 void cleanUpResourcesLI() {
16813 throw new UnsupportedOperationException();
16816 boolean doPostDeleteLI(boolean delete) {
16817 throw new UnsupportedOperationException();
16821 static String getAsecPackageName(String packageCid) {
16822 int idx = packageCid.lastIndexOf("-");
16826 return packageCid.substring(0, idx);
16829 // Utility method used to create code paths based on package name and available index.
16830 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16831 String idxStr = "";
16833 // Fall back to default value of idx=1 if prefix is not
16834 // part of oldCodePath
16835 if (oldCodePath != null) {
16836 String subStr = oldCodePath;
16837 // Drop the suffix right away
16838 if (suffix != null && subStr.endsWith(suffix)) {
16839 subStr = subStr.substring(0, subStr.length() - suffix.length());
16841 // If oldCodePath already contains prefix find out the
16842 // ending index to either increment or decrement.
16843 int sidx = subStr.lastIndexOf(prefix);
16845 subStr = subStr.substring(sidx + prefix.length());
16846 if (subStr != null) {
16847 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16848 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16851 idx = Integer.parseInt(subStr);
16857 } catch(NumberFormatException e) {
16862 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16863 return prefix + idxStr;
16866 private File getNextCodePath(File targetDir, String packageName) {
16868 SecureRandom random = new SecureRandom();
16869 byte[] bytes = new byte[16];
16871 random.nextBytes(bytes);
16872 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16873 result = new File(targetDir, packageName + "-" + suffix);
16874 } while (result.exists());
16878 // Utility method that returns the relative package path with respect
16879 // to the installation directory. Like say for /data/data/com.test-1.apk
16880 // string com.test-1 is returned.
16881 static String deriveCodePathName(String codePath) {
16882 if (codePath == null) {
16885 final File codeFile = new File(codePath);
16886 final String name = codeFile.getName();
16887 if (codeFile.isDirectory()) {
16889 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16890 final int lastDot = name.lastIndexOf('.');
16891 return name.substring(0, lastDot);
16893 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16898 static class PackageInstalledInfo {
16901 // The set of users that originally had this package installed.
16903 // The set of users that now have this package installed.
16905 PackageParser.Package pkg;
16908 PackageRemovedInfo removedInfo;
16909 ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16911 public void setError(int code, String msg) {
16912 setReturnCode(code);
16913 setReturnMessage(msg);
16917 public void setError(String msg, PackageParserException e) {
16918 setReturnCode(e.error);
16919 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16920 Slog.w(TAG, msg, e);
16923 public void setError(String msg, PackageManagerException e) {
16924 returnCode = e.error;
16925 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16926 Slog.w(TAG, msg, e);
16929 public void setReturnCode(int returnCode) {
16930 this.returnCode = returnCode;
16931 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16932 for (int i = 0; i < childCount; i++) {
16933 addedChildPackages.valueAt(i).returnCode = returnCode;
16937 private void setReturnMessage(String returnMsg) {
16938 this.returnMsg = returnMsg;
16939 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16940 for (int i = 0; i < childCount; i++) {
16941 addedChildPackages.valueAt(i).returnMsg = returnMsg;
16945 // In some error cases we want to convey more info back to the observer
16946 String origPackage;
16947 String origPermission;
16951 * Install a non-existing package.
16953 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16954 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16955 PackageInstalledInfo res, int installReason) {
16956 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16958 // Remember this for later, in case we need to rollback this install
16959 String pkgName = pkg.packageName;
16961 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16963 synchronized(mPackages) {
16964 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16965 if (renamedPackage != null) {
16966 // A package with the same name is already installed, though
16967 // it has been renamed to an older name. The package we
16968 // are trying to install should be installed as an update to
16969 // the existing one, but that has not been requested, so bail.
16970 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16971 + " without first uninstalling package running as "
16975 if (mPackages.containsKey(pkgName)) {
16976 // Don't allow installation over an existing package with the same name.
16977 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16978 + " without first uninstalling.");
16984 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
16985 System.currentTimeMillis(), user);
16987 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16989 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16990 prepareAppDataAfterInstallLIF(newPackage);
16993 // Remove package from internal structures, but keep around any
16994 // data that might have already existed
16995 deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16996 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16998 } catch (PackageManagerException e) {
16999 res.setError("Package couldn't be installed in " + pkg.codePath, e);
17002 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17005 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17006 // Can't rotate keys during boot or if sharedUser.
17007 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17008 || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17011 // app is using upgradeKeySets; make sure all are valid
17012 KeySetManagerService ksms = mSettings.mKeySetManagerService;
17013 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17014 for (int i = 0; i < upgradeKeySets.length; i++) {
17015 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17016 Slog.wtf(TAG, "Package "
17017 + (oldPs.name != null ? oldPs.name : "<null>")
17018 + " contains upgrade-key-set reference to unknown key-set: "
17019 + upgradeKeySets[i]
17020 + " reverting to signatures check.");
17027 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17028 // Upgrade keysets are being used. Determine if new package has a superset of the
17030 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17031 KeySetManagerService ksms = mSettings.mKeySetManagerService;
17032 for (int i = 0; i < upgradeKeySets.length; i++) {
17033 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17034 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17041 private static void updateDigest(MessageDigest digest, File file) throws IOException {
17042 try (DigestInputStream digestStream =
17043 new DigestInputStream(new FileInputStream(file), digest)) {
17044 while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17048 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17049 UserHandle user, String installerPackageName, PackageInstalledInfo res,
17050 int installReason) {
17051 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17053 final PackageParser.Package oldPackage;
17054 final PackageSetting ps;
17055 final String pkgName = pkg.packageName;
17056 final int[] allUsers;
17057 final int[] installedUsers;
17059 synchronized(mPackages) {
17060 oldPackage = mPackages.get(pkgName);
17061 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17063 // don't allow upgrade to target a release SDK from a pre-release SDK
17064 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17065 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17066 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17067 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17068 if (oldTargetsPreRelease
17069 && !newTargetsPreRelease
17070 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17071 Slog.w(TAG, "Can't install package targeting released sdk");
17072 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17076 ps = mSettings.mPackages.get(pkgName);
17078 // verify signatures are valid
17079 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17080 if (!checkUpgradeKeySetLP(ps, pkg)) {
17081 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17082 "New package not signed by keys specified by upgrade-keysets: "
17087 // default to original signature matching
17088 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17089 != PackageManager.SIGNATURE_MATCH) {
17090 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17091 "New package has a different signature: " + pkgName);
17096 // don't allow a system upgrade unless the upgrade hash matches
17097 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17098 byte[] digestBytes = null;
17100 final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17101 updateDigest(digest, new File(pkg.baseCodePath));
17102 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17103 for (String path : pkg.splitCodePaths) {
17104 updateDigest(digest, new File(path));
17107 digestBytes = digest.digest();
17108 } catch (NoSuchAlgorithmException | IOException e) {
17109 res.setError(INSTALL_FAILED_INVALID_APK,
17110 "Could not compute hash: " + pkgName);
17113 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17114 res.setError(INSTALL_FAILED_INVALID_APK,
17115 "New package fails restrict-update check: " + pkgName);
17118 // retain upgrade restriction
17119 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17122 // Check for shared user id changes
17123 String invalidPackageName =
17124 getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17125 if (invalidPackageName != null) {
17126 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17127 "Package " + invalidPackageName + " tried to change user "
17128 + oldPackage.mSharedUserId);
17132 // In case of rollback, remember per-user/profile install state
17133 allUsers = sUserManager.getUserIds();
17134 installedUsers = ps.queryInstalledUsers(allUsers, true);
17136 // don't allow an upgrade from full to ephemeral
17137 if (isInstantApp) {
17138 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17139 for (int currentUser : allUsers) {
17140 if (!ps.getInstantApp(currentUser)) {
17141 // can't downgrade from full to instant
17142 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17143 + " for user: " + currentUser);
17144 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17148 } else if (!ps.getInstantApp(user.getIdentifier())) {
17149 // can't downgrade from full to instant
17150 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17151 + " for user: " + user.getIdentifier());
17152 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17158 // Update what is removed
17159 res.removedInfo = new PackageRemovedInfo(this);
17160 res.removedInfo.uid = oldPackage.applicationInfo.uid;
17161 res.removedInfo.removedPackage = oldPackage.packageName;
17162 res.removedInfo.installerPackageName = ps.installerPackageName;
17163 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17164 res.removedInfo.isUpdate = true;
17165 res.removedInfo.origUsers = installedUsers;
17166 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17167 for (int i = 0; i < installedUsers.length; i++) {
17168 final int userId = installedUsers[i];
17169 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17172 final int childCount = (oldPackage.childPackages != null)
17173 ? oldPackage.childPackages.size() : 0;
17174 for (int i = 0; i < childCount; i++) {
17175 boolean childPackageUpdated = false;
17176 PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17177 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17178 if (res.addedChildPackages != null) {
17179 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17180 if (childRes != null) {
17181 childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17182 childRes.removedInfo.removedPackage = childPkg.packageName;
17183 if (childPs != null) {
17184 childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17186 childRes.removedInfo.isUpdate = true;
17187 childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17188 childPackageUpdated = true;
17191 if (!childPackageUpdated) {
17192 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17193 childRemovedRes.removedPackage = childPkg.packageName;
17194 if (childPs != null) {
17195 childRemovedRes.installerPackageName = childPs.installerPackageName;
17197 childRemovedRes.isUpdate = false;
17198 childRemovedRes.dataRemoved = true;
17199 synchronized (mPackages) {
17200 if (childPs != null) {
17201 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17204 if (res.removedInfo.removedChildPackages == null) {
17205 res.removedInfo.removedChildPackages = new ArrayMap<>();
17207 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17211 boolean sysPkg = (isSystemApp(oldPackage));
17213 // Set the system/privileged flags as needed
17214 final boolean privileged =
17215 (oldPackage.applicationInfo.privateFlags
17216 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17217 final int systemPolicyFlags = policyFlags
17218 | PackageParser.PARSE_IS_SYSTEM
17219 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17221 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17222 user, allUsers, installerPackageName, res, installReason);
17224 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17225 user, allUsers, installerPackageName, res, installReason);
17230 public List<String> getPreviousCodePaths(String packageName) {
17231 final int callingUid = Binder.getCallingUid();
17232 final List<String> result = new ArrayList<>();
17233 if (getInstantAppPackageName(callingUid) != null) {
17236 final PackageSetting ps = mSettings.mPackages.get(packageName);
17238 && ps.oldCodePaths != null
17239 && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17240 result.addAll(ps.oldCodePaths);
17245 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17246 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17247 int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17248 int installReason) {
17249 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17252 String pkgName = deletedPackage.packageName;
17253 boolean deletedPkg = true;
17254 boolean addedPkg = false;
17255 boolean updatedSettings = false;
17256 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17257 final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17258 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17260 final long origUpdateTime = (pkg.mExtras != null)
17261 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17263 // First delete the existing package while retaining the data directory
17264 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17265 res.removedInfo, true, pkg)) {
17266 // If the existing package wasn't successfully deleted
17267 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17268 deletedPkg = false;
17270 // Successfully deleted the old package; proceed with replace.
17272 // If deleted package lived in a container, give users a chance to
17273 // relinquish resources before killing.
17274 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17275 if (DEBUG_INSTALL) {
17276 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17278 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17279 final ArrayList<String> pkgList = new ArrayList<String>(1);
17280 pkgList.add(deletedPackage.applicationInfo.packageName);
17281 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17284 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17285 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17286 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17289 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17290 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17291 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17294 // Update the in-memory copy of the previous code paths.
17295 PackageSetting ps = mSettings.mPackages.get(pkgName);
17297 if (ps.oldCodePaths == null) {
17298 ps.oldCodePaths = new ArraySet<>();
17300 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17301 if (deletedPackage.splitCodePaths != null) {
17302 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17305 ps.oldCodePaths = null;
17307 if (ps.childPackageNames != null) {
17308 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17309 final String childPkgName = ps.childPackageNames.get(i);
17310 final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17311 childPs.oldCodePaths = ps.oldCodePaths;
17314 // set instant app status, but, only if it's explicitly specified
17315 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17316 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17317 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17318 prepareAppDataAfterInstallLIF(newPackage);
17320 mDexManager.notifyPackageUpdated(newPackage.packageName,
17321 newPackage.baseCodePath, newPackage.splitCodePaths);
17322 } catch (PackageManagerException e) {
17323 res.setError("Package couldn't be installed in " + pkg.codePath, e);
17327 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17328 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17330 // Revert all internal state mutations and added folders for the failed install
17332 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17333 res.removedInfo, true, null);
17336 // Restore the old package
17338 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17339 File restoreFile = new File(deletedPackage.codePath);
17340 // Parse old package
17341 boolean oldExternal = isExternal(deletedPackage);
17342 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
17343 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17344 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17345 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17347 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17349 } catch (PackageManagerException e) {
17350 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17355 synchronized (mPackages) {
17356 // Ensure the installer package name up to date
17357 setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17359 // Update permissions for restored package
17360 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17362 mSettings.writeLPr();
17365 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17368 synchronized (mPackages) {
17369 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17371 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17372 if (res.removedInfo.removedChildPackages != null) {
17373 final int childCount = res.removedInfo.removedChildPackages.size();
17374 // Iterate in reverse as we may modify the collection
17375 for (int i = childCount - 1; i >= 0; i--) {
17376 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17377 if (res.addedChildPackages.containsKey(childPackageName)) {
17378 res.removedInfo.removedChildPackages.removeAt(i);
17380 PackageRemovedInfo childInfo = res.removedInfo
17381 .removedChildPackages.valueAt(i);
17382 childInfo.removedForAllUsers = mPackages.get(
17383 childInfo.removedPackage) == null;
17392 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17393 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17394 int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17395 int installReason) {
17396 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17397 + ", old=" + deletedPackage);
17399 final boolean disabledSystem;
17401 // Remove existing system package
17402 removePackageLI(deletedPackage, true);
17404 synchronized (mPackages) {
17405 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17407 if (!disabledSystem) {
17408 // We didn't need to disable the .apk as a current system package,
17409 // which means we are replacing another update that is already
17410 // installed. We need to make sure to delete the older one's .apk.
17411 res.removedInfo.args = createInstallArgsForExisting(0,
17412 deletedPackage.applicationInfo.getCodePath(),
17413 deletedPackage.applicationInfo.getResourcePath(),
17414 getAppDexInstructionSets(deletedPackage.applicationInfo));
17416 res.removedInfo.args = null;
17419 // Successfully disabled the old package. Now proceed with re-installation
17420 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17421 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17422 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17424 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17425 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17426 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17428 PackageParser.Package newPackage = null;
17430 // Add the package to the internal data structures
17431 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17433 // Set the update and install times
17434 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17435 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17436 System.currentTimeMillis());
17438 // Update the package dynamic state if succeeded
17439 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17440 // Now that the install succeeded make sure we remove data
17441 // directories for any child package the update removed.
17442 final int deletedChildCount = (deletedPackage.childPackages != null)
17443 ? deletedPackage.childPackages.size() : 0;
17444 final int newChildCount = (newPackage.childPackages != null)
17445 ? newPackage.childPackages.size() : 0;
17446 for (int i = 0; i < deletedChildCount; i++) {
17447 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17448 boolean childPackageDeleted = true;
17449 for (int j = 0; j < newChildCount; j++) {
17450 PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17451 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17452 childPackageDeleted = false;
17456 if (childPackageDeleted) {
17457 PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17458 deletedChildPkg.packageName);
17459 if (ps != null && res.removedInfo.removedChildPackages != null) {
17460 PackageRemovedInfo removedChildRes = res.removedInfo
17461 .removedChildPackages.get(deletedChildPkg.packageName);
17462 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17463 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17468 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17470 prepareAppDataAfterInstallLIF(newPackage);
17472 mDexManager.notifyPackageUpdated(newPackage.packageName,
17473 newPackage.baseCodePath, newPackage.splitCodePaths);
17475 } catch (PackageManagerException e) {
17476 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17477 res.setError("Package couldn't be installed in " + pkg.codePath, e);
17480 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17481 // Re installation failed. Restore old information
17482 // Remove new pkg information
17483 if (newPackage != null) {
17484 removeInstalledPackageLI(newPackage, true);
17486 // Add back the old system package
17488 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17489 } catch (PackageManagerException e) {
17490 Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17493 synchronized (mPackages) {
17494 if (disabledSystem) {
17495 enableSystemPackageLPw(deletedPackage);
17498 // Ensure the installer package name up to date
17499 setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17501 // Update permissions for restored package
17502 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17504 mSettings.writeLPr();
17507 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17508 + " after failed upgrade");
17513 * Checks whether the parent or any of the child packages have a change shared
17514 * user. For a package to be a valid update the shred users of the parent and
17515 * the children should match. We may later support changing child shared users.
17516 * @param oldPkg The updated package.
17517 * @param newPkg The update package.
17518 * @return The shared user that change between the versions.
17520 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17521 PackageParser.Package newPkg) {
17522 // Check parent shared user
17523 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17524 return newPkg.packageName;
17526 // Check child shared users
17527 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17528 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17529 for (int i = 0; i < newChildCount; i++) {
17530 PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17531 // If this child was present, did it have the same shared user?
17532 for (int j = 0; j < oldChildCount; j++) {
17533 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17534 if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17535 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17536 return newChildPkg.packageName;
17543 private void removeNativeBinariesLI(PackageSetting ps) {
17544 // Remove the lib path for the parent package
17546 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17547 // Remove the lib path for the child packages
17548 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17549 for (int i = 0; i < childCount; i++) {
17550 PackageSetting childPs = null;
17551 synchronized (mPackages) {
17552 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17554 if (childPs != null) {
17555 NativeLibraryHelper.removeNativeBinariesLI(childPs
17556 .legacyNativeLibraryPathString);
17562 private void enableSystemPackageLPw(PackageParser.Package pkg) {
17563 // Enable the parent package
17564 mSettings.enableSystemPackageLPw(pkg.packageName);
17565 // Enable the child packages
17566 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17567 for (int i = 0; i < childCount; i++) {
17568 PackageParser.Package childPkg = pkg.childPackages.get(i);
17569 mSettings.enableSystemPackageLPw(childPkg.packageName);
17573 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17574 PackageParser.Package newPkg) {
17575 // Disable the parent package (parent always replaced)
17576 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17577 // Disable the child packages
17578 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17579 for (int i = 0; i < childCount; i++) {
17580 PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17581 final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17582 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17587 private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17588 String installerPackageName) {
17589 // Enable the parent package
17590 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17591 // Enable the child packages
17592 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17593 for (int i = 0; i < childCount; i++) {
17594 PackageParser.Package childPkg = pkg.childPackages.get(i);
17595 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17599 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17600 // Collect all used permissions in the UID
17601 ArraySet<String> usedPermissions = new ArraySet<>();
17602 final int packageCount = su.packages.size();
17603 for (int i = 0; i < packageCount; i++) {
17604 PackageSetting ps = su.packages.valueAt(i);
17605 if (ps.pkg == null) {
17608 final int requestedPermCount = ps.pkg.requestedPermissions.size();
17609 for (int j = 0; j < requestedPermCount; j++) {
17610 String permission = ps.pkg.requestedPermissions.get(j);
17611 BasePermission bp = mSettings.mPermissions.get(permission);
17613 usedPermissions.add(permission);
17618 PermissionsState permissionsState = su.getPermissionsState();
17619 // Prune install permissions
17620 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17621 final int installPermCount = installPermStates.size();
17622 for (int i = installPermCount - 1; i >= 0; i--) {
17623 PermissionState permissionState = installPermStates.get(i);
17624 if (!usedPermissions.contains(permissionState.getName())) {
17625 BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17627 permissionsState.revokeInstallPermission(bp);
17628 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17629 PackageManager.MASK_PERMISSION_FLAGS, 0);
17634 int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17636 // Prune runtime permissions
17637 for (int userId : allUserIds) {
17638 List<PermissionState> runtimePermStates = permissionsState
17639 .getRuntimePermissionStates(userId);
17640 final int runtimePermCount = runtimePermStates.size();
17641 for (int i = runtimePermCount - 1; i >= 0; i--) {
17642 PermissionState permissionState = runtimePermStates.get(i);
17643 if (!usedPermissions.contains(permissionState.getName())) {
17644 BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17646 permissionsState.revokeRuntimePermission(bp, userId);
17647 permissionsState.updatePermissionFlags(bp, userId,
17648 PackageManager.MASK_PERMISSION_FLAGS, 0);
17649 runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17650 runtimePermissionChangedUserIds, userId);
17656 return runtimePermissionChangedUserIds;
17659 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17660 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17661 // Update the parent package setting
17662 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17663 res, user, installReason);
17664 // Update the child packages setting
17665 final int childCount = (newPackage.childPackages != null)
17666 ? newPackage.childPackages.size() : 0;
17667 for (int i = 0; i < childCount; i++) {
17668 PackageParser.Package childPackage = newPackage.childPackages.get(i);
17669 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17670 updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17671 childRes.origUsers, childRes, user, installReason);
17675 private void updateSettingsInternalLI(PackageParser.Package newPackage,
17676 String installerPackageName, int[] allUsers, int[] installedForUsers,
17677 PackageInstalledInfo res, UserHandle user, int installReason) {
17678 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17680 String pkgName = newPackage.packageName;
17681 synchronized (mPackages) {
17682 //write settings. the installStatus will be incomplete at this stage.
17683 //note that the new package setting would have already been
17684 //added to mPackages. It hasn't been persisted yet.
17685 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17686 // TODO: Remove this write? It's also written at the end of this method
17687 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17688 mSettings.writeLPr();
17689 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17692 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17693 synchronized (mPackages) {
17694 updatePermissionsLPw(newPackage.packageName, newPackage,
17695 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17696 ? UPDATE_PERMISSIONS_ALL : 0));
17697 // For system-bundled packages, we assume that installing an upgraded version
17698 // of the package implies that the user actually wants to run that new code,
17699 // so we enable the package.
17700 PackageSetting ps = mSettings.mPackages.get(pkgName);
17701 final int userId = user.getIdentifier();
17703 if (isSystemApp(newPackage)) {
17704 if (DEBUG_INSTALL) {
17705 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17707 // Enable system package for requested users
17708 if (res.origUsers != null) {
17709 for (int origUserId : res.origUsers) {
17710 if (userId == UserHandle.USER_ALL || userId == origUserId) {
17711 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17712 origUserId, installerPackageName);
17716 // Also convey the prior install/uninstall state
17717 if (allUsers != null && installedForUsers != null) {
17718 for (int currentUserId : allUsers) {
17719 final boolean installed = ArrayUtils.contains(
17720 installedForUsers, currentUserId);
17721 if (DEBUG_INSTALL) {
17722 Slog.d(TAG, " user " + currentUserId + " => " + installed);
17724 ps.setInstalled(installed, currentUserId);
17726 // these install state changes will be persisted in the
17727 // upcoming call to mSettings.writeLPr().
17730 // It's implied that when a user requests installation, they want the app to be
17731 // installed and enabled.
17732 if (userId != UserHandle.USER_ALL) {
17733 ps.setInstalled(true, userId);
17734 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17737 // When replacing an existing package, preserve the original install reason for all
17738 // users that had the package installed before.
17739 final Set<Integer> previousUserIds = new ArraySet<>();
17740 if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17741 final int installReasonCount = res.removedInfo.installReasons.size();
17742 for (int i = 0; i < installReasonCount; i++) {
17743 final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17744 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17745 ps.setInstallReason(previousInstallReason, previousUserId);
17746 previousUserIds.add(previousUserId);
17750 // Set install reason for users that are having the package newly installed.
17751 if (userId == UserHandle.USER_ALL) {
17752 for (int currentUserId : sUserManager.getUserIds()) {
17753 if (!previousUserIds.contains(currentUserId)) {
17754 ps.setInstallReason(installReason, currentUserId);
17757 } else if (!previousUserIds.contains(userId)) {
17758 ps.setInstallReason(installReason, userId);
17760 mSettings.writeKernelMappingLPr(ps);
17762 res.name = pkgName;
17763 res.uid = newPackage.applicationInfo.uid;
17764 res.pkg = newPackage;
17765 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17766 mSettings.setInstallerPackageName(pkgName, installerPackageName);
17767 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17768 //to update install status
17769 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17770 mSettings.writeLPr();
17771 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17774 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17777 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17779 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17780 installPackageLI(args, res);
17782 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17786 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17787 final int installFlags = args.installFlags;
17788 final String installerPackageName = args.installerPackageName;
17789 final String volumeUuid = args.volumeUuid;
17790 final File tmpPackageFile = new File(args.getCodePath());
17791 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17792 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17793 || (args.volumeUuid != null));
17794 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17795 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17796 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17797 boolean replace = false;
17798 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17799 if (args.move != null) {
17800 // moving a complete application; perform an initial scan on the new install location
17801 scanFlags |= SCAN_INITIAL;
17803 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17804 scanFlags |= SCAN_DONT_KILL_APP;
17807 scanFlags |= SCAN_AS_INSTANT_APP;
17810 scanFlags |= SCAN_AS_FULL_APP;
17813 // Result object to be returned
17814 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17816 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17819 if (instantApp && (forwardLocked || onExternal)) {
17820 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17821 + " external=" + onExternal);
17822 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17826 // Retrieve PackageSettings and parse package
17827 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17828 | PackageParser.PARSE_ENFORCE_CODE
17829 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17830 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17831 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17832 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17833 PackageParser pp = new PackageParser();
17834 pp.setSeparateProcesses(mSeparateProcesses);
17835 pp.setDisplayMetrics(mMetrics);
17836 pp.setCallback(mPackageParserCallback);
17838 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17839 final PackageParser.Package pkg;
17841 pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17842 } catch (PackageParserException e) {
17843 res.setError("Failed parse during installPackageLI", e);
17846 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17849 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17850 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17851 Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17852 res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17853 "Instant app package must target O");
17856 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17857 Slog.w(TAG, "Instant app package " + pkg.packageName
17858 + " does not target targetSandboxVersion 2");
17859 res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17860 "Instant app package must use targetSanboxVersion 2");
17864 if (pkg.applicationInfo.isStaticSharedLibrary()) {
17865 // Static shared libraries have synthetic package names
17866 renameStaticSharedLibraryPackage(pkg);
17868 // No static shared libs on external storage
17870 Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17871 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17872 "Packages declaring static-shared libs cannot be updated");
17877 // If we are installing a clustered package add results for the children
17878 if (pkg.childPackages != null) {
17879 synchronized (mPackages) {
17880 final int childCount = pkg.childPackages.size();
17881 for (int i = 0; i < childCount; i++) {
17882 PackageParser.Package childPkg = pkg.childPackages.get(i);
17883 PackageInstalledInfo childRes = new PackageInstalledInfo();
17884 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17885 childRes.pkg = childPkg;
17886 childRes.name = childPkg.packageName;
17887 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17888 if (childPs != null) {
17889 childRes.origUsers = childPs.queryInstalledUsers(
17890 sUserManager.getUserIds(), true);
17892 if ((mPackages.containsKey(childPkg.packageName))) {
17893 childRes.removedInfo = new PackageRemovedInfo(this);
17894 childRes.removedInfo.removedPackage = childPkg.packageName;
17895 childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17897 if (res.addedChildPackages == null) {
17898 res.addedChildPackages = new ArrayMap<>();
17900 res.addedChildPackages.put(childPkg.packageName, childRes);
17905 // If package doesn't declare API override, mark that we have an install
17906 // time CPU ABI override.
17907 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17908 pkg.cpuAbiOverride = args.abiOverride;
17911 String pkgName = res.name = pkg.packageName;
17912 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17913 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17914 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17920 // either use what we've been given or parse directly from the APK
17921 if (args.certificates != null) {
17923 PackageParser.populateCertificates(pkg, args.certificates);
17924 } catch (PackageParserException e) {
17925 // there was something wrong with the certificates we were given;
17926 // try to pull them from the APK
17927 PackageParser.collectCertificates(pkg, parseFlags);
17930 PackageParser.collectCertificates(pkg, parseFlags);
17932 } catch (PackageParserException e) {
17933 res.setError("Failed collect during installPackageLI", e);
17937 // Get rid of all references to package scan path via parser.
17939 String oldCodePath = null;
17940 boolean systemApp = false;
17941 synchronized (mPackages) {
17942 // Check if installing already existing package
17943 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17944 String oldName = mSettings.getRenamedPackageLPr(pkgName);
17945 if (pkg.mOriginalPackages != null
17946 && pkg.mOriginalPackages.contains(oldName)
17947 && mPackages.containsKey(oldName)) {
17948 // This package is derived from an original package,
17949 // and this device has been updating from that original
17950 // name. We must continue using the original name, so
17951 // rename the new package here.
17952 pkg.setPackageName(oldName);
17953 pkgName = pkg.packageName;
17955 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17956 + oldName + " pkgName=" + pkgName);
17957 } else if (mPackages.containsKey(pkgName)) {
17958 // This package, under its official name, already exists
17959 // on the device; we should replace it.
17961 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17964 // Child packages are installed through the parent package
17965 if (pkg.parentPackage != null) {
17966 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17967 "Package " + pkg.packageName + " is child of package "
17968 + pkg.parentPackage.parentPackage + ". Child packages "
17969 + "can be updated only through the parent package.");
17974 // Prevent apps opting out from runtime permissions
17975 PackageParser.Package oldPackage = mPackages.get(pkgName);
17976 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17977 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17978 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17979 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17980 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17981 "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17982 + " doesn't support runtime permissions but the old"
17983 + " target SDK " + oldTargetSdk + " does.");
17986 // Prevent apps from downgrading their targetSandbox.
17987 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17988 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17989 if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17990 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17991 "Package " + pkg.packageName + " new target sandbox "
17992 + newTargetSandbox + " is incompatible with the previous value of"
17993 + oldTargetSandbox + ".");
17997 // Prevent installing of child packages
17998 if (oldPackage.parentPackage != null) {
17999 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18000 "Package " + pkg.packageName + " is child of package "
18001 + oldPackage.parentPackage + ". Child packages "
18002 + "can be updated only through the parent package.");
18008 PackageSetting ps = mSettings.mPackages.get(pkgName);
18010 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18012 // Static shared libs have same package with different versions where
18013 // we internally use a synthetic package name to allow multiple versions
18014 // of the same package, therefore we need to compare signatures against
18015 // the package setting for the latest library version.
18016 PackageSetting signatureCheckPs = ps;
18017 if (pkg.applicationInfo.isStaticSharedLibrary()) {
18018 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18019 if (libraryEntry != null) {
18020 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18024 // Quick sanity check that we're signed correctly if updating;
18025 // we'll check this again later when scanning, but we want to
18026 // bail early here before tripping over redefined permissions.
18027 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18028 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18029 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18030 + pkg.packageName + " upgrade keys do not match the "
18031 + "previously installed version");
18036 verifySignaturesLP(signatureCheckPs, pkg);
18037 } catch (PackageManagerException e) {
18038 res.setError(e.error, e.getMessage());
18043 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18044 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18045 systemApp = (ps.pkg.applicationInfo.flags &
18046 ApplicationInfo.FLAG_SYSTEM) != 0;
18048 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18051 int N = pkg.permissions.size();
18052 for (int i = N-1; i >= 0; i--) {
18053 PackageParser.Permission perm = pkg.permissions.get(i);
18054 BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18056 // Don't allow anyone but the system to define ephemeral permissions.
18057 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18059 Slog.w(TAG, "Non-System package " + pkg.packageName
18060 + " attempting to delcare ephemeral permission "
18061 + perm.info.name + "; Removing ephemeral.");
18062 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18064 // Check whether the newly-scanned package wants to define an already-defined perm
18066 // If the defining package is signed with our cert, it's okay. This
18067 // also includes the "updating the same package" case, of course.
18068 // "updating same package" could also involve key-rotation.
18069 final boolean sigsOk;
18070 if (bp.sourcePackage.equals(pkg.packageName)
18071 && (bp.packageSetting instanceof PackageSetting)
18072 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18074 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18076 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18077 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18080 // If the owning package is the system itself, we log but allow
18081 // install to proceed; we fail the install on all other permission
18083 if (!bp.sourcePackage.equals("android")) {
18084 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18085 + pkg.packageName + " attempting to redeclare permission "
18086 + perm.info.name + " already owned by " + bp.sourcePackage);
18087 res.origPermission = perm.info.name;
18088 res.origPackage = bp.sourcePackage;
18091 Slog.w(TAG, "Package " + pkg.packageName
18092 + " attempting to redeclare system permission "
18093 + perm.info.name + "; ignoring new declaration");
18094 pkg.permissions.remove(i);
18096 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18097 // Prevent apps to change protection level to dangerous from any other
18098 // type as this would allow a privilege escalation where an app adds a
18099 // normal/signature permission in other app's group and later redefines
18100 // it as dangerous leading to the group auto-grant.
18101 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18102 == PermissionInfo.PROTECTION_DANGEROUS) {
18103 if (bp != null && !bp.isRuntime()) {
18104 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18105 + "non-runtime permission " + perm.info.name
18106 + " to runtime; keeping old protection level");
18107 perm.info.protectionLevel = bp.protectionLevel;
18117 // Abort update; system app can't be replaced with app on sdcard
18118 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18119 "Cannot install updates to system apps on sdcard");
18121 } else if (instantApp) {
18122 // Abort update; system app can't be replaced with an instant app
18123 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18124 "Cannot update a system app with an instant app");
18129 if (args.move != null) {
18130 // We did an in-place move, so dex is ready to roll
18131 scanFlags |= SCAN_NO_DEX;
18132 scanFlags |= SCAN_MOVE;
18134 synchronized (mPackages) {
18135 final PackageSetting ps = mSettings.mPackages.get(pkgName);
18137 res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18138 "Missing settings for moved package " + pkgName);
18141 // We moved the entire application as-is, so bring over the
18142 // previously derived ABI information.
18143 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18144 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18147 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18148 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18149 scanFlags |= SCAN_NO_DEX;
18152 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18153 args.abiOverride : pkg.cpuAbiOverride);
18154 final boolean extractNativeLibs = !pkg.isLibrary();
18155 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18156 extractNativeLibs, mAppLib32InstallDir);
18157 } catch (PackageManagerException pme) {
18158 Slog.e(TAG, "Error deriving application ABI", pme);
18159 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18163 // Shared libraries for the package need to be updated.
18164 synchronized (mPackages) {
18166 updateSharedLibrariesLPr(pkg, null);
18167 } catch (PackageManagerException e) {
18168 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18172 // dexopt can take some time to complete, so, for instant apps, we skip this
18173 // step during installation. Instead, we'll take extra time the first time the
18174 // instant app starts. It's preferred to do it this way to provide continuous
18175 // progress to the user instead of mysteriously blocking somewhere in the
18176 // middle of running an instant app. The default behaviour can be overridden
18178 if (!instantApp || Global.getInt(
18179 mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18180 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18181 // Do not run PackageDexOptimizer through the local performDexOpt
18182 // method because `pkg` may not be in `mPackages` yet.
18184 // Also, don't fail application installs if the dexopt step fails.
18185 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18186 null /* instructionSets */, false /* checkProfiles */,
18187 getCompilerFilterForReason(REASON_INSTALL),
18188 getOrCreateCompilerPackageStats(pkg),
18189 mDexManager.isUsedByOtherApps(pkg.packageName));
18190 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18193 // Notify BackgroundDexOptService that the package has been changed.
18194 // If this is an update of a package which used to fail to compile,
18195 // BDOS will remove it from its blacklist.
18196 // TODO: Layering violation
18197 BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18200 if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18201 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18205 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18207 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18208 "installPackageLI")) {
18210 if (pkg.applicationInfo.isStaticSharedLibrary()) {
18211 // Static libs have a synthetic package name containing the version
18212 // and cannot be updated as an update would get a new package name,
18213 // unless this is the exact same version code which is useful for
18215 PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18216 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18217 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18218 + "static-shared libs cannot be updated");
18222 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18223 installerPackageName, res, args.installReason);
18225 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18226 args.user, installerPackageName, volumeUuid, res, args.installReason);
18230 synchronized (mPackages) {
18231 final PackageSetting ps = mSettings.mPackages.get(pkgName);
18233 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18234 ps.setUpdateAvailable(false /*updateAvailable*/);
18237 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18238 for (int i = 0; i < childCount; i++) {
18239 PackageParser.Package childPkg = pkg.childPackages.get(i);
18240 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18241 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18242 if (childPs != null) {
18243 childRes.newUsers = childPs.queryInstalledUsers(
18244 sUserManager.getUserIds(), true);
18248 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18249 updateSequenceNumberLP(ps, res.newUsers);
18250 updateInstantAppInstallerLocked(pkgName);
18255 private void startIntentFilterVerifications(int userId, boolean replacing,
18256 PackageParser.Package pkg) {
18257 if (mIntentFilterVerifierComponent == null) {
18258 Slog.w(TAG, "No IntentFilter verification will not be done as "
18259 + "there is no IntentFilterVerifier available!");
18263 final int verifierUid = getPackageUid(
18264 mIntentFilterVerifierComponent.getPackageName(),
18265 MATCH_DEBUG_TRIAGED_MISSING,
18266 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18268 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18269 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18270 mHandler.sendMessage(msg);
18272 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18273 for (int i = 0; i < childCount; i++) {
18274 PackageParser.Package childPkg = pkg.childPackages.get(i);
18275 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18276 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18277 mHandler.sendMessage(msg);
18281 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18282 PackageParser.Package pkg) {
18283 int size = pkg.activities.size();
18285 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18286 "No activity, so no need to verify any IntentFilter!");
18290 final boolean hasDomainURLs = hasDomainURLs(pkg);
18291 if (!hasDomainURLs) {
18292 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18293 "No domain URLs, so no need to verify any IntentFilter!");
18297 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18298 + " if any IntentFilter from the " + size
18299 + " Activities needs verification ...");
18302 final String packageName = pkg.packageName;
18304 synchronized (mPackages) {
18305 // If this is a new install and we see that we've already run verification for this
18306 // package, we have nothing to do: it means the state was restored from backup.
18308 IntentFilterVerificationInfo ivi =
18309 mSettings.getIntentFilterVerificationLPr(packageName);
18311 if (DEBUG_DOMAIN_VERIFICATION) {
18312 Slog.i(TAG, "Package " + packageName+ " already verified: status="
18313 + ivi.getStatusString());
18319 // If any filters need to be verified, then all need to be.
18320 boolean needToVerify = false;
18321 for (PackageParser.Activity a : pkg.activities) {
18322 for (ActivityIntentInfo filter : a.intents) {
18323 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18324 if (DEBUG_DOMAIN_VERIFICATION) {
18325 Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18327 needToVerify = true;
18333 if (needToVerify) {
18334 final int verificationId = mIntentFilterVerificationToken++;
18335 for (PackageParser.Activity a : pkg.activities) {
18336 for (ActivityIntentInfo filter : a.intents) {
18337 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18338 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18339 "Verification needed for IntentFilter:" + filter.toString());
18340 mIntentFilterVerifier.addOneIntentFilterVerification(
18341 verifierUid, userId, verificationId, filter, packageName);
18350 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18351 + " IntentFilter verification" + (count > 1 ? "s" : "")
18352 + " for userId:" + userId);
18353 mIntentFilterVerifier.startVerifications(userId);
18355 if (DEBUG_DOMAIN_VERIFICATION) {
18356 Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18361 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18362 final ComponentName cn = filter.activity.getComponentName();
18363 final String packageName = cn.getPackageName();
18365 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18370 int status = ivi.getStatus();
18372 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18373 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18382 private static boolean isMultiArch(ApplicationInfo info) {
18383 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18386 private static boolean isExternal(PackageParser.Package pkg) {
18387 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18390 private static boolean isExternal(PackageSetting ps) {
18391 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18394 private static boolean isSystemApp(PackageParser.Package pkg) {
18395 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18398 private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18399 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18402 private static boolean hasDomainURLs(PackageParser.Package pkg) {
18403 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18406 private static boolean isSystemApp(PackageSetting ps) {
18407 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18410 private static boolean isUpdatedSystemApp(PackageSetting ps) {
18411 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18414 private int packageFlagsToInstallFlags(PackageSetting ps) {
18415 int installFlags = 0;
18416 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18417 // This existing package was an external ASEC install when we have
18418 // the external flag without a UUID
18419 installFlags |= PackageManager.INSTALL_EXTERNAL;
18421 if (ps.isForwardLocked()) {
18422 installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18424 return installFlags;
18427 private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18428 if (isExternal(pkg)) {
18429 if (TextUtils.isEmpty(pkg.volumeUuid)) {
18430 return StorageManager.UUID_PRIMARY_PHYSICAL;
18432 return pkg.volumeUuid;
18435 return StorageManager.UUID_PRIVATE_INTERNAL;
18439 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18440 if (isExternal(pkg)) {
18441 if (TextUtils.isEmpty(pkg.volumeUuid)) {
18442 return mSettings.getExternalVersion();
18444 return mSettings.findOrCreateVersion(pkg.volumeUuid);
18447 return mSettings.getInternalVersion();
18451 private void deleteTempPackageFiles() {
18452 final FilenameFilter filter = new FilenameFilter() {
18453 public boolean accept(File dir, String name) {
18454 return name.startsWith("vmdl") && name.endsWith(".tmp");
18457 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18463 public void deletePackageAsUser(String packageName, int versionCode,
18464 IPackageDeleteObserver observer, int userId, int flags) {
18465 deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18466 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18470 public void deletePackageVersioned(VersionedPackage versionedPackage,
18471 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18472 final int callingUid = Binder.getCallingUid();
18473 mContext.enforceCallingOrSelfPermission(
18474 android.Manifest.permission.DELETE_PACKAGES, null);
18475 final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18476 Preconditions.checkNotNull(versionedPackage);
18477 Preconditions.checkNotNull(observer);
18478 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18479 PackageManager.VERSION_CODE_HIGHEST,
18480 Integer.MAX_VALUE, "versionCode must be >= -1");
18482 final String packageName = versionedPackage.getPackageName();
18483 final int versionCode = versionedPackage.getVersionCode();
18484 final String internalPackageName;
18485 synchronized (mPackages) {
18486 // Normalize package name to handle renamed packages and static libs
18487 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18488 versionedPackage.getVersionCode());
18491 final int uid = Binder.getCallingUid();
18492 if (!isOrphaned(internalPackageName)
18493 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18495 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18496 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18497 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18498 observer.onUserActionRequired(intent);
18499 } catch (RemoteException re) {
18503 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18504 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18505 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18506 mContext.enforceCallingOrSelfPermission(
18507 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18508 "deletePackage for user " + userId);
18511 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18513 observer.onPackageDeleted(packageName,
18514 PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18515 } catch (RemoteException re) {
18520 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18522 observer.onPackageDeleted(packageName,
18523 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18524 } catch (RemoteException re) {
18529 if (DEBUG_REMOVE) {
18530 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18531 + " deleteAllUsers: " + deleteAllUsers + " version="
18532 + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18533 ? "VERSION_CODE_HIGHEST" : versionCode));
18535 // Queue up an async operation since the package deletion may take a little while.
18536 mHandler.post(new Runnable() {
18537 public void run() {
18538 mHandler.removeCallbacks(this);
18540 final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18541 boolean doDeletePackage = true;
18543 final boolean targetIsInstantApp =
18544 ps.getInstantApp(UserHandle.getUserId(callingUid));
18545 doDeletePackage = !targetIsInstantApp
18546 || canViewInstantApps;
18548 if (doDeletePackage) {
18549 if (!deleteAllUsers) {
18550 returnCode = deletePackageX(internalPackageName, versionCode,
18551 userId, deleteFlags);
18553 int[] blockUninstallUserIds = getBlockUninstallForUsers(
18554 internalPackageName, users);
18555 // If nobody is blocking uninstall, proceed with delete for all users
18556 if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18557 returnCode = deletePackageX(internalPackageName, versionCode,
18558 userId, deleteFlags);
18560 // Otherwise uninstall individually for users with blockUninstalls=false
18561 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18562 for (int userId : users) {
18563 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18564 returnCode = deletePackageX(internalPackageName, versionCode,
18565 userId, userFlags);
18566 if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18567 Slog.w(TAG, "Package delete failed for user " + userId
18568 + ", returnCode " + returnCode);
18572 // The app has only been marked uninstalled for certain users.
18573 // We still need to report that delete was blocked
18574 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18578 returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18581 observer.onPackageDeleted(packageName, returnCode, null);
18582 } catch (RemoteException e) {
18583 Log.i(TAG, "Observer no longer exists.");
18589 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18590 if (pkg.staticSharedLibName != null) {
18591 return pkg.manifestPackageName;
18593 return pkg.packageName;
18596 private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18597 // Handle renamed packages
18598 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18599 packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18601 // Is this a static library?
18602 SparseArray<SharedLibraryEntry> versionedLib =
18603 mStaticLibsByDeclaringPackage.get(packageName);
18604 if (versionedLib == null || versionedLib.size() <= 0) {
18605 return packageName;
18608 // Figure out which lib versions the caller can see
18609 SparseIntArray versionsCallerCanSee = null;
18610 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18611 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18612 && callingAppId != Process.ROOT_UID) {
18613 versionsCallerCanSee = new SparseIntArray();
18614 String libName = versionedLib.valueAt(0).info.getName();
18615 String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18616 if (uidPackages != null) {
18617 for (String uidPackage : uidPackages) {
18618 PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18619 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18621 final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18622 versionsCallerCanSee.append(libVersion, libVersion);
18628 // Caller can see nothing - done
18629 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18630 return packageName;
18633 // Find the version the caller can see and the app version code
18634 SharedLibraryEntry highestVersion = null;
18635 final int versionCount = versionedLib.size();
18636 for (int i = 0; i < versionCount; i++) {
18637 SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18638 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18639 libEntry.info.getVersion()) < 0) {
18642 final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18643 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18644 if (libVersionCode == versionCode) {
18645 return libEntry.apk;
18647 } else if (highestVersion == null) {
18648 highestVersion = libEntry;
18649 } else if (libVersionCode > highestVersion.info
18650 .getDeclaringPackage().getVersionCode()) {
18651 highestVersion = libEntry;
18655 if (highestVersion != null) {
18656 return highestVersion.apk;
18659 return packageName;
18662 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18663 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18664 || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18667 final int callingUserId = UserHandle.getUserId(callingUid);
18668 // If the caller installed the pkgName, then allow it to silently uninstall.
18669 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18673 // Allow package verifier to silently uninstall.
18674 if (mRequiredVerifierPackage != null &&
18675 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18679 // Allow package uninstaller to silently uninstall.
18680 if (mRequiredUninstallerPackage != null &&
18681 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18685 // Allow storage manager to silently uninstall.
18686 if (mStorageManagerPackage != null &&
18687 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18693 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18694 int[] result = EMPTY_INT_ARRAY;
18695 for (int userId : userIds) {
18696 if (getBlockUninstallForUser(packageName, userId)) {
18697 result = ArrayUtils.appendInt(result, userId);
18704 public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18705 final int callingUid = Binder.getCallingUid();
18706 if (getInstantAppPackageName(callingUid) != null
18707 && !isCallerSameApp(packageName, callingUid)) {
18710 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18713 private boolean isPackageDeviceAdmin(String packageName, int userId) {
18714 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18715 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18718 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18719 /* callingUserOnly =*/ false);
18720 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18721 : deviceOwnerComponentName.getPackageName();
18722 // Does the package contains the device owner?
18723 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise,
18724 // this check is probably not needed, since DO should be registered as a device
18725 // admin on some user too. (Original bug for this: b/17657954)
18726 if (packageName.equals(deviceOwnerPackageName)) {
18729 // Does it contain a device admin for any user?
18731 if (userId == UserHandle.USER_ALL) {
18732 users = sUserManager.getUserIds();
18734 users = new int[]{userId};
18736 for (int i = 0; i < users.length; ++i) {
18737 if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18742 } catch (RemoteException e) {
18747 private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18748 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18752 * This method is an internal method that could be get invoked either
18753 * to delete an installed package or to clean up a failed installation.
18754 * After deleting an installed package, a broadcast is sent to notify any
18755 * listeners that the package has been removed. For cleaning up a failed
18756 * installation, the broadcast is not necessary since the package's
18757 * installation wouldn't have sent the initial broadcast either
18758 * The key steps in deleting a package are
18759 * deleting the package information in internal structures like mPackages,
18760 * deleting the packages base directories through installd
18761 * updating mSettings to reflect current status
18762 * persisting settings for later use
18763 * sending a broadcast if necessary
18765 int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18766 final PackageRemovedInfo info = new PackageRemovedInfo(this);
18769 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18770 ? UserHandle.USER_ALL : userId;
18772 if (isPackageDeviceAdmin(packageName, removeUser)) {
18773 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18774 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18777 PackageSetting uninstalledPs = null;
18778 PackageParser.Package pkg = null;
18780 // for the uninstall-updates case and restricted profiles, remember the per-
18781 // user handle installed state
18783 synchronized (mPackages) {
18784 uninstalledPs = mSettings.mPackages.get(packageName);
18785 if (uninstalledPs == null) {
18786 Slog.w(TAG, "Not removing non-existent package " + packageName);
18787 return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18790 if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18791 && uninstalledPs.versionCode != versionCode) {
18792 Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18793 + uninstalledPs.versionCode + " != " + versionCode);
18794 return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18797 // Static shared libs can be declared by any package, so let us not
18798 // allow removing a package if it provides a lib others depend on.
18799 pkg = mPackages.get(packageName);
18801 allUsers = sUserManager.getUserIds();
18803 if (pkg != null && pkg.staticSharedLibName != null) {
18804 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18805 pkg.staticSharedLibVersion);
18806 if (libEntry != null) {
18807 for (int currUserId : allUsers) {
18808 if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18811 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18812 libEntry.info, 0, currUserId);
18813 if (!ArrayUtils.isEmpty(libClientPackages)) {
18814 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18815 + " hosting lib " + libEntry.info.getName() + " version "
18816 + libEntry.info.getVersion() + " used by " + libClientPackages
18817 + " for user " + currUserId);
18818 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18824 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18827 final int freezeUser;
18828 if (isUpdatedSystemApp(uninstalledPs)
18829 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18830 // We're downgrading a system app, which will apply to all users, so
18831 // freeze them all during the downgrade
18832 freezeUser = UserHandle.USER_ALL;
18834 freezeUser = removeUser;
18837 synchronized (mInstallLock) {
18838 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18839 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18840 deleteFlags, "deletePackageX")) {
18841 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18842 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18844 synchronized (mPackages) {
18847 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18849 updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18850 updateInstantAppInstallerLocked(packageName);
18856 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18857 info.sendPackageRemovedBroadcasts(killApp);
18858 info.sendSystemPackageUpdatedBroadcasts();
18859 info.sendSystemPackageAppearedBroadcasts();
18861 // Force a gc here.
18862 Runtime.getRuntime().gc();
18863 // Delete the resources here after sending the broadcast to let
18864 // other processes clean up before deleting resources.
18865 if (info.args != null) {
18866 synchronized (mInstallLock) {
18867 info.args.doPostDeleteLI(true);
18871 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18874 static class PackageRemovedInfo {
18875 final PackageSender packageSender;
18876 String removedPackage;
18877 String installerPackageName;
18879 int removedAppId = -1;
18881 int[] removedUsers = null;
18882 int[] broadcastUsers = null;
18883 SparseArray<Integer> installReasons;
18884 boolean isRemovedPackageSystemUpdate = false;
18886 boolean dataRemoved;
18887 boolean removedForAllUsers;
18888 boolean isStaticSharedLib;
18889 // Clean up resources deleted packages.
18890 InstallArgs args = null;
18891 ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18892 ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18894 PackageRemovedInfo(PackageSender packageSender) {
18895 this.packageSender = packageSender;
18898 void sendPackageRemovedBroadcasts(boolean killApp) {
18899 sendPackageRemovedBroadcastInternal(killApp);
18900 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18901 for (int i = 0; i < childCount; i++) {
18902 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18903 childInfo.sendPackageRemovedBroadcastInternal(killApp);
18907 void sendSystemPackageUpdatedBroadcasts() {
18908 if (isRemovedPackageSystemUpdate) {
18909 sendSystemPackageUpdatedBroadcastsInternal();
18910 final int childCount = (removedChildPackages != null)
18911 ? removedChildPackages.size() : 0;
18912 for (int i = 0; i < childCount; i++) {
18913 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18914 if (childInfo.isRemovedPackageSystemUpdate) {
18915 childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18921 void sendSystemPackageAppearedBroadcasts() {
18922 final int packageCount = (appearedChildPackages != null)
18923 ? appearedChildPackages.size() : 0;
18924 for (int i = 0; i < packageCount; i++) {
18925 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18926 packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18927 true, UserHandle.getAppId(installedInfo.uid),
18928 installedInfo.newUsers);
18932 private void sendSystemPackageUpdatedBroadcastsInternal() {
18933 Bundle extras = new Bundle(2);
18934 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18935 extras.putBoolean(Intent.EXTRA_REPLACING, true);
18936 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18937 removedPackage, extras, 0, null /*targetPackage*/, null, null);
18938 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18939 removedPackage, extras, 0, null /*targetPackage*/, null, null);
18940 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18941 null, null, 0, removedPackage, null, null);
18942 if (installerPackageName != null) {
18943 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18944 removedPackage, extras, 0 /*flags*/,
18945 installerPackageName, null, null);
18946 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18947 removedPackage, extras, 0 /*flags*/,
18948 installerPackageName, null, null);
18952 private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18953 // Don't send static shared library removal broadcasts as these
18954 // libs are visible only the the apps that depend on them an one
18955 // cannot remove the library if it has a dependency.
18956 if (isStaticSharedLib) {
18959 Bundle extras = new Bundle(2);
18960 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18961 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18962 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18963 if (isUpdate || isRemovedPackageSystemUpdate) {
18964 extras.putBoolean(Intent.EXTRA_REPLACING, true);
18966 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18967 if (removedPackage != null) {
18968 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18969 removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18970 if (installerPackageName != null) {
18971 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18972 removedPackage, extras, 0 /*flags*/,
18973 installerPackageName, null, broadcastUsers);
18975 if (dataRemoved && !isRemovedPackageSystemUpdate) {
18976 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18977 removedPackage, extras,
18978 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18979 null, null, broadcastUsers);
18982 if (removedAppId >= 0) {
18983 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras,
18984 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers);
18988 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18989 removedUsers = userIds;
18990 if (removedUsers == null) {
18991 broadcastUsers = null;
18995 broadcastUsers = EMPTY_INT_ARRAY;
18996 for (int i = userIds.length - 1; i >= 0; --i) {
18997 final int userId = userIds[i];
18998 if (deletedPackageSetting.getInstantApp(userId)) {
19001 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19007 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19008 * flag is not set, the data directory is removed as well.
19009 * make sure this flag is set for partially installed apps. If not its meaningless to
19010 * delete a partially installed application.
19012 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19013 PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19014 String packageName = ps.name;
19015 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19016 // Retrieve object to delete permissions for shared user later on
19017 final PackageParser.Package deletedPkg;
19018 final PackageSetting deletedPs;
19020 synchronized (mPackages) {
19021 deletedPkg = mPackages.get(packageName);
19022 deletedPs = mSettings.mPackages.get(packageName);
19023 if (outInfo != null) {
19024 outInfo.removedPackage = packageName;
19025 outInfo.installerPackageName = ps.installerPackageName;
19026 outInfo.isStaticSharedLib = deletedPkg != null
19027 && deletedPkg.staticSharedLibName != null;
19028 outInfo.populateUsers(deletedPs == null ? null
19029 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19033 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19035 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19036 final PackageParser.Package resolvedPkg;
19037 if (deletedPkg != null) {
19038 resolvedPkg = deletedPkg;
19040 // We don't have a parsed package when it lives on an ejected
19041 // adopted storage device, so fake something together
19042 resolvedPkg = new PackageParser.Package(ps.name);
19043 resolvedPkg.setVolumeUuid(ps.volumeUuid);
19045 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19046 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19047 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19048 if (outInfo != null) {
19049 outInfo.dataRemoved = true;
19051 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19054 int removedAppId = -1;
19057 synchronized (mPackages) {
19058 boolean installedStateChanged = false;
19059 if (deletedPs != null) {
19060 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19061 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19062 clearDefaultBrowserIfNeeded(packageName);
19063 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19064 removedAppId = mSettings.removePackageLPw(packageName);
19065 if (outInfo != null) {
19066 outInfo.removedAppId = removedAppId;
19068 updatePermissionsLPw(deletedPs.name, null, 0);
19069 if (deletedPs.sharedUser != null) {
19070 // Remove permissions associated with package. Since runtime
19071 // permissions are per user we have to kill the removed package
19072 // or packages running under the shared user of the removed
19073 // package if revoking the permissions requested only by the removed
19074 // package is successful and this causes a change in gids.
19075 for (int userId : UserManagerService.getInstance().getUserIds()) {
19076 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19078 if (userIdToKill == UserHandle.USER_ALL
19079 || userIdToKill >= UserHandle.USER_SYSTEM) {
19080 // If gids changed for this user, kill all affected packages.
19081 mHandler.post(new Runnable() {
19083 public void run() {
19084 // This has to happen with no lock held.
19085 killApplication(deletedPs.name, deletedPs.appId,
19086 KILL_APP_REASON_GIDS_CHANGED);
19093 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19095 // make sure to preserve per-user disabled state if this removal was just
19096 // a downgrade of a system app to the factory package
19097 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19098 if (DEBUG_REMOVE) {
19099 Slog.d(TAG, "Propagating install state across downgrade");
19101 for (int userId : allUserHandles) {
19102 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19103 if (DEBUG_REMOVE) {
19104 Slog.d(TAG, " user " + userId + " => " + installed);
19106 if (installed != ps.getInstalled(userId)) {
19107 installedStateChanged = true;
19109 ps.setInstalled(installed, userId);
19113 // can downgrade to reader
19114 if (writeSettings) {
19115 // Save settings now
19116 mSettings.writeLPr();
19118 if (installedStateChanged) {
19119 mSettings.writeKernelMappingLPr(ps);
19122 if (removedAppId != -1) {
19123 // A user ID was deleted here. Go through all users and remove it
19125 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19129 static boolean locationIsPrivileged(File path) {
19131 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19132 .getCanonicalPath();
19133 return path.getCanonicalPath().startsWith(privilegedAppDir);
19134 } catch (IOException e) {
19135 Slog.e(TAG, "Unable to access code path " + path);
19141 * Tries to delete system package.
19143 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19144 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19145 boolean writeSettings) {
19146 if (deletedPs.parentPackageName != null) {
19147 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19151 final boolean applyUserRestrictions
19152 = (allUserHandles != null) && (outInfo.origUsers != null);
19153 final PackageSetting disabledPs;
19154 // Confirm if the system package has been updated
19155 // An updated system app can be deleted. This will also have to restore
19156 // the system pkg from system partition
19158 synchronized (mPackages) {
19159 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19162 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19163 + " disabledPs=" + disabledPs);
19165 if (disabledPs == null) {
19166 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19168 } else if (DEBUG_REMOVE) {
19169 Slog.d(TAG, "Deleting system pkg from data partition");
19172 if (DEBUG_REMOVE) {
19173 if (applyUserRestrictions) {
19174 Slog.d(TAG, "Remembering install states:");
19175 for (int userId : allUserHandles) {
19176 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19177 Slog.d(TAG, " u=" + userId + " inst=" + finstalled);
19182 // Delete the updated package
19183 outInfo.isRemovedPackageSystemUpdate = true;
19184 if (outInfo.removedChildPackages != null) {
19185 final int childCount = (deletedPs.childPackageNames != null)
19186 ? deletedPs.childPackageNames.size() : 0;
19187 for (int i = 0; i < childCount; i++) {
19188 String childPackageName = deletedPs.childPackageNames.get(i);
19189 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19190 .contains(childPackageName)) {
19191 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19193 if (childInfo != null) {
19194 childInfo.isRemovedPackageSystemUpdate = true;
19200 if (disabledPs.versionCode < deletedPs.versionCode) {
19201 // Delete data for downgrades
19202 flags &= ~PackageManager.DELETE_KEEP_DATA;
19204 // Preserve data by setting flag
19205 flags |= PackageManager.DELETE_KEEP_DATA;
19208 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19209 outInfo, writeSettings, disabledPs.pkg);
19215 synchronized (mPackages) {
19216 // Reinstate the old system package
19217 enableSystemPackageLPw(disabledPs.pkg);
19218 // Remove any native libraries from the upgraded package.
19219 removeNativeBinariesLI(deletedPs);
19222 // Install the system package
19223 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19224 int parseFlags = mDefParseFlags
19225 | PackageParser.PARSE_MUST_BE_APK
19226 | PackageParser.PARSE_IS_SYSTEM
19227 | PackageParser.PARSE_IS_SYSTEM_DIR;
19228 if (locationIsPrivileged(disabledPs.codePath)) {
19229 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19232 final PackageParser.Package newPkg;
19234 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19235 0 /* currentTime */, null);
19236 } catch (PackageManagerException e) {
19237 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19243 // update shared libraries for the newly re-installed system package
19244 updateSharedLibrariesLPr(newPkg, null);
19245 } catch (PackageManagerException e) {
19246 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19249 prepareAppDataAfterInstallLIF(newPkg);
19252 synchronized (mPackages) {
19253 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19255 // Propagate the permissions state as we do not want to drop on the floor
19256 // runtime permissions. The update permissions method below will take
19257 // care of removing obsolete permissions and grant install permissions.
19258 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19259 updatePermissionsLPw(newPkg.packageName, newPkg,
19260 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19262 if (applyUserRestrictions) {
19263 boolean installedStateChanged = false;
19264 if (DEBUG_REMOVE) {
19265 Slog.d(TAG, "Propagating install state across reinstall");
19267 for (int userId : allUserHandles) {
19268 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19269 if (DEBUG_REMOVE) {
19270 Slog.d(TAG, " user " + userId + " => " + installed);
19272 if (installed != ps.getInstalled(userId)) {
19273 installedStateChanged = true;
19275 ps.setInstalled(installed, userId);
19277 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19279 // Regardless of writeSettings we need to ensure that this restriction
19280 // state propagation is persisted
19281 mSettings.writeAllUsersPackageRestrictionsLPr();
19282 if (installedStateChanged) {
19283 mSettings.writeKernelMappingLPr(ps);
19286 // can downgrade to reader here
19287 if (writeSettings) {
19288 mSettings.writeLPr();
19294 private boolean deleteInstalledPackageLIF(PackageSetting ps,
19295 boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19296 PackageRemovedInfo outInfo, boolean writeSettings,
19297 PackageParser.Package replacingPackage) {
19298 synchronized (mPackages) {
19299 if (outInfo != null) {
19300 outInfo.uid = ps.appId;
19303 if (outInfo != null && outInfo.removedChildPackages != null) {
19304 final int childCount = (ps.childPackageNames != null)
19305 ? ps.childPackageNames.size() : 0;
19306 for (int i = 0; i < childCount; i++) {
19307 String childPackageName = ps.childPackageNames.get(i);
19308 PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19309 if (childPs == null) {
19312 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19314 if (childInfo != null) {
19315 childInfo.uid = childPs.appId;
19321 // Delete package data from internal structures and also remove data if flag is set
19322 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19324 // Delete the child packages data
19325 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19326 for (int i = 0; i < childCount; i++) {
19327 PackageSetting childPs;
19328 synchronized (mPackages) {
19329 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19331 if (childPs != null) {
19332 PackageRemovedInfo childOutInfo = (outInfo != null
19333 && outInfo.removedChildPackages != null)
19334 ? outInfo.removedChildPackages.get(childPs.name) : null;
19335 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19336 && (replacingPackage != null
19337 && !replacingPackage.hasChildPackage(childPs.name))
19338 ? flags & ~DELETE_KEEP_DATA : flags;
19339 removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19340 deleteFlags, writeSettings);
19344 // Delete application code and resources only for parent packages
19345 if (ps.parentPackageName == null) {
19346 if (deleteCodeAndResources && (outInfo != null)) {
19347 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19348 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19349 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19357 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19359 mContext.enforceCallingOrSelfPermission(
19360 android.Manifest.permission.DELETE_PACKAGES, null);
19361 synchronized (mPackages) {
19362 // Cannot block uninstall of static shared libs as they are
19363 // considered a part of the using app (emulating static linking).
19364 // Also static libs are installed always on internal storage.
19365 PackageParser.Package pkg = mPackages.get(packageName);
19366 if (pkg != null && pkg.staticSharedLibName != null) {
19367 Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19368 + " providing static shared library: " + pkg.staticSharedLibName);
19371 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19372 mSettings.writePackageRestrictionsLPr(userId);
19378 public boolean getBlockUninstallForUser(String packageName, int userId) {
19379 synchronized (mPackages) {
19380 final PackageSetting ps = mSettings.mPackages.get(packageName);
19381 if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19384 return mSettings.getBlockUninstallLPr(userId, packageName);
19389 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19390 enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19391 synchronized (mPackages) {
19392 PackageSetting ps = mSettings.mPackages.get(packageName);
19394 Log.w(TAG, "Package doesn't exist: " + packageName);
19397 if (systemUserApp) {
19398 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19400 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19402 mSettings.writeLPr();
19408 * This method handles package deletion in general
19410 private boolean deletePackageLIF(String packageName, UserHandle user,
19411 boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19412 PackageRemovedInfo outInfo, boolean writeSettings,
19413 PackageParser.Package replacingPackage) {
19414 if (packageName == null) {
19415 Slog.w(TAG, "Attempt to delete null packageName.");
19419 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19422 synchronized (mPackages) {
19423 ps = mSettings.mPackages.get(packageName);
19425 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19429 if (ps.parentPackageName != null && (!isSystemApp(ps)
19430 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19431 if (DEBUG_REMOVE) {
19432 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19433 + ((user == null) ? UserHandle.USER_ALL : user));
19435 final int removedUserId = (user != null) ? user.getIdentifier()
19436 : UserHandle.USER_ALL;
19437 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19440 markPackageUninstalledForUserLPw(ps, user);
19441 scheduleWritePackageRestrictionsLocked(user);
19446 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19447 && user.getIdentifier() != UserHandle.USER_ALL)) {
19448 // The caller is asking that the package only be deleted for a single
19449 // user. To do this, we just mark its uninstalled state and delete
19450 // its data. If this is a system app, we only allow this to happen if
19451 // they have set the special DELETE_SYSTEM_APP which requests different
19452 // semantics than normal for uninstalling system apps.
19453 markPackageUninstalledForUserLPw(ps, user);
19455 if (!isSystemApp(ps)) {
19456 // Do not uninstall the APK if an app should be cached
19457 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19458 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19459 // Other user still have this package installed, so all
19460 // we need to do is clear this user's data and save that
19461 // it is uninstalled.
19462 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19463 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19466 scheduleWritePackageRestrictionsLocked(user);
19469 // We need to set it back to 'installed' so the uninstall
19470 // broadcasts will be sent correctly.
19471 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19472 ps.setInstalled(true, user.getIdentifier());
19473 mSettings.writeKernelMappingLPr(ps);
19476 // This is a system app, so we assume that the
19477 // other users still have this package installed, so all
19478 // we need to do is clear this user's data and save that
19479 // it is uninstalled.
19480 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19481 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19484 scheduleWritePackageRestrictionsLocked(user);
19489 // If we are deleting a composite package for all users, keep track
19490 // of result for each child.
19491 if (ps.childPackageNames != null && outInfo != null) {
19492 synchronized (mPackages) {
19493 final int childCount = ps.childPackageNames.size();
19494 outInfo.removedChildPackages = new ArrayMap<>(childCount);
19495 for (int i = 0; i < childCount; i++) {
19496 String childPackageName = ps.childPackageNames.get(i);
19497 PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19498 childInfo.removedPackage = childPackageName;
19499 childInfo.installerPackageName = ps.installerPackageName;
19500 outInfo.removedChildPackages.put(childPackageName, childInfo);
19501 PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19502 if (childPs != null) {
19503 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19509 boolean ret = false;
19510 if (isSystemApp(ps)) {
19511 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19512 // When an updated system application is deleted we delete the existing resources
19513 // as well and fall back to existing code in system partition
19514 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19516 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19517 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19518 outInfo, writeSettings, replacingPackage);
19521 // Take a note whether we deleted the package for all users
19522 if (outInfo != null) {
19523 outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19524 if (outInfo.removedChildPackages != null) {
19525 synchronized (mPackages) {
19526 final int childCount = outInfo.removedChildPackages.size();
19527 for (int i = 0; i < childCount; i++) {
19528 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19529 if (childInfo != null) {
19530 childInfo.removedForAllUsers = mPackages.get(
19531 childInfo.removedPackage) == null;
19536 // If we uninstalled an update to a system app there may be some
19537 // child packages that appeared as they are declared in the system
19538 // app but were not declared in the update.
19539 if (isSystemApp(ps)) {
19540 synchronized (mPackages) {
19541 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19542 final int childCount = (updatedPs.childPackageNames != null)
19543 ? updatedPs.childPackageNames.size() : 0;
19544 for (int i = 0; i < childCount; i++) {
19545 String childPackageName = updatedPs.childPackageNames.get(i);
19546 if (outInfo.removedChildPackages == null
19547 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19548 PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19549 if (childPs == null) {
19552 PackageInstalledInfo installRes = new PackageInstalledInfo();
19553 installRes.name = childPackageName;
19554 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19555 installRes.pkg = mPackages.get(childPackageName);
19556 installRes.uid = childPs.pkg.applicationInfo.uid;
19557 if (outInfo.appearedChildPackages == null) {
19558 outInfo.appearedChildPackages = new ArrayMap<>();
19560 outInfo.appearedChildPackages.put(childPackageName, installRes);
19570 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19571 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19572 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19573 for (int nextUserId : userIds) {
19574 if (DEBUG_REMOVE) {
19575 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19577 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19578 false /*installed*/,
19580 true /*notLaunched*/,
19582 false /*suspended*/,
19583 false /*instantApp*/,
19584 null /*lastDisableAppCaller*/,
19585 null /*enabledComponents*/,
19586 null /*disabledComponents*/,
19587 ps.readUserState(nextUserId).domainVerificationStatus,
19588 0, PackageManager.INSTALL_REASON_UNKNOWN);
19590 mSettings.writeKernelMappingLPr(ps);
19593 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19594 PackageRemovedInfo outInfo) {
19595 final PackageParser.Package pkg;
19596 synchronized (mPackages) {
19597 pkg = mPackages.get(ps.name);
19600 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19601 : new int[] {userId};
19602 for (int nextUserId : userIds) {
19603 if (DEBUG_REMOVE) {
19604 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19608 destroyAppDataLIF(pkg, userId,
19609 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19610 destroyAppProfilesLIF(pkg, userId);
19611 clearDefaultBrowserIfNeededForUser(ps.name, userId);
19612 removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19613 schedulePackageCleaning(ps.name, nextUserId, false);
19614 synchronized (mPackages) {
19615 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19616 scheduleWritePackageRestrictionsLocked(nextUserId);
19618 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19622 if (outInfo != null) {
19623 outInfo.removedPackage = ps.name;
19624 outInfo.installerPackageName = ps.installerPackageName;
19625 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19626 outInfo.removedAppId = ps.appId;
19627 outInfo.removedUsers = userIds;
19628 outInfo.broadcastUsers = userIds;
19634 private final class ClearStorageConnection implements ServiceConnection {
19635 IMediaContainerService mContainerService;
19638 public void onServiceConnected(ComponentName name, IBinder service) {
19639 synchronized (this) {
19640 mContainerService = IMediaContainerService.Stub
19641 .asInterface(Binder.allowBlocking(service));
19647 public void onServiceDisconnected(ComponentName name) {
19651 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19652 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19654 final boolean mounted;
19655 if (Environment.isExternalStorageEmulated()) {
19658 final String status = Environment.getExternalStorageState();
19660 mounted = status.equals(Environment.MEDIA_MOUNTED)
19661 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19668 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19670 if (userId == UserHandle.USER_ALL) {
19671 users = sUserManager.getUserIds();
19673 users = new int[] { userId };
19675 final ClearStorageConnection conn = new ClearStorageConnection();
19676 if (mContext.bindServiceAsUser(
19677 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19679 for (int curUser : users) {
19680 long timeout = SystemClock.uptimeMillis() + 5000;
19681 synchronized (conn) {
19683 while (conn.mContainerService == null &&
19684 (now = SystemClock.uptimeMillis()) < timeout) {
19686 conn.wait(timeout - now);
19687 } catch (InterruptedException e) {
19691 if (conn.mContainerService == null) {
19695 final UserEnvironment userEnv = new UserEnvironment(curUser);
19696 clearDirectory(conn.mContainerService,
19697 userEnv.buildExternalStorageAppCacheDirs(packageName));
19699 clearDirectory(conn.mContainerService,
19700 userEnv.buildExternalStorageAppDataDirs(packageName));
19701 clearDirectory(conn.mContainerService,
19702 userEnv.buildExternalStorageAppMediaDirs(packageName));
19706 mContext.unbindService(conn);
19712 public void clearApplicationProfileData(String packageName) {
19713 enforceSystemOrRoot("Only the system can clear all profile data");
19715 final PackageParser.Package pkg;
19716 synchronized (mPackages) {
19717 pkg = mPackages.get(packageName);
19720 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19721 synchronized (mInstallLock) {
19722 clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19728 public void clearApplicationUserData(final String packageName,
19729 final IPackageDataObserver observer, final int userId) {
19730 mContext.enforceCallingOrSelfPermission(
19731 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19733 final int callingUid = Binder.getCallingUid();
19734 enforceCrossUserPermission(callingUid, userId,
19735 true /* requireFullPermission */, false /* checkShell */, "clear application data");
19737 final PackageSetting ps = mSettings.getPackageLPr(packageName);
19738 if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19741 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19742 throw new SecurityException("Cannot clear data for a protected package: "
19745 // Queue up an async operation since the package deletion may take a little while.
19746 mHandler.post(new Runnable() {
19747 public void run() {
19748 mHandler.removeCallbacks(this);
19749 final boolean succeeded;
19750 try (PackageFreezer freezer = freezePackage(packageName,
19751 "clearApplicationUserData")) {
19752 synchronized (mInstallLock) {
19753 succeeded = clearApplicationUserDataLIF(packageName, userId);
19755 clearExternalStorageDataSync(packageName, userId, true);
19756 synchronized (mPackages) {
19757 mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19758 packageName, userId);
19762 // invoke DeviceStorageMonitor's update method to clear any notifications
19763 DeviceStorageMonitorInternal dsm = LocalServices
19764 .getService(DeviceStorageMonitorInternal.class);
19769 if(observer != null) {
19771 observer.onRemoveCompleted(packageName, succeeded);
19772 } catch (RemoteException e) {
19773 Log.i(TAG, "Observer no longer exists.");
19775 } //end if observer
19780 private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19781 if (packageName == null) {
19782 Slog.w(TAG, "Attempt to delete null packageName.");
19786 // Try finding details about the requested package
19787 PackageParser.Package pkg;
19788 synchronized (mPackages) {
19789 pkg = mPackages.get(packageName);
19791 final PackageSetting ps = mSettings.mPackages.get(packageName);
19798 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19802 PackageSetting ps = (PackageSetting) pkg.mExtras;
19803 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19806 clearAppDataLIF(pkg, userId,
19807 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19809 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19810 removeKeystoreDataIfNeeded(userId, appId);
19812 UserManagerInternal umInternal = getUserManagerInternal();
19814 if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19815 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19816 } else if (umInternal.isUserRunning(userId)) {
19817 flags = StorageManager.FLAG_STORAGE_DE;
19821 prepareAppDataContentsLIF(pkg, userId, flags);
19827 * Reverts user permission state changes (permissions and flags) in
19828 * all packages for a given user.
19830 * @param userId The device user for which to do a reset.
19832 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19833 final int packageCount = mPackages.size();
19834 for (int i = 0; i < packageCount; i++) {
19835 PackageParser.Package pkg = mPackages.valueAt(i);
19836 PackageSetting ps = (PackageSetting) pkg.mExtras;
19837 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19841 private void resetNetworkPolicies(int userId) {
19842 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19846 * Reverts user permission state changes (permissions and flags).
19848 * @param ps The package for which to reset.
19849 * @param userId The device user for which to do a reset.
19851 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19852 final PackageSetting ps, final int userId) {
19853 if (ps.pkg == null) {
19857 // These are flags that can change base on user actions.
19858 final int userSettableMask = FLAG_PERMISSION_USER_SET
19859 | FLAG_PERMISSION_USER_FIXED
19860 | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19861 | FLAG_PERMISSION_REVIEW_REQUIRED;
19863 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19864 | FLAG_PERMISSION_POLICY_FIXED;
19866 boolean writeInstallPermissions = false;
19867 boolean writeRuntimePermissions = false;
19869 final int permissionCount = ps.pkg.requestedPermissions.size();
19870 for (int i = 0; i < permissionCount; i++) {
19871 String permission = ps.pkg.requestedPermissions.get(i);
19873 BasePermission bp = mSettings.mPermissions.get(permission);
19878 // If shared user we just reset the state to which only this app contributed.
19879 if (ps.sharedUser != null) {
19880 boolean used = false;
19881 final int packageCount = ps.sharedUser.packages.size();
19882 for (int j = 0; j < packageCount; j++) {
19883 PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19884 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19885 && pkg.pkg.requestedPermissions.contains(permission)) {
19895 PermissionsState permissionsState = ps.getPermissionsState();
19897 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19899 // Always clear the user settable flags.
19900 final boolean hasInstallState = permissionsState.getInstallPermissionState(
19902 // If permission review is enabled and this is a legacy app, mark the
19903 // permission as requiring a review as this is the initial state.
19905 if (mPermissionReviewRequired
19906 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19907 flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19909 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19910 if (hasInstallState) {
19911 writeInstallPermissions = true;
19913 writeRuntimePermissions = true;
19917 // Below is only runtime permission handling.
19918 if (!bp.isRuntime()) {
19922 // Never clobber system or policy.
19923 if ((oldFlags & policyOrSystemFlags) != 0) {
19927 // If this permission was granted by default, make sure it is.
19928 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19929 if (permissionsState.grantRuntimePermission(bp, userId)
19930 != PERMISSION_OPERATION_FAILURE) {
19931 writeRuntimePermissions = true;
19933 // If permission review is enabled the permissions for a legacy apps
19934 // are represented as constantly granted runtime ones, so don't revoke.
19935 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19936 // Otherwise, reset the permission.
19937 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19938 switch (revokeResult) {
19939 case PERMISSION_OPERATION_SUCCESS:
19940 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19941 writeRuntimePermissions = true;
19942 final int appId = ps.appId;
19943 mHandler.post(new Runnable() {
19945 public void run() {
19946 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19954 // Synchronously write as we are taking permissions away.
19955 if (writeRuntimePermissions) {
19956 mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19959 // Synchronously write as we are taking permissions away.
19960 if (writeInstallPermissions) {
19961 mSettings.writeLPr();
19966 * Remove entries from the keystore daemon. Will only remove it if the
19967 * {@code appId} is valid.
19969 private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19974 final KeyStore keyStore = KeyStore.getInstance();
19975 if (keyStore != null) {
19976 if (userId == UserHandle.USER_ALL) {
19977 for (final int individual : sUserManager.getUserIds()) {
19978 keyStore.clearUid(UserHandle.getUid(individual, appId));
19981 keyStore.clearUid(UserHandle.getUid(userId, appId));
19984 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19989 public void deleteApplicationCacheFiles(final String packageName,
19990 final IPackageDataObserver observer) {
19991 final int userId = UserHandle.getCallingUserId();
19992 deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19996 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19997 final IPackageDataObserver observer) {
19998 final int callingUid = Binder.getCallingUid();
19999 mContext.enforceCallingOrSelfPermission(
20000 android.Manifest.permission.DELETE_CACHE_FILES, null);
20001 enforceCrossUserPermission(callingUid, userId,
20002 /* requireFullPermission= */ true, /* checkShell= */ false,
20003 "delete application cache files");
20004 final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20005 android.Manifest.permission.ACCESS_INSTANT_APPS);
20007 final PackageParser.Package pkg;
20008 synchronized (mPackages) {
20009 pkg = mPackages.get(packageName);
20012 // Queue up an async operation since the package deletion may take a little while.
20013 mHandler.post(new Runnable() {
20014 public void run() {
20015 final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20016 boolean doClearData = true;
20018 final boolean targetIsInstantApp =
20019 ps.getInstantApp(UserHandle.getUserId(callingUid));
20020 doClearData = !targetIsInstantApp
20021 || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20024 synchronized (mInstallLock) {
20025 final int flags = StorageManager.FLAG_STORAGE_DE
20026 | StorageManager.FLAG_STORAGE_CE;
20027 // We're only clearing cache files, so we don't care if the
20028 // app is unfrozen and still able to run
20029 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20030 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20032 clearExternalStorageDataSync(packageName, userId, false);
20034 if (observer != null) {
20036 observer.onRemoveCompleted(packageName, true);
20037 } catch (RemoteException e) {
20038 Log.i(TAG, "Observer no longer exists.");
20046 public void getPackageSizeInfo(final String packageName, int userHandle,
20047 final IPackageStatsObserver observer) {
20048 throw new UnsupportedOperationException(
20049 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20052 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20053 final PackageSetting ps;
20054 synchronized (mPackages) {
20055 ps = mSettings.mPackages.get(packageName);
20057 Slog.w(TAG, "Failed to find settings for " + packageName);
20062 final String[] packageNames = { packageName };
20063 final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20064 final String[] codePaths = { ps.codePathString };
20067 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20068 ps.appId, ceDataInodes, codePaths, stats);
20070 // For now, ignore code size of packages on system partition
20071 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20072 stats.codeSize = 0;
20075 // External clients expect these to be tracked separately
20076 stats.dataSize -= stats.cacheSize;
20078 } catch (InstallerException e) {
20079 Slog.w(TAG, String.valueOf(e));
20086 private int getUidTargetSdkVersionLockedLPr(int uid) {
20087 Object obj = mSettings.getUserIdLPr(uid);
20088 if (obj instanceof SharedUserSetting) {
20089 final SharedUserSetting sus = (SharedUserSetting) obj;
20090 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20091 final Iterator<PackageSetting> it = sus.packages.iterator();
20092 while (it.hasNext()) {
20093 final PackageSetting ps = it.next();
20094 if (ps.pkg != null) {
20095 int v = ps.pkg.applicationInfo.targetSdkVersion;
20096 if (v < vers) vers = v;
20100 } else if (obj instanceof PackageSetting) {
20101 final PackageSetting ps = (PackageSetting) obj;
20102 if (ps.pkg != null) {
20103 return ps.pkg.applicationInfo.targetSdkVersion;
20106 return Build.VERSION_CODES.CUR_DEVELOPMENT;
20110 public void addPreferredActivity(IntentFilter filter, int match,
20111 ComponentName[] set, ComponentName activity, int userId) {
20112 addPreferredActivityInternal(filter, match, set, activity, true, userId,
20113 "Adding preferred");
20116 private void addPreferredActivityInternal(IntentFilter filter, int match,
20117 ComponentName[] set, ComponentName activity, boolean always, int userId,
20120 int callingUid = Binder.getCallingUid();
20121 enforceCrossUserPermission(callingUid, userId,
20122 true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20123 if (filter.countActions() == 0) {
20124 Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20127 synchronized (mPackages) {
20128 if (mContext.checkCallingOrSelfPermission(
20129 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20130 != PackageManager.PERMISSION_GRANTED) {
20131 if (getUidTargetSdkVersionLockedLPr(callingUid)
20132 < Build.VERSION_CODES.FROYO) {
20133 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20137 mContext.enforceCallingOrSelfPermission(
20138 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20141 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20142 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20144 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
20145 pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20146 scheduleWritePackageRestrictionsLocked(userId);
20147 postPreferredActivityChangedBroadcast(userId);
20151 private void postPreferredActivityChangedBroadcast(int userId) {
20152 mHandler.post(() -> {
20153 final IActivityManager am = ActivityManager.getService();
20158 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20159 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20161 am.broadcastIntent(null, intent, null, null,
20162 0, null, null, null, android.app.AppOpsManager.OP_NONE,
20163 null, false, false, userId);
20164 } catch (RemoteException e) {
20170 public void replacePreferredActivity(IntentFilter filter, int match,
20171 ComponentName[] set, ComponentName activity, int userId) {
20172 if (filter.countActions() != 1) {
20173 throw new IllegalArgumentException(
20174 "replacePreferredActivity expects filter to have only 1 action.");
20176 if (filter.countDataAuthorities() != 0
20177 || filter.countDataPaths() != 0
20178 || filter.countDataSchemes() > 1
20179 || filter.countDataTypes() != 0) {
20180 throw new IllegalArgumentException(
20181 "replacePreferredActivity expects filter to have no data authorities, " +
20182 "paths, or types; and at most one scheme.");
20185 final int callingUid = Binder.getCallingUid();
20186 enforceCrossUserPermission(callingUid, userId,
20187 true /* requireFullPermission */, false /* checkShell */,
20188 "replace preferred activity");
20189 synchronized (mPackages) {
20190 if (mContext.checkCallingOrSelfPermission(
20191 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20192 != PackageManager.PERMISSION_GRANTED) {
20193 if (getUidTargetSdkVersionLockedLPr(callingUid)
20194 < Build.VERSION_CODES.FROYO) {
20195 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20196 + Binder.getCallingUid());
20199 mContext.enforceCallingOrSelfPermission(
20200 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20203 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20205 // Get all of the existing entries that exactly match this filter.
20206 ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20207 if (existing != null && existing.size() == 1) {
20208 PreferredActivity cur = existing.get(0);
20209 if (DEBUG_PREFERRED) {
20210 Slog.i(TAG, "Checking replace of preferred:");
20211 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
20212 if (!cur.mPref.mAlways) {
20213 Slog.i(TAG, " -- CUR; not mAlways!");
20215 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch);
20216 Slog.i(TAG, " -- CUR: mSet="
20217 + Arrays.toString(cur.mPref.mSetComponents));
20218 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent);
20219 Slog.i(TAG, " -- NEW: mMatch="
20220 + (match&IntentFilter.MATCH_CATEGORY_MASK));
20221 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set));
20222 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString());
20225 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20226 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20227 && cur.mPref.sameSet(set)) {
20228 // Setting the preferred activity to what it happens to be already
20229 if (DEBUG_PREFERRED) {
20230 Slog.i(TAG, "Replacing with same preferred activity "
20231 + cur.mPref.mShortComponent + " for user "
20233 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
20239 if (existing != null) {
20240 if (DEBUG_PREFERRED) {
20241 Slog.i(TAG, existing.size() + " existing preferred matches for:");
20242 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
20244 for (int i = 0; i < existing.size(); i++) {
20245 PreferredActivity pa = existing.get(i);
20246 if (DEBUG_PREFERRED) {
20247 Slog.i(TAG, "Removing existing preferred activity "
20248 + pa.mPref.mComponent + ":");
20249 pa.dump(new LogPrinter(Log.INFO, TAG), " ");
20251 pir.removeFilter(pa);
20255 addPreferredActivityInternal(filter, match, set, activity, true, userId,
20256 "Replacing preferred");
20261 public void clearPackagePreferredActivities(String packageName) {
20262 final int callingUid = Binder.getCallingUid();
20263 if (getInstantAppPackageName(callingUid) != null) {
20267 synchronized (mPackages) {
20268 PackageParser.Package pkg = mPackages.get(packageName);
20269 if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20270 if (mContext.checkCallingOrSelfPermission(
20271 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20272 != PackageManager.PERMISSION_GRANTED) {
20273 if (getUidTargetSdkVersionLockedLPr(callingUid)
20274 < Build.VERSION_CODES.FROYO) {
20275 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20279 mContext.enforceCallingOrSelfPermission(
20280 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20283 final PackageSetting ps = mSettings.getPackageLPr(packageName);
20285 && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20288 int user = UserHandle.getCallingUserId();
20289 if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20290 scheduleWritePackageRestrictionsLocked(user);
20295 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20296 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20297 ArrayList<PreferredActivity> removed = null;
20298 boolean changed = false;
20299 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20300 final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20301 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20302 if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20305 Iterator<PreferredActivity> it = pir.filterIterator();
20306 while (it.hasNext()) {
20307 PreferredActivity pa = it.next();
20308 // Mark entry for removal only if it matches the package name
20309 // and the entry is of type "always".
20310 if (packageName == null ||
20311 (pa.mPref.mComponent.getPackageName().equals(packageName)
20312 && pa.mPref.mAlways)) {
20313 if (removed == null) {
20314 removed = new ArrayList<PreferredActivity>();
20319 if (removed != null) {
20320 for (int j=0; j<removed.size(); j++) {
20321 PreferredActivity pa = removed.get(j);
20322 pir.removeFilter(pa);
20328 postPreferredActivityChangedBroadcast(userId);
20333 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20334 private void clearIntentFilterVerificationsLPw(int userId) {
20335 final int packageCount = mPackages.size();
20336 for (int i = 0; i < packageCount; i++) {
20337 PackageParser.Package pkg = mPackages.valueAt(i);
20338 clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20342 /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20343 void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20344 if (userId == UserHandle.USER_ALL) {
20345 if (mSettings.removeIntentFilterVerificationLPw(packageName,
20346 sUserManager.getUserIds())) {
20347 for (int oneUserId : sUserManager.getUserIds()) {
20348 scheduleWritePackageRestrictionsLocked(oneUserId);
20352 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20353 scheduleWritePackageRestrictionsLocked(userId);
20358 /** Clears state for all users, and touches intent filter verification policy */
20359 void clearDefaultBrowserIfNeeded(String packageName) {
20360 for (int oneUserId : sUserManager.getUserIds()) {
20361 clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20365 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20366 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20367 if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20368 if (packageName.equals(defaultBrowserPackageName)) {
20369 setDefaultBrowserPackageName(null, userId);
20375 public void resetApplicationPreferences(int userId) {
20376 mContext.enforceCallingOrSelfPermission(
20377 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20378 final long identity = Binder.clearCallingIdentity();
20381 synchronized (mPackages) {
20382 clearPackagePreferredActivitiesLPw(null, userId);
20383 mSettings.applyDefaultPreferredAppsLPw(this, userId);
20384 // TODO: We have to reset the default SMS and Phone. This requires
20385 // significant refactoring to keep all default apps in the package
20386 // manager (cleaner but more work) or have the services provide
20387 // callbacks to the package manager to request a default app reset.
20388 applyFactoryDefaultBrowserLPw(userId);
20389 clearIntentFilterVerificationsLPw(userId);
20390 primeDomainVerificationsLPw(userId);
20391 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20392 scheduleWritePackageRestrictionsLocked(userId);
20394 resetNetworkPolicies(userId);
20396 Binder.restoreCallingIdentity(identity);
20401 public int getPreferredActivities(List<IntentFilter> outFilters,
20402 List<ComponentName> outActivities, String packageName) {
20403 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20407 final int userId = UserHandle.getCallingUserId();
20409 synchronized (mPackages) {
20410 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20412 final Iterator<PreferredActivity> it = pir.filterIterator();
20413 while (it.hasNext()) {
20414 final PreferredActivity pa = it.next();
20415 if (packageName == null
20416 || (pa.mPref.mComponent.getPackageName().equals(packageName)
20417 && pa.mPref.mAlways)) {
20418 if (outFilters != null) {
20419 outFilters.add(new IntentFilter(pa));
20421 if (outActivities != null) {
20422 outActivities.add(pa.mPref.mComponent);
20433 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20435 int callingUid = Binder.getCallingUid();
20436 if (callingUid != Process.SYSTEM_UID) {
20437 throw new SecurityException(
20438 "addPersistentPreferredActivity can only be run by the system");
20440 if (filter.countActions() == 0) {
20441 Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20444 synchronized (mPackages) {
20445 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20447 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
20448 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20449 new PersistentPreferredActivity(filter, activity));
20450 scheduleWritePackageRestrictionsLocked(userId);
20451 postPreferredActivityChangedBroadcast(userId);
20456 public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20457 int callingUid = Binder.getCallingUid();
20458 if (callingUid != Process.SYSTEM_UID) {
20459 throw new SecurityException(
20460 "clearPackagePersistentPreferredActivities can only be run by the system");
20462 ArrayList<PersistentPreferredActivity> removed = null;
20463 boolean changed = false;
20464 synchronized (mPackages) {
20465 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20466 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20467 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20469 if (userId != thisUserId) {
20472 Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20473 while (it.hasNext()) {
20474 PersistentPreferredActivity ppa = it.next();
20475 // Mark entry for removal only if it matches the package name.
20476 if (ppa.mComponent.getPackageName().equals(packageName)) {
20477 if (removed == null) {
20478 removed = new ArrayList<PersistentPreferredActivity>();
20483 if (removed != null) {
20484 for (int j=0; j<removed.size(); j++) {
20485 PersistentPreferredActivity ppa = removed.get(j);
20486 ppir.removeFilter(ppa);
20493 scheduleWritePackageRestrictionsLocked(userId);
20494 postPreferredActivityChangedBroadcast(userId);
20500 * Common machinery for picking apart a restored XML blob and passing
20501 * it to a caller-supplied functor to be applied to the running system.
20503 private void restoreFromXml(XmlPullParser parser, int userId,
20504 String expectedStartTag, BlobXmlRestorer functor)
20505 throws IOException, XmlPullParserException {
20507 while ((type = parser.next()) != XmlPullParser.START_TAG
20508 && type != XmlPullParser.END_DOCUMENT) {
20510 if (type != XmlPullParser.START_TAG) {
20511 // oops didn't find a start tag?!
20512 if (DEBUG_BACKUP) {
20513 Slog.e(TAG, "Didn't find start tag during restore");
20517 Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20518 // this is supposed to be TAG_PREFERRED_BACKUP
20519 if (!expectedStartTag.equals(parser.getName())) {
20520 if (DEBUG_BACKUP) {
20521 Slog.e(TAG, "Found unexpected tag " + parser.getName());
20526 // skip interfering stuff, then we're aligned with the backing implementation
20527 while ((type = parser.next()) == XmlPullParser.TEXT) { }
20528 Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20529 functor.apply(parser, userId);
20532 private interface BlobXmlRestorer {
20533 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20537 * Non-Binder method, support for the backup/restore mechanism: write the
20538 * full set of preferred activities in its canonical XML format. Returns the
20539 * XML output as a byte array, or null if there is none.
20542 public byte[] getPreferredActivityBackup(int userId) {
20543 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20544 throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20547 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20549 final XmlSerializer serializer = new FastXmlSerializer();
20550 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20551 serializer.startDocument(null, true);
20552 serializer.startTag(null, TAG_PREFERRED_BACKUP);
20554 synchronized (mPackages) {
20555 mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20558 serializer.endTag(null, TAG_PREFERRED_BACKUP);
20559 serializer.endDocument();
20560 serializer.flush();
20561 } catch (Exception e) {
20562 if (DEBUG_BACKUP) {
20563 Slog.e(TAG, "Unable to write preferred activities for backup", e);
20568 return dataStream.toByteArray();
20572 public void restorePreferredActivities(byte[] backup, int userId) {
20573 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20574 throw new SecurityException("Only the system may call restorePreferredActivities()");
20578 final XmlPullParser parser = Xml.newPullParser();
20579 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20580 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20581 new BlobXmlRestorer() {
20583 public void apply(XmlPullParser parser, int userId)
20584 throws XmlPullParserException, IOException {
20585 synchronized (mPackages) {
20586 mSettings.readPreferredActivitiesLPw(parser, userId);
20590 } catch (Exception e) {
20591 if (DEBUG_BACKUP) {
20592 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20598 * Non-Binder method, support for the backup/restore mechanism: write the
20599 * default browser (etc) settings in its canonical XML format. Returns the default
20600 * browser XML representation as a byte array, or null if there is none.
20603 public byte[] getDefaultAppsBackup(int userId) {
20604 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20605 throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20608 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20610 final XmlSerializer serializer = new FastXmlSerializer();
20611 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20612 serializer.startDocument(null, true);
20613 serializer.startTag(null, TAG_DEFAULT_APPS);
20615 synchronized (mPackages) {
20616 mSettings.writeDefaultAppsLPr(serializer, userId);
20619 serializer.endTag(null, TAG_DEFAULT_APPS);
20620 serializer.endDocument();
20621 serializer.flush();
20622 } catch (Exception e) {
20623 if (DEBUG_BACKUP) {
20624 Slog.e(TAG, "Unable to write default apps for backup", e);
20629 return dataStream.toByteArray();
20633 public void restoreDefaultApps(byte[] backup, int userId) {
20634 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20635 throw new SecurityException("Only the system may call restoreDefaultApps()");
20639 final XmlPullParser parser = Xml.newPullParser();
20640 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20641 restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20642 new BlobXmlRestorer() {
20644 public void apply(XmlPullParser parser, int userId)
20645 throws XmlPullParserException, IOException {
20646 synchronized (mPackages) {
20647 mSettings.readDefaultAppsLPw(parser, userId);
20651 } catch (Exception e) {
20652 if (DEBUG_BACKUP) {
20653 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20659 public byte[] getIntentFilterVerificationBackup(int userId) {
20660 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20661 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20664 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20666 final XmlSerializer serializer = new FastXmlSerializer();
20667 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20668 serializer.startDocument(null, true);
20669 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20671 synchronized (mPackages) {
20672 mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20675 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20676 serializer.endDocument();
20677 serializer.flush();
20678 } catch (Exception e) {
20679 if (DEBUG_BACKUP) {
20680 Slog.e(TAG, "Unable to write default apps for backup", e);
20685 return dataStream.toByteArray();
20689 public void restoreIntentFilterVerification(byte[] backup, int userId) {
20690 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20691 throw new SecurityException("Only the system may call restorePreferredActivities()");
20695 final XmlPullParser parser = Xml.newPullParser();
20696 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20697 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20698 new BlobXmlRestorer() {
20700 public void apply(XmlPullParser parser, int userId)
20701 throws XmlPullParserException, IOException {
20702 synchronized (mPackages) {
20703 mSettings.readAllDomainVerificationsLPr(parser, userId);
20704 mSettings.writeLPr();
20708 } catch (Exception e) {
20709 if (DEBUG_BACKUP) {
20710 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20716 public byte[] getPermissionGrantBackup(int userId) {
20717 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20718 throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20721 ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20723 final XmlSerializer serializer = new FastXmlSerializer();
20724 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20725 serializer.startDocument(null, true);
20726 serializer.startTag(null, TAG_PERMISSION_BACKUP);
20728 synchronized (mPackages) {
20729 serializeRuntimePermissionGrantsLPr(serializer, userId);
20732 serializer.endTag(null, TAG_PERMISSION_BACKUP);
20733 serializer.endDocument();
20734 serializer.flush();
20735 } catch (Exception e) {
20736 if (DEBUG_BACKUP) {
20737 Slog.e(TAG, "Unable to write default apps for backup", e);
20742 return dataStream.toByteArray();
20746 public void restorePermissionGrants(byte[] backup, int userId) {
20747 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20748 throw new SecurityException("Only the system may call restorePermissionGrants()");
20752 final XmlPullParser parser = Xml.newPullParser();
20753 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20754 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20755 new BlobXmlRestorer() {
20757 public void apply(XmlPullParser parser, int userId)
20758 throws XmlPullParserException, IOException {
20759 synchronized (mPackages) {
20760 processRestoredPermissionGrantsLPr(parser, userId);
20764 } catch (Exception e) {
20765 if (DEBUG_BACKUP) {
20766 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20771 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20772 throws IOException {
20773 serializer.startTag(null, TAG_ALL_GRANTS);
20775 final int N = mSettings.mPackages.size();
20776 for (int i = 0; i < N; i++) {
20777 final PackageSetting ps = mSettings.mPackages.valueAt(i);
20778 boolean pkgGrantsKnown = false;
20780 PermissionsState packagePerms = ps.getPermissionsState();
20782 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20783 final int grantFlags = state.getFlags();
20784 // only look at grants that are not system/policy fixed
20785 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20786 final boolean isGranted = state.isGranted();
20787 // And only back up the user-twiddled state bits
20788 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20789 final String packageName = mSettings.mPackages.keyAt(i);
20790 if (!pkgGrantsKnown) {
20791 serializer.startTag(null, TAG_GRANT);
20792 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20793 pkgGrantsKnown = true;
20796 final boolean userSet =
20797 (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20798 final boolean userFixed =
20799 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20800 final boolean revoke =
20801 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20803 serializer.startTag(null, TAG_PERMISSION);
20804 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20806 serializer.attribute(null, ATTR_IS_GRANTED, "true");
20809 serializer.attribute(null, ATTR_USER_SET, "true");
20812 serializer.attribute(null, ATTR_USER_FIXED, "true");
20815 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20817 serializer.endTag(null, TAG_PERMISSION);
20822 if (pkgGrantsKnown) {
20823 serializer.endTag(null, TAG_GRANT);
20827 serializer.endTag(null, TAG_ALL_GRANTS);
20830 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20831 throws XmlPullParserException, IOException {
20832 String pkgName = null;
20833 int outerDepth = parser.getDepth();
20835 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20836 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20837 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20841 final String tagName = parser.getName();
20842 if (tagName.equals(TAG_GRANT)) {
20843 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20844 if (DEBUG_BACKUP) {
20845 Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20847 } else if (tagName.equals(TAG_PERMISSION)) {
20849 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20850 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20852 int newFlagSet = 0;
20853 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20854 newFlagSet |= FLAG_PERMISSION_USER_SET;
20856 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20857 newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20859 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20860 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20862 if (DEBUG_BACKUP) {
20863 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName
20864 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20866 final PackageSetting ps = mSettings.mPackages.get(pkgName);
20868 // Already installed so we apply the grant immediately
20869 if (DEBUG_BACKUP) {
20870 Slog.v(TAG, " + already installed; applying");
20872 PermissionsState perms = ps.getPermissionsState();
20873 BasePermission bp = mSettings.mPermissions.get(permName);
20876 perms.grantRuntimePermission(bp, userId);
20878 if (newFlagSet != 0) {
20879 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20883 // Need to wait for post-restore install to apply the grant
20884 if (DEBUG_BACKUP) {
20885 Slog.v(TAG, " - not yet installed; saving for later");
20887 mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20888 isGranted, newFlagSet, userId);
20891 PackageManagerService.reportSettingsProblem(Log.WARN,
20892 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20893 XmlUtils.skipCurrentTag(parser);
20897 scheduleWriteSettingsLocked();
20898 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20902 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20903 int sourceUserId, int targetUserId, int flags) {
20904 mContext.enforceCallingOrSelfPermission(
20905 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20906 int callingUid = Binder.getCallingUid();
20907 enforceOwnerRights(ownerPackage, callingUid);
20908 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20909 if (intentFilter.countActions() == 0) {
20910 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20913 synchronized (mPackages) {
20914 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20915 ownerPackage, targetUserId, flags);
20916 CrossProfileIntentResolver resolver =
20917 mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20918 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20919 // We have all those whose filter is equal. Now checking if the rest is equal as well.
20920 if (existing != null) {
20921 int size = existing.size();
20922 for (int i = 0; i < size; i++) {
20923 if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20928 resolver.addFilter(newFilter);
20929 scheduleWritePackageRestrictionsLocked(sourceUserId);
20934 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20935 mContext.enforceCallingOrSelfPermission(
20936 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20937 final int callingUid = Binder.getCallingUid();
20938 enforceOwnerRights(ownerPackage, callingUid);
20939 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20940 synchronized (mPackages) {
20941 CrossProfileIntentResolver resolver =
20942 mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20943 ArraySet<CrossProfileIntentFilter> set =
20944 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20945 for (CrossProfileIntentFilter filter : set) {
20946 if (filter.getOwnerPackage().equals(ownerPackage)) {
20947 resolver.removeFilter(filter);
20950 scheduleWritePackageRestrictionsLocked(sourceUserId);
20954 // Enforcing that callingUid is owning pkg on userId
20955 private void enforceOwnerRights(String pkg, int callingUid) {
20956 // The system owns everything.
20957 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20960 final int callingUserId = UserHandle.getUserId(callingUid);
20961 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20963 throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20966 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20967 throw new SecurityException("Calling uid " + callingUid
20968 + " does not own package " + pkg);
20973 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20974 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20977 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20980 public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20981 UserManagerService ums = UserManagerService.getInstance();
20983 final UserInfo parent = ums.getProfileParent(userId);
20984 final int launcherUid = (parent != null) ? parent.id : userId;
20985 final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20986 if (launcherComponent != null) {
20987 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20988 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20989 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20990 .setPackage(launcherComponent.getPackageName());
20991 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20997 * Report the 'Home' activity which is currently set as "always use this one". If non is set
20998 * then reports the most likely home activity or null if there are more than one.
21000 private ComponentName getDefaultHomeActivity(int userId) {
21001 List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21002 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21007 // Find the launcher with the highest priority and return that component if there are no
21008 // other home activity with the same priority.
21009 int lastPriority = Integer.MIN_VALUE;
21010 ComponentName lastComponent = null;
21011 final int size = allHomeCandidates.size();
21012 for (int i = 0; i < size; i++) {
21013 final ResolveInfo ri = allHomeCandidates.get(i);
21014 if (ri.priority > lastPriority) {
21015 lastComponent = ri.activityInfo.getComponentName();
21016 lastPriority = ri.priority;
21017 } else if (ri.priority == lastPriority) {
21018 // Two components found with same priority.
21019 lastComponent = null;
21022 return lastComponent;
21025 private Intent getHomeIntent() {
21026 Intent intent = new Intent(Intent.ACTION_MAIN);
21027 intent.addCategory(Intent.CATEGORY_HOME);
21028 intent.addCategory(Intent.CATEGORY_DEFAULT);
21032 private IntentFilter getHomeFilter() {
21033 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21034 filter.addCategory(Intent.CATEGORY_HOME);
21035 filter.addCategory(Intent.CATEGORY_DEFAULT);
21039 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21041 Intent intent = getHomeIntent();
21042 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21043 PackageManager.GET_META_DATA, userId);
21044 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21045 true, false, false, userId);
21047 allHomeCandidates.clear();
21048 if (list != null) {
21049 for (ResolveInfo ri : list) {
21050 allHomeCandidates.add(ri);
21053 return (preferred == null || preferred.activityInfo == null)
21055 : new ComponentName(preferred.activityInfo.packageName,
21056 preferred.activityInfo.name);
21060 public void setHomeActivity(ComponentName comp, int userId) {
21061 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21064 ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21065 getHomeActivitiesAsUser(homeActivities, userId);
21067 boolean found = false;
21069 final int size = homeActivities.size();
21070 final ComponentName[] set = new ComponentName[size];
21071 for (int i = 0; i < size; i++) {
21072 final ResolveInfo candidate = homeActivities.get(i);
21073 final ActivityInfo info = candidate.activityInfo;
21074 final ComponentName activityName = new ComponentName(info.packageName, info.name);
21075 set[i] = activityName;
21076 if (!found && activityName.equals(comp)) {
21081 throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21084 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21085 set, comp, userId);
21088 private @Nullable String getSetupWizardPackageName() {
21089 final Intent intent = new Intent(Intent.ACTION_MAIN);
21090 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21092 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21093 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21094 | MATCH_DISABLED_COMPONENTS,
21095 UserHandle.myUserId());
21096 if (matches.size() == 1) {
21097 return matches.get(0).getComponentInfo().packageName;
21099 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21100 + ": matches=" + matches);
21105 private @Nullable String getStorageManagerPackageName() {
21106 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21108 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21109 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21110 | MATCH_DISABLED_COMPONENTS,
21111 UserHandle.myUserId());
21112 if (matches.size() == 1) {
21113 return matches.get(0).getComponentInfo().packageName;
21115 Slog.e(TAG, "There should probably be exactly one storage manager; found "
21116 + matches.size() + ": matches=" + matches);
21122 public void setApplicationEnabledSetting(String appPackageName,
21123 int newState, int flags, int userId, String callingPackage) {
21124 if (!sUserManager.exists(userId)) return;
21125 if (callingPackage == null) {
21126 callingPackage = Integer.toString(Binder.getCallingUid());
21128 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21132 public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21133 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21134 synchronized (mPackages) {
21135 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21136 if (pkgSetting != null) {
21137 pkgSetting.setUpdateAvailable(updateAvailable);
21143 public void setComponentEnabledSetting(ComponentName componentName,
21144 int newState, int flags, int userId) {
21145 if (!sUserManager.exists(userId)) return;
21146 setEnabledSetting(componentName.getPackageName(),
21147 componentName.getClassName(), newState, flags, userId, null);
21150 private void setEnabledSetting(final String packageName, String className, int newState,
21151 final int flags, int userId, String callingPackage) {
21152 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21153 || newState == COMPONENT_ENABLED_STATE_ENABLED
21154 || newState == COMPONENT_ENABLED_STATE_DISABLED
21155 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21156 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21157 throw new IllegalArgumentException("Invalid new component state: "
21160 PackageSetting pkgSetting;
21161 final int callingUid = Binder.getCallingUid();
21162 final int permission;
21163 if (callingUid == Process.SYSTEM_UID) {
21164 permission = PackageManager.PERMISSION_GRANTED;
21166 permission = mContext.checkCallingOrSelfPermission(
21167 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21169 enforceCrossUserPermission(callingUid, userId,
21170 false /* requireFullPermission */, true /* checkShell */, "set enabled");
21171 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21172 boolean sendNow = false;
21173 boolean isApp = (className == null);
21174 final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21175 String componentName = isApp ? packageName : className;
21176 int packageUid = -1;
21177 ArrayList<String> components;
21180 synchronized (mPackages) {
21181 pkgSetting = mSettings.mPackages.get(packageName);
21182 if (pkgSetting == null) {
21183 if (!isCallerInstantApp) {
21184 if (className == null) {
21185 throw new IllegalArgumentException("Unknown package: " + packageName);
21187 throw new IllegalArgumentException(
21188 "Unknown component: " + packageName + "/" + className);
21190 // throw SecurityException to prevent leaking package information
21191 throw new SecurityException(
21192 "Attempt to change component state; "
21193 + "pid=" + Binder.getCallingPid()
21194 + ", uid=" + callingUid
21195 + (className == null
21196 ? ", package=" + packageName
21197 : ", component=" + packageName + "/" + className));
21202 // Limit who can change which apps
21203 if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21204 // Don't allow apps that don't have permission to modify other apps
21205 if (!allowedByPermission
21206 || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21207 throw new SecurityException(
21208 "Attempt to change component state; "
21209 + "pid=" + Binder.getCallingPid()
21210 + ", uid=" + callingUid
21211 + (className == null
21212 ? ", package=" + packageName
21213 : ", component=" + packageName + "/" + className));
21215 // Don't allow changing protected packages.
21216 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21217 throw new SecurityException("Cannot disable a protected package: " + packageName);
21221 synchronized (mPackages) {
21222 if (callingUid == Process.SHELL_UID
21223 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21224 // Shell can only change whole packages between ENABLED and DISABLED_USER states
21225 // unless it is a test package.
21226 int oldState = pkgSetting.getEnabled(userId);
21227 if (className == null
21229 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21230 || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21231 || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21233 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21234 || newState == COMPONENT_ENABLED_STATE_DEFAULT
21235 || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21238 throw new SecurityException(
21239 "Shell cannot change component state for " + packageName + "/"
21240 + className + " to " + newState);
21243 if (className == null) {
21244 // We're dealing with an application/package level state change
21245 if (pkgSetting.getEnabled(userId) == newState) {
21249 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21250 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21251 // Don't care about who enables an app.
21252 callingPackage = null;
21254 pkgSetting.setEnabled(newState, userId, callingPackage);
21255 // pkgSetting.pkg.mSetEnabled = newState;
21257 // We're dealing with a component level state change
21258 // First, verify that this is a valid class name.
21259 PackageParser.Package pkg = pkgSetting.pkg;
21260 if (pkg == null || !pkg.hasComponentClassName(className)) {
21262 pkg.applicationInfo.targetSdkVersion >=
21263 Build.VERSION_CODES.JELLY_BEAN) {
21264 throw new IllegalArgumentException("Component class " + className
21265 + " does not exist in " + packageName);
21267 Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21268 + className + " does not exist in " + packageName);
21271 switch (newState) {
21272 case COMPONENT_ENABLED_STATE_ENABLED:
21273 if (!pkgSetting.enableComponentLPw(className, userId)) {
21277 case COMPONENT_ENABLED_STATE_DISABLED:
21278 if (!pkgSetting.disableComponentLPw(className, userId)) {
21282 case COMPONENT_ENABLED_STATE_DEFAULT:
21283 if (!pkgSetting.restoreComponentLPw(className, userId)) {
21288 Slog.e(TAG, "Invalid new component state: " + newState);
21292 scheduleWritePackageRestrictionsLocked(userId);
21293 updateSequenceNumberLP(pkgSetting, new int[] { userId });
21294 final long callingId = Binder.clearCallingIdentity();
21296 updateInstantAppInstallerLocked(packageName);
21298 Binder.restoreCallingIdentity(callingId);
21300 components = mPendingBroadcasts.get(userId, packageName);
21301 final boolean newPackage = components == null;
21303 components = new ArrayList<String>();
21305 if (!components.contains(componentName)) {
21306 components.add(componentName);
21308 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21310 // Purge entry from pending broadcast list if another one exists already
21311 // since we are sending one right away.
21312 mPendingBroadcasts.remove(userId, packageName);
21315 mPendingBroadcasts.put(userId, packageName, components);
21317 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21318 // Schedule a message
21319 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21324 long callingId = Binder.clearCallingIdentity();
21327 packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21328 sendPackageChangedBroadcast(packageName,
21329 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21332 Binder.restoreCallingIdentity(callingId);
21337 public void flushPackageRestrictionsAsUser(int userId) {
21338 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21341 if (!sUserManager.exists(userId)) {
21344 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21345 false /* checkShell */, "flushPackageRestrictions");
21346 synchronized (mPackages) {
21347 mSettings.writePackageRestrictionsLPr(userId);
21348 mDirtyUsers.remove(userId);
21349 if (mDirtyUsers.isEmpty()) {
21350 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21355 private void sendPackageChangedBroadcast(String packageName,
21356 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21358 Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21360 Bundle extras = new Bundle(4);
21361 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21362 String nameList[] = new String[componentNames.size()];
21363 componentNames.toArray(nameList);
21364 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21365 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21366 extras.putInt(Intent.EXTRA_UID, packageUid);
21367 // If this is not reporting a change of the overall package, then only send it
21368 // to registered receivers. We don't want to launch a swath of apps for every
21369 // little component state change.
21370 final int flags = !componentNames.contains(packageName)
21371 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21372 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null,
21373 new int[] {UserHandle.getUserId(packageUid)});
21377 public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21378 if (!sUserManager.exists(userId)) return;
21379 final int callingUid = Binder.getCallingUid();
21380 if (getInstantAppPackageName(callingUid) != null) {
21383 final int permission = mContext.checkCallingOrSelfPermission(
21384 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21385 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21386 enforceCrossUserPermission(callingUid, userId,
21387 true /* requireFullPermission */, true /* checkShell */, "stop package");
21389 synchronized (mPackages) {
21390 final PackageSetting ps = mSettings.mPackages.get(packageName);
21391 if (!filterAppAccessLPr(ps, callingUid, userId)
21392 && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21393 allowedByPermission, callingUid, userId)) {
21394 scheduleWritePackageRestrictionsLocked(userId);
21400 public String getInstallerPackageName(String packageName) {
21401 final int callingUid = Binder.getCallingUid();
21402 if (getInstantAppPackageName(callingUid) != null) {
21406 synchronized (mPackages) {
21407 final PackageSetting ps = mSettings.mPackages.get(packageName);
21408 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21411 return mSettings.getInstallerPackageNameLPr(packageName);
21415 public boolean isOrphaned(String packageName) {
21417 synchronized (mPackages) {
21418 return mSettings.isOrphaned(packageName);
21423 public int getApplicationEnabledSetting(String packageName, int userId) {
21424 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21425 int callingUid = Binder.getCallingUid();
21426 enforceCrossUserPermission(callingUid, userId,
21427 false /* requireFullPermission */, false /* checkShell */, "get enabled");
21429 synchronized (mPackages) {
21430 if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21431 return COMPONENT_ENABLED_STATE_DISABLED;
21433 return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21438 public int getComponentEnabledSetting(ComponentName component, int userId) {
21439 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21440 int callingUid = Binder.getCallingUid();
21441 enforceCrossUserPermission(callingUid, userId,
21442 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21443 synchronized (mPackages) {
21444 if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21445 component, TYPE_UNKNOWN, userId)) {
21446 return COMPONENT_ENABLED_STATE_DISABLED;
21448 return mSettings.getComponentEnabledSettingLPr(component, userId);
21453 public void enterSafeMode() {
21454 enforceSystemOrRoot("Only the system can request entering safe mode");
21456 if (!mSystemReady) {
21462 public void systemReady() {
21463 enforceSystemOrRoot("Only the system can claim the system is ready");
21465 mSystemReady = true;
21466 final ContentResolver resolver = mContext.getContentResolver();
21467 ContentObserver co = new ContentObserver(mHandler) {
21469 public void onChange(boolean selfChange) {
21470 mEphemeralAppsDisabled =
21471 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21472 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21475 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21476 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21477 false, co, UserHandle.USER_SYSTEM);
21478 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21479 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21482 // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21483 // disabled after already being started.
21484 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21485 mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21487 // Read the compatibilty setting when the system is ready.
21488 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21489 mContext.getContentResolver(),
21490 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21491 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21492 if (DEBUG_SETTINGS) {
21493 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21496 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21498 synchronized (mPackages) {
21499 // Verify that all of the preferred activity components actually
21500 // exist. It is possible for applications to be updated and at
21501 // that point remove a previously declared activity component that
21502 // had been set as a preferred activity. We try to clean this up
21503 // the next time we encounter that preferred activity, but it is
21504 // possible for the user flow to never be able to return to that
21505 // situation so here we do a sanity check to make sure we haven't
21506 // left any junk around.
21507 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21508 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21509 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21511 for (PreferredActivity pa : pir.filterSet()) {
21512 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21516 if (removed.size() > 0) {
21517 for (int r=0; r<removed.size(); r++) {
21518 PreferredActivity pa = removed.get(r);
21519 Slog.w(TAG, "Removing dangling preferred activity: "
21520 + pa.mPref.mComponent);
21521 pir.removeFilter(pa);
21523 mSettings.writePackageRestrictionsLPr(
21524 mSettings.mPreferredActivities.keyAt(i));
21528 for (int userId : UserManagerService.getInstance().getUserIds()) {
21529 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21530 grantPermissionsUserIds = ArrayUtils.appendInt(
21531 grantPermissionsUserIds, userId);
21535 sUserManager.systemReady();
21537 // If we upgraded grant all default permissions before kicking off.
21538 for (int userId : grantPermissionsUserIds) {
21539 mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21542 // If we did not grant default permissions, we preload from this the
21543 // default permission exceptions lazily to ensure we don't hit the
21544 // disk on a new user creation.
21545 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21546 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21549 // Kick off any messages waiting for system ready
21550 if (mPostSystemReadyMessages != null) {
21551 for (Message msg : mPostSystemReadyMessages) {
21552 msg.sendToTarget();
21554 mPostSystemReadyMessages = null;
21557 // Watch for external volumes that come and go over time
21558 final StorageManager storage = mContext.getSystemService(StorageManager.class);
21559 storage.registerListener(mStorageListener);
21561 mInstallerService.systemReady();
21562 mPackageDexOptimizer.systemReady();
21564 StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21565 StorageManagerInternal.class);
21566 StorageManagerInternal.addExternalStoragePolicy(
21567 new StorageManagerInternal.ExternalStorageMountPolicy() {
21569 public int getMountMode(int uid, String packageName) {
21570 if (Process.isIsolated(uid)) {
21571 return Zygote.MOUNT_EXTERNAL_NONE;
21573 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21574 return Zygote.MOUNT_EXTERNAL_DEFAULT;
21576 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21577 return Zygote.MOUNT_EXTERNAL_DEFAULT;
21579 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21580 return Zygote.MOUNT_EXTERNAL_READ;
21582 return Zygote.MOUNT_EXTERNAL_WRITE;
21586 public boolean hasExternalStorage(int uid, String packageName) {
21591 // Now that we're mostly running, clean up stale users and apps
21592 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21593 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21595 if (mPrivappPermissionsViolations != null) {
21596 Slog.wtf(TAG,"Signature|privileged permissions not in "
21597 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21598 mPrivappPermissionsViolations = null;
21602 public void waitForAppDataPrepared() {
21603 if (mPrepareAppDataFuture == null) {
21606 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21607 mPrepareAppDataFuture = null;
21611 public boolean isSafeMode() {
21612 // allow instant applications
21617 public boolean hasSystemUidErrors() {
21618 // allow instant applications
21619 return mHasSystemUidErrors;
21622 static String arrayToString(int[] array) {
21623 StringBuffer buf = new StringBuffer(128);
21625 if (array != null) {
21626 for (int i=0; i<array.length; i++) {
21627 if (i > 0) buf.append(", ");
21628 buf.append(array[i]);
21632 return buf.toString();
21635 static class DumpState {
21636 public static final int DUMP_LIBS = 1 << 0;
21637 public static final int DUMP_FEATURES = 1 << 1;
21638 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21639 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21640 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21641 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21642 public static final int DUMP_PERMISSIONS = 1 << 6;
21643 public static final int DUMP_PACKAGES = 1 << 7;
21644 public static final int DUMP_SHARED_USERS = 1 << 8;
21645 public static final int DUMP_MESSAGES = 1 << 9;
21646 public static final int DUMP_PROVIDERS = 1 << 10;
21647 public static final int DUMP_VERIFIERS = 1 << 11;
21648 public static final int DUMP_PREFERRED = 1 << 12;
21649 public static final int DUMP_PREFERRED_XML = 1 << 13;
21650 public static final int DUMP_KEYSETS = 1 << 14;
21651 public static final int DUMP_VERSION = 1 << 15;
21652 public static final int DUMP_INSTALLS = 1 << 16;
21653 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21654 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21655 public static final int DUMP_FROZEN = 1 << 19;
21656 public static final int DUMP_DEXOPT = 1 << 20;
21657 public static final int DUMP_COMPILER_STATS = 1 << 21;
21658 public static final int DUMP_CHANGES = 1 << 22;
21660 public static final int OPTION_SHOW_FILTERS = 1 << 0;
21662 private int mTypes;
21664 private int mOptions;
21666 private boolean mTitlePrinted;
21668 private SharedUserSetting mSharedUser;
21670 public boolean isDumping(int type) {
21671 if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21675 return (mTypes & type) != 0;
21678 public void setDump(int type) {
21682 public boolean isOptionEnabled(int option) {
21683 return (mOptions & option) != 0;
21686 public void setOptionEnabled(int option) {
21687 mOptions |= option;
21690 public boolean onTitlePrinted() {
21691 final boolean printed = mTitlePrinted;
21692 mTitlePrinted = true;
21696 public boolean getTitlePrinted() {
21697 return mTitlePrinted;
21700 public void setTitlePrinted(boolean enabled) {
21701 mTitlePrinted = enabled;
21704 public SharedUserSetting getSharedUser() {
21705 return mSharedUser;
21708 public void setSharedUser(SharedUserSetting user) {
21709 mSharedUser = user;
21714 public void onShellCommand(FileDescriptor in, FileDescriptor out,
21715 FileDescriptor err, String[] args, ShellCallback callback,
21716 ResultReceiver resultReceiver) {
21717 (new PackageManagerShellCommand(this)).exec(
21718 this, in, out, err, args, callback, resultReceiver);
21722 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21723 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21725 DumpState dumpState = new DumpState();
21726 boolean fullPreferred = false;
21727 boolean checkin = false;
21729 String packageName = null;
21730 ArraySet<String> permissionNames = null;
21733 while (opti < args.length) {
21734 String opt = args[opti];
21735 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21740 if ("-a".equals(opt)) {
21741 // Right now we only know how to print all.
21742 } else if ("-h".equals(opt)) {
21743 pw.println("Package manager dump options:");
21744 pw.println(" [-h] [-f] [--checkin] [cmd] ...");
21745 pw.println(" --checkin: dump for a checkin");
21746 pw.println(" -f: print details of intent filters");
21747 pw.println(" -h: print this help");
21748 pw.println(" cmd may be one of:");
21749 pw.println(" l[ibraries]: list known shared libraries");
21750 pw.println(" f[eatures]: list device features");
21751 pw.println(" k[eysets]: print known keysets");
21752 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21753 pw.println(" perm[issions]: dump permissions");
21754 pw.println(" permission [name ...]: dump declaration and use of given permission");
21755 pw.println(" pref[erred]: print preferred package settings");
21756 pw.println(" preferred-xml [--full]: print preferred package settings as xml");
21757 pw.println(" prov[iders]: dump content providers");
21758 pw.println(" p[ackages]: dump installed packages");
21759 pw.println(" s[hared-users]: dump shared user IDs");
21760 pw.println(" m[essages]: print collected runtime messages");
21761 pw.println(" v[erifiers]: print package verifier info");
21762 pw.println(" d[omain-preferred-apps]: print domains preferred apps");
21763 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21764 pw.println(" version: print database version info");
21765 pw.println(" write: write current settings now");
21766 pw.println(" installs: details about install sessions");
21767 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?");
21768 pw.println(" dexopt: dump dexopt state");
21769 pw.println(" compiler-stats: dump compiler statistics");
21770 pw.println(" enabled-overlays: dump list of enabled overlay packages");
21771 pw.println(" <package.name>: info about given package");
21773 } else if ("--checkin".equals(opt)) {
21775 } else if ("-f".equals(opt)) {
21776 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21777 } else if ("--proto".equals(opt)) {
21781 pw.println("Unknown argument: " + opt + "; use -h for help");
21785 // Is the caller requesting to dump a particular piece of data?
21786 if (opti < args.length) {
21787 String cmd = args[opti];
21789 // Is this a package name?
21790 if ("android".equals(cmd) || cmd.contains(".")) {
21792 // When dumping a single package, we always dump all of its
21793 // filter information since the amount of data will be reasonable.
21794 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21795 } else if ("check-permission".equals(cmd)) {
21796 if (opti >= args.length) {
21797 pw.println("Error: check-permission missing permission argument");
21800 String perm = args[opti];
21802 if (opti >= args.length) {
21803 pw.println("Error: check-permission missing package argument");
21807 String pkg = args[opti];
21809 int user = UserHandle.getUserId(Binder.getCallingUid());
21810 if (opti < args.length) {
21812 user = Integer.parseInt(args[opti]);
21813 } catch (NumberFormatException e) {
21814 pw.println("Error: check-permission user argument is not a number: "
21820 // Normalize package name to handle renamed packages and static libs
21821 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21823 pw.println(checkPermission(perm, pkg, user));
21825 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21826 dumpState.setDump(DumpState.DUMP_LIBS);
21827 } else if ("f".equals(cmd) || "features".equals(cmd)) {
21828 dumpState.setDump(DumpState.DUMP_FEATURES);
21829 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21830 if (opti >= args.length) {
21831 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21832 | DumpState.DUMP_SERVICE_RESOLVERS
21833 | DumpState.DUMP_RECEIVER_RESOLVERS
21834 | DumpState.DUMP_CONTENT_RESOLVERS);
21836 while (opti < args.length) {
21837 String name = args[opti];
21838 if ("a".equals(name) || "activity".equals(name)) {
21839 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21840 } else if ("s".equals(name) || "service".equals(name)) {
21841 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21842 } else if ("r".equals(name) || "receiver".equals(name)) {
21843 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21844 } else if ("c".equals(name) || "content".equals(name)) {
21845 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21847 pw.println("Error: unknown resolver table type: " + name);
21853 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21854 dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21855 } else if ("permission".equals(cmd)) {
21856 if (opti >= args.length) {
21857 pw.println("Error: permission requires permission name");
21860 permissionNames = new ArraySet<>();
21861 while (opti < args.length) {
21862 permissionNames.add(args[opti]);
21865 dumpState.setDump(DumpState.DUMP_PERMISSIONS
21866 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21867 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21868 dumpState.setDump(DumpState.DUMP_PREFERRED);
21869 } else if ("preferred-xml".equals(cmd)) {
21870 dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21871 if (opti < args.length && "--full".equals(args[opti])) {
21872 fullPreferred = true;
21875 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21876 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21877 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21878 dumpState.setDump(DumpState.DUMP_PACKAGES);
21879 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21880 dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21881 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21882 dumpState.setDump(DumpState.DUMP_PROVIDERS);
21883 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21884 dumpState.setDump(DumpState.DUMP_MESSAGES);
21885 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21886 dumpState.setDump(DumpState.DUMP_VERIFIERS);
21887 } else if ("i".equals(cmd) || "ifv".equals(cmd)
21888 || "intent-filter-verifiers".equals(cmd)) {
21889 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21890 } else if ("version".equals(cmd)) {
21891 dumpState.setDump(DumpState.DUMP_VERSION);
21892 } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21893 dumpState.setDump(DumpState.DUMP_KEYSETS);
21894 } else if ("installs".equals(cmd)) {
21895 dumpState.setDump(DumpState.DUMP_INSTALLS);
21896 } else if ("frozen".equals(cmd)) {
21897 dumpState.setDump(DumpState.DUMP_FROZEN);
21898 } else if ("dexopt".equals(cmd)) {
21899 dumpState.setDump(DumpState.DUMP_DEXOPT);
21900 } else if ("compiler-stats".equals(cmd)) {
21901 dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21902 } else if ("changes".equals(cmd)) {
21903 dumpState.setDump(DumpState.DUMP_CHANGES);
21904 } else if ("write".equals(cmd)) {
21905 synchronized (mPackages) {
21906 mSettings.writeLPr();
21907 pw.println("Settings written.");
21914 pw.println("vers,1");
21918 synchronized (mPackages) {
21919 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21921 if (dumpState.onTitlePrinted())
21923 pw.println("Database versions:");
21924 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " "));
21928 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21930 if (dumpState.onTitlePrinted())
21932 pw.println("Verifiers:");
21933 pw.print(" Required: ");
21934 pw.print(mRequiredVerifierPackage);
21935 pw.print(" (uid=");
21936 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21937 UserHandle.USER_SYSTEM));
21939 } else if (mRequiredVerifierPackage != null) {
21940 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21942 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21943 UserHandle.USER_SYSTEM));
21947 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21948 packageName == null) {
21949 if (mIntentFilterVerifierComponent != null) {
21950 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21952 if (dumpState.onTitlePrinted())
21954 pw.println("Intent Filter Verifier:");
21955 pw.print(" Using: ");
21956 pw.print(verifierPackageName);
21957 pw.print(" (uid=");
21958 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21959 UserHandle.USER_SYSTEM));
21961 } else if (verifierPackageName != null) {
21962 pw.print("ifv,"); pw.print(verifierPackageName);
21964 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21965 UserHandle.USER_SYSTEM));
21969 pw.println("No Intent Filter Verifier available!");
21973 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21974 boolean printedHeader = false;
21975 final Iterator<String> it = mSharedLibraries.keySet().iterator();
21976 while (it.hasNext()) {
21977 String libName = it.next();
21978 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21979 if (versionedLib == null) {
21982 final int versionCount = versionedLib.size();
21983 for (int i = 0; i < versionCount; i++) {
21984 SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21986 if (!printedHeader) {
21987 if (dumpState.onTitlePrinted())
21989 pw.println("Libraries:");
21990 printedHeader = true;
21996 pw.print(libEntry.info.getName());
21997 if (libEntry.info.isStatic()) {
21998 pw.print(" version=" + libEntry.info.getVersion());
22003 if (libEntry.path != null) {
22004 pw.print(" (jar) ");
22005 pw.print(libEntry.path);
22007 pw.print(" (apk) ");
22008 pw.print(libEntry.apk);
22015 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22016 if (dumpState.onTitlePrinted())
22019 pw.println("Features:");
22022 synchronized (mAvailableFeatures) {
22023 for (FeatureInfo feat : mAvailableFeatures.values()) {
22026 pw.print(feat.name);
22028 pw.println(feat.version);
22031 pw.print(feat.name);
22032 if (feat.version > 0) {
22033 pw.print(" version=");
22034 pw.print(feat.version);
22042 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22043 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22044 : "Activity Resolver Table:", " ", packageName,
22045 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22046 dumpState.setTitlePrinted(true);
22049 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22050 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22051 : "Receiver Resolver Table:", " ", packageName,
22052 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22053 dumpState.setTitlePrinted(true);
22056 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22057 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22058 : "Service Resolver Table:", " ", packageName,
22059 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22060 dumpState.setTitlePrinted(true);
22063 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22064 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22065 : "Provider Resolver Table:", " ", packageName,
22066 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22067 dumpState.setTitlePrinted(true);
22071 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22072 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22073 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22074 int user = mSettings.mPreferredActivities.keyAt(i);
22076 dumpState.getTitlePrinted()
22077 ? "\nPreferred Activities User " + user + ":"
22078 : "Preferred Activities User " + user + ":", " ",
22079 packageName, true, false)) {
22080 dumpState.setTitlePrinted(true);
22085 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22087 FileOutputStream fout = new FileOutputStream(fd);
22088 BufferedOutputStream str = new BufferedOutputStream(fout);
22089 XmlSerializer serializer = new FastXmlSerializer();
22091 serializer.setOutput(str, StandardCharsets.UTF_8.name());
22092 serializer.startDocument(null, true);
22093 serializer.setFeature(
22094 "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22095 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22096 serializer.endDocument();
22097 serializer.flush();
22098 } catch (IllegalArgumentException e) {
22099 pw.println("Failed writing: " + e);
22100 } catch (IllegalStateException e) {
22101 pw.println("Failed writing: " + e);
22102 } catch (IOException e) {
22103 pw.println("Failed writing: " + e);
22108 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22109 && packageName == null) {
22111 int count = mSettings.mPackages.size();
22113 pw.println("No applications!");
22116 final String prefix = " ";
22117 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22118 if (allPackageSettings.size() == 0) {
22119 pw.println("No domain preferred apps!");
22122 pw.println("App verification status:");
22125 for (PackageSetting ps : allPackageSettings) {
22126 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22127 if (ivi == null || ivi.getPackageName() == null) continue;
22128 pw.println(prefix + "Package: " + ivi.getPackageName());
22129 pw.println(prefix + "Domains: " + ivi.getDomainsString());
22130 pw.println(prefix + "Status: " + ivi.getStatusString());
22135 pw.println(prefix + "No app verification established.");
22138 for (int userId : sUserManager.getUserIds()) {
22139 pw.println("App linkages for user " + userId + ":");
22142 for (PackageSetting ps : allPackageSettings) {
22143 final long status = ps.getDomainVerificationStatusForUser(userId);
22144 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22145 && !DEBUG_DOMAIN_VERIFICATION) {
22148 pw.println(prefix + "Package: " + ps.name);
22149 pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22150 String statusStr = IntentFilterVerificationInfo.
22151 getStatusStringFromValue(status);
22152 pw.println(prefix + "Status: " + statusStr);
22157 pw.println(prefix + "No configured app linkages.");
22165 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22166 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22167 if (packageName == null && permissionNames == null) {
22168 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22170 if (dumpState.onTitlePrinted())
22172 pw.println("AppOp Permissions:");
22174 pw.print(" AppOp Permission ");
22175 pw.print(mAppOpPermissionPackages.keyAt(iperm));
22177 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22178 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22179 pw.print(" "); pw.println(pkgs.valueAt(ipkg));
22185 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22186 boolean printedSomething = false;
22187 for (PackageParser.Provider p : mProviders.mProviders.values()) {
22188 if (packageName != null && !packageName.equals(p.info.packageName)) {
22191 if (!printedSomething) {
22192 if (dumpState.onTitlePrinted())
22194 pw.println("Registered ContentProviders:");
22195 printedSomething = true;
22197 pw.print(" "); p.printComponentShortName(pw); pw.println(":");
22198 pw.print(" "); pw.println(p.toString());
22200 printedSomething = false;
22201 for (Map.Entry<String, PackageParser.Provider> entry :
22202 mProvidersByAuthority.entrySet()) {
22203 PackageParser.Provider p = entry.getValue();
22204 if (packageName != null && !packageName.equals(p.info.packageName)) {
22207 if (!printedSomething) {
22208 if (dumpState.onTitlePrinted())
22210 pw.println("ContentProvider Authorities:");
22211 printedSomething = true;
22213 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:");
22214 pw.print(" "); pw.println(p.toString());
22215 if (p.info != null && p.info.applicationInfo != null) {
22216 final String appInfo = p.info.applicationInfo.toString();
22217 pw.print(" applicationInfo="); pw.println(appInfo);
22222 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22223 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22226 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22227 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22230 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22231 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22234 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22235 if (dumpState.onTitlePrinted()) pw.println();
22236 pw.println("Package Changes:");
22237 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22238 final int K = mChangedPackages.size();
22239 for (int i = 0; i < K; i++) {
22240 final SparseArray<String> changes = mChangedPackages.valueAt(i);
22241 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22242 final int N = changes.size();
22244 pw.print(" "); pw.println("No packages changed");
22246 for (int j = 0; j < N; j++) {
22247 final String pkgName = changes.valueAt(j);
22248 final int sequenceNumber = changes.keyAt(j);
22251 pw.print(sequenceNumber);
22252 pw.print(", package=");
22253 pw.println(pkgName);
22259 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22260 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22263 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22264 // XXX should handle packageName != null by dumping only install data that
22265 // the given package is involved with.
22266 if (dumpState.onTitlePrinted()) pw.println();
22268 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120);
22270 ipw.println("Frozen packages:");
22271 ipw.increaseIndent();
22272 if (mFrozenPackages.size() == 0) {
22273 ipw.println("(none)");
22275 for (int i = 0; i < mFrozenPackages.size(); i++) {
22276 ipw.println(mFrozenPackages.valueAt(i));
22279 ipw.decreaseIndent();
22282 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22283 if (dumpState.onTitlePrinted()) pw.println();
22284 dumpDexoptStateLPr(pw, packageName);
22287 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22288 if (dumpState.onTitlePrinted()) pw.println();
22289 dumpCompilerStatsLPr(pw, packageName);
22292 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22293 if (dumpState.onTitlePrinted()) pw.println();
22294 mSettings.dumpReadMessagesLPr(pw, dumpState);
22297 pw.println("Package warning messages:");
22298 BufferedReader in = null;
22299 String line = null;
22301 in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22302 while ((line = in.readLine()) != null) {
22303 if (line.contains("ignored: updated version")) continue;
22306 } catch (IOException ignored) {
22308 IoUtils.closeQuietly(in);
22312 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22313 BufferedReader in = null;
22314 String line = null;
22316 in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22317 while ((line = in.readLine()) != null) {
22318 if (line.contains("ignored: updated version")) continue;
22322 } catch (IOException ignored) {
22324 IoUtils.closeQuietly(in);
22329 // PackageInstaller should be called outside of mPackages lock
22330 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22331 // XXX should handle packageName != null by dumping only install data that
22332 // the given package is involved with.
22333 if (dumpState.onTitlePrinted()) pw.println();
22334 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120));
22338 private void dumpProto(FileDescriptor fd) {
22339 final ProtoOutputStream proto = new ProtoOutputStream(fd);
22341 synchronized (mPackages) {
22342 final long requiredVerifierPackageToken =
22343 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22344 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22346 PackageServiceDumpProto.PackageShortProto.UID,
22348 mRequiredVerifierPackage,
22349 MATCH_DEBUG_TRIAGED_MISSING,
22350 UserHandle.USER_SYSTEM));
22351 proto.end(requiredVerifierPackageToken);
22353 if (mIntentFilterVerifierComponent != null) {
22354 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22355 final long verifierPackageToken =
22356 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22357 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22359 PackageServiceDumpProto.PackageShortProto.UID,
22361 verifierPackageName,
22362 MATCH_DEBUG_TRIAGED_MISSING,
22363 UserHandle.USER_SYSTEM));
22364 proto.end(verifierPackageToken);
22367 dumpSharedLibrariesProto(proto);
22368 dumpFeaturesProto(proto);
22369 mSettings.dumpPackagesProto(proto);
22370 mSettings.dumpSharedUsersProto(proto);
22371 dumpMessagesProto(proto);
22376 private void dumpMessagesProto(ProtoOutputStream proto) {
22377 BufferedReader in = null;
22378 String line = null;
22380 in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22381 while ((line = in.readLine()) != null) {
22382 if (line.contains("ignored: updated version")) continue;
22383 proto.write(PackageServiceDumpProto.MESSAGES, line);
22385 } catch (IOException ignored) {
22387 IoUtils.closeQuietly(in);
22391 private void dumpFeaturesProto(ProtoOutputStream proto) {
22392 synchronized (mAvailableFeatures) {
22393 final int count = mAvailableFeatures.size();
22394 for (int i = 0; i < count; i++) {
22395 final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22396 final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22397 proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22398 proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22399 proto.end(featureToken);
22404 private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22405 final int count = mSharedLibraries.size();
22406 for (int i = 0; i < count; i++) {
22407 final String libName = mSharedLibraries.keyAt(i);
22408 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22409 if (versionedLib == null) {
22412 final int versionCount = versionedLib.size();
22413 for (int j = 0; j < versionCount; j++) {
22414 final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22415 final long sharedLibraryToken =
22416 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22417 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22418 final boolean isJar = (libEntry.path != null);
22419 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22421 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22423 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22425 proto.end(sharedLibraryToken);
22430 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22431 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120);
22433 ipw.println("Dexopt state:");
22434 ipw.increaseIndent();
22435 Collection<PackageParser.Package> packages = null;
22436 if (packageName != null) {
22437 PackageParser.Package targetPackage = mPackages.get(packageName);
22438 if (targetPackage != null) {
22439 packages = Collections.singletonList(targetPackage);
22441 ipw.println("Unable to find package: " + packageName);
22445 packages = mPackages.values();
22448 for (PackageParser.Package pkg : packages) {
22449 ipw.println("[" + pkg.packageName + "]");
22450 ipw.increaseIndent();
22451 mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22452 ipw.decreaseIndent();
22456 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22457 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120);
22459 ipw.println("Compiler stats:");
22460 ipw.increaseIndent();
22461 Collection<PackageParser.Package> packages = null;
22462 if (packageName != null) {
22463 PackageParser.Package targetPackage = mPackages.get(packageName);
22464 if (targetPackage != null) {
22465 packages = Collections.singletonList(targetPackage);
22467 ipw.println("Unable to find package: " + packageName);
22471 packages = mPackages.values();
22474 for (PackageParser.Package pkg : packages) {
22475 ipw.println("[" + pkg.packageName + "]");
22476 ipw.increaseIndent();
22478 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22479 if (stats == null) {
22480 ipw.println("(No recorded stats)");
22484 ipw.decreaseIndent();
22488 private String dumpDomainString(String packageName) {
22489 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22491 List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22493 ArraySet<String> result = new ArraySet<>();
22494 if (iviList.size() > 0) {
22495 for (IntentFilterVerificationInfo ivi : iviList) {
22496 for (String host : ivi.getDomains()) {
22501 if (filters != null && filters.size() > 0) {
22502 for (IntentFilter filter : filters) {
22503 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22504 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22505 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22506 result.addAll(filter.getHostsList());
22511 StringBuilder sb = new StringBuilder(result.size() * 16);
22512 for (String domain : result) {
22513 if (sb.length() > 0) sb.append(" ");
22516 return sb.toString();
22519 // ------- apps on sdcard specific code -------
22520 static final boolean DEBUG_SD_INSTALL = false;
22522 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22524 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22526 private boolean mMediaMounted = false;
22528 static String getEncryptKey() {
22530 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22531 SD_ENCRYPTION_KEYSTORE_NAME);
22532 if (sdEncKey == null) {
22533 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22534 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22535 if (sdEncKey == null) {
22536 Slog.e(TAG, "Failed to create encryption keys");
22541 } catch (NoSuchAlgorithmException nsae) {
22542 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22544 } catch (IOException ioe) {
22545 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22551 * Update media status on PackageManager.
22554 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22555 enforceSystemOrRoot("Media status can only be updated by the system");
22556 // reader; this apparently protects mMediaMounted, but should probably
22557 // be a different lock in that case.
22558 synchronized (mPackages) {
22559 Log.i(TAG, "Updating external media status from "
22560 + (mMediaMounted ? "mounted" : "unmounted") + " to "
22561 + (mediaStatus ? "mounted" : "unmounted"));
22562 if (DEBUG_SD_INSTALL)
22563 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22564 + ", mMediaMounted=" + mMediaMounted);
22565 if (mediaStatus == mMediaMounted) {
22566 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22568 mHandler.sendMessage(msg);
22571 mMediaMounted = mediaStatus;
22573 // Queue up an async operation since the package installation may take a
22575 mHandler.post(new Runnable() {
22576 public void run() {
22577 updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22583 * Called by StorageManagerService when the initial ASECs to scan are available.
22584 * Should block until all the ASEC containers are finished being scanned.
22586 public void scanAvailableAsecs() {
22587 updateExternalMediaStatusInner(true, false, false);
22591 * Collect information of applications on external media, map them against
22592 * existing containers and update information based on current mount status.
22593 * Please note that we always have to report status if reportStatus has been
22594 * set to true especially when unloading packages.
22596 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22597 boolean externalStorage) {
22598 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22599 int[] uidArr = EmptyArray.INT;
22601 final String[] list = PackageHelper.getSecureContainerList();
22602 if (ArrayUtils.isEmpty(list)) {
22603 Log.i(TAG, "No secure containers found");
22605 // Process list of secure containers and categorize them
22606 // as active or stale based on their package internal state.
22609 synchronized (mPackages) {
22610 for (String cid : list) {
22611 // Leave stages untouched for now; installer service owns them
22612 if (PackageInstallerService.isStageName(cid)) continue;
22614 if (DEBUG_SD_INSTALL)
22615 Log.i(TAG, "Processing container " + cid);
22616 String pkgName = getAsecPackageName(cid);
22617 if (pkgName == null) {
22618 Slog.i(TAG, "Found stale container " + cid + " with no package name");
22621 if (DEBUG_SD_INSTALL)
22622 Log.i(TAG, "Looking for pkg : " + pkgName);
22624 final PackageSetting ps = mSettings.mPackages.get(pkgName);
22626 Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22631 * Skip packages that are not external if we're unmounting
22632 * external storage.
22634 if (externalStorage && !isMounted && !isExternal(ps)) {
22638 final AsecInstallArgs args = new AsecInstallArgs(cid,
22639 getAppDexInstructionSets(ps), ps.isForwardLocked());
22640 // The package status is changed only if the code path
22641 // matches between settings and the container id.
22642 if (ps.codePathString != null
22643 && ps.codePathString.startsWith(args.getCodePath())) {
22644 if (DEBUG_SD_INSTALL) {
22645 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22646 + " at code path: " + ps.codePathString);
22649 // We do have a valid package installed on sdcard
22650 processCids.put(args, ps.codePathString);
22651 final int uid = ps.appId;
22653 uidArr = ArrayUtils.appendInt(uidArr, uid);
22656 Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22657 + ps.codePathString);
22662 Arrays.sort(uidArr);
22665 // Process packages with valid entries.
22667 if (DEBUG_SD_INSTALL)
22668 Log.i(TAG, "Loading packages");
22669 loadMediaPackages(processCids, uidArr, externalStorage);
22670 startCleaningPackages();
22671 mInstallerService.onSecureContainersAvailable();
22673 if (DEBUG_SD_INSTALL)
22674 Log.i(TAG, "Unloading packages");
22675 unloadMediaPackages(processCids, uidArr, reportStatus);
22679 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22680 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22681 final int size = infos.size();
22682 final String[] packageNames = new String[size];
22683 final int[] packageUids = new int[size];
22684 for (int i = 0; i < size; i++) {
22685 final ApplicationInfo info = infos.get(i);
22686 packageNames[i] = info.packageName;
22687 packageUids[i] = info.uid;
22689 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22693 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22694 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22695 sendResourcesChangedBroadcast(mediaStatus, replacing,
22696 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22699 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22700 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22701 int size = pkgList.length;
22703 // Send broadcasts here
22704 Bundle extras = new Bundle();
22705 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22706 if (uidArr != null) {
22707 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22710 extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22712 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22713 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22714 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22719 * Look at potentially valid container ids from processCids If package
22720 * information doesn't match the one on record or package scanning fails,
22721 * the cid is added to list of removeCids. We currently don't delete stale
22724 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22725 boolean externalStorage) {
22726 ArrayList<String> pkgList = new ArrayList<String>();
22727 Set<AsecInstallArgs> keys = processCids.keySet();
22729 for (AsecInstallArgs args : keys) {
22730 String codePath = processCids.get(args);
22731 if (DEBUG_SD_INSTALL)
22732 Log.i(TAG, "Loading container : " + args.cid);
22733 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22735 // Make sure there are no container errors first.
22736 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22737 Slog.e(TAG, "Failed to mount cid : " + args.cid
22738 + " when installing from sdcard");
22741 // Check code path here.
22742 if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22743 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22744 + " does not match one in settings " + codePath);
22748 int parseFlags = mDefParseFlags;
22749 if (args.isExternalAsec()) {
22750 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22752 if (args.isFwdLocked()) {
22753 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22756 synchronized (mInstallLock) {
22757 PackageParser.Package pkg = null;
22759 // Sadly we don't know the package name yet to freeze it
22760 pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22761 SCAN_IGNORE_FROZEN, 0, null);
22762 } catch (PackageManagerException e) {
22763 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22765 // Scan the package
22768 * TODO why is the lock being held? doPostInstall is
22769 * called in other places without the lock. This needs
22770 * to be straightened out.
22773 synchronized (mPackages) {
22774 retCode = PackageManager.INSTALL_SUCCEEDED;
22775 pkgList.add(pkg.packageName);
22776 // Post process args
22777 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22778 pkg.applicationInfo.uid);
22781 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard");
22786 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22787 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22792 synchronized (mPackages) {
22793 // If the platform SDK has changed since the last time we booted,
22794 // we need to re-grant app permission to catch any new ones that
22795 // appear. This is really a hack, and means that apps can in some
22796 // cases get permissions that the user didn't initially explicitly
22797 // allow... it would be nice to have some better way to handle
22799 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22800 : mSettings.getInternalVersion();
22801 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22802 : StorageManager.UUID_PRIVATE_INTERNAL;
22804 int updateFlags = UPDATE_PERMISSIONS_ALL;
22805 if (ver.sdkVersion != mSdkVersion) {
22806 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22807 + mSdkVersion + "; regranting permissions for external");
22808 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22810 updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22812 // Yay, everything is now upgraded
22813 ver.forceCurrent();
22815 // can downgrade to reader
22816 // Persist settings
22817 mSettings.writeLPr();
22819 // Send a broadcast to let everyone know we are done processing
22820 if (pkgList.size() > 0) {
22821 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22826 * Utility method to unload a list of specified containers
22828 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22829 // Just unmount all valid containers.
22830 for (AsecInstallArgs arg : cidArgs) {
22831 synchronized (mInstallLock) {
22832 arg.doPostDeleteLI(false);
22838 * Unload packages mounted on external media. This involves deleting package
22839 * data from internal structures, sending broadcasts about disabled packages,
22840 * gc'ing to free up references, unmounting all secure containers
22841 * corresponding to packages on external media, and posting a
22842 * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22843 * that we always have to post this message if status has been requested no
22846 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22847 final boolean reportStatus) {
22848 if (DEBUG_SD_INSTALL)
22849 Log.i(TAG, "unloading media packages");
22850 ArrayList<String> pkgList = new ArrayList<String>();
22851 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22852 final Set<AsecInstallArgs> keys = processCids.keySet();
22853 for (AsecInstallArgs args : keys) {
22854 String pkgName = args.getPackageName();
22855 if (DEBUG_SD_INSTALL)
22856 Log.i(TAG, "Trying to unload pkg : " + pkgName);
22857 // Delete package internally
22858 PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22859 synchronized (mInstallLock) {
22860 final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22862 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22863 "unloadMediaPackages")) {
22864 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22868 pkgList.add(pkgName);
22870 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22871 failedList.add(args);
22877 synchronized (mPackages) {
22878 // We didn't update the settings after removing each package;
22879 // write them now for all packages.
22880 mSettings.writeLPr();
22883 // We have to absolutely send UPDATED_MEDIA_STATUS only
22884 // after confirming that all the receivers processed the ordered
22885 // broadcast when packages get disabled, force a gc to clean things up.
22886 // and unload all the containers.
22887 if (pkgList.size() > 0) {
22888 sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22889 new IIntentReceiver.Stub() {
22890 public void performReceive(Intent intent, int resultCode, String data,
22891 Bundle extras, boolean ordered, boolean sticky,
22892 int sendingUser) throws RemoteException {
22893 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22894 reportStatus ? 1 : 0, 1, keys);
22895 mHandler.sendMessage(msg);
22899 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22901 mHandler.sendMessage(msg);
22905 private void loadPrivatePackages(final VolumeInfo vol) {
22906 mHandler.post(new Runnable() {
22908 public void run() {
22909 loadPrivatePackagesInner(vol);
22914 private void loadPrivatePackagesInner(VolumeInfo vol) {
22915 final String volumeUuid = vol.fsUuid;
22916 if (TextUtils.isEmpty(volumeUuid)) {
22917 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22921 final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22922 final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22923 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22925 final VersionInfo ver;
22926 final List<PackageSetting> packages;
22927 synchronized (mPackages) {
22928 ver = mSettings.findOrCreateVersion(volumeUuid);
22929 packages = mSettings.getVolumePackagesLPr(volumeUuid);
22932 for (PackageSetting ps : packages) {
22933 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22934 synchronized (mInstallLock) {
22935 final PackageParser.Package pkg;
22937 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22938 loaded.add(pkg.applicationInfo);
22940 } catch (PackageManagerException e) {
22941 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22944 if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22945 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22946 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22947 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22952 // Reconcile app data for all started/unlocked users
22953 final StorageManager sm = mContext.getSystemService(StorageManager.class);
22954 final UserManager um = mContext.getSystemService(UserManager.class);
22955 UserManagerInternal umInternal = getUserManagerInternal();
22956 for (UserInfo user : um.getUsers()) {
22958 if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22959 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22960 } else if (umInternal.isUserRunning(user.id)) {
22961 flags = StorageManager.FLAG_STORAGE_DE;
22967 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22968 synchronized (mInstallLock) {
22969 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22971 } catch (IllegalStateException e) {
22972 // Device was probably ejected, and we'll process that event momentarily
22973 Slog.w(TAG, "Failed to prepare storage: " + e);
22977 synchronized (mPackages) {
22978 int updateFlags = UPDATE_PERMISSIONS_ALL;
22979 if (ver.sdkVersion != mSdkVersion) {
22980 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22981 + mSdkVersion + "; regranting permissions for " + volumeUuid);
22982 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22984 updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22986 // Yay, everything is now upgraded
22987 ver.forceCurrent();
22989 mSettings.writeLPr();
22992 for (PackageFreezer freezer : freezers) {
22996 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22997 sendResourcesChangedBroadcast(true, false, loaded, null);
23000 private void unloadPrivatePackages(final VolumeInfo vol) {
23001 mHandler.post(new Runnable() {
23003 public void run() {
23004 unloadPrivatePackagesInner(vol);
23009 private void unloadPrivatePackagesInner(VolumeInfo vol) {
23010 final String volumeUuid = vol.fsUuid;
23011 if (TextUtils.isEmpty(volumeUuid)) {
23012 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23016 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23017 synchronized (mInstallLock) {
23018 synchronized (mPackages) {
23019 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23020 for (PackageSetting ps : packages) {
23021 if (ps.pkg == null) continue;
23023 final ApplicationInfo info = ps.pkg.applicationInfo;
23024 final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23025 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23027 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23028 "unloadPrivatePackagesInner")) {
23029 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23031 unloaded.add(info);
23033 Slog.w(TAG, "Failed to unload " + ps.codePath);
23037 // Try very hard to release any references to this package
23038 // so we don't risk the system server being killed due to
23040 AttributeCache.instance().removePackage(ps.name);
23043 mSettings.writeLPr();
23047 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23048 sendResourcesChangedBroadcast(false, false, unloaded, null);
23050 // Try very hard to release any references to this path so we don't risk
23051 // the system server being killed due to open FDs
23052 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23054 for (int i = 0; i < 3; i++) {
23056 System.runFinalization();
23060 private void assertPackageKnown(String volumeUuid, String packageName)
23061 throws PackageManagerException {
23062 synchronized (mPackages) {
23063 // Normalize package name to handle renamed packages
23064 packageName = normalizePackageNameLPr(packageName);
23066 final PackageSetting ps = mSettings.mPackages.get(packageName);
23068 throw new PackageManagerException("Package " + packageName + " is unknown");
23069 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23070 throw new PackageManagerException(
23071 "Package " + packageName + " found on unknown volume " + volumeUuid
23072 + "; expected volume " + ps.volumeUuid);
23077 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23078 throws PackageManagerException {
23079 synchronized (mPackages) {
23080 // Normalize package name to handle renamed packages
23081 packageName = normalizePackageNameLPr(packageName);
23083 final PackageSetting ps = mSettings.mPackages.get(packageName);
23085 throw new PackageManagerException("Package " + packageName + " is unknown");
23086 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23087 throw new PackageManagerException(
23088 "Package " + packageName + " found on unknown volume " + volumeUuid
23089 + "; expected volume " + ps.volumeUuid);
23090 } else if (!ps.getInstalled(userId)) {
23091 throw new PackageManagerException(
23092 "Package " + packageName + " not installed for user " + userId);
23097 private List<String> collectAbsoluteCodePaths() {
23098 synchronized (mPackages) {
23099 List<String> codePaths = new ArrayList<>();
23100 final int packageCount = mSettings.mPackages.size();
23101 for (int i = 0; i < packageCount; i++) {
23102 final PackageSetting ps = mSettings.mPackages.valueAt(i);
23103 codePaths.add(ps.codePath.getAbsolutePath());
23110 * Examine all apps present on given mounted volume, and destroy apps that
23111 * aren't expected, either due to uninstallation or reinstallation on
23114 private void reconcileApps(String volumeUuid) {
23115 List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23116 List<File> filesToDelete = null;
23118 final File[] files = FileUtils.listFilesOrEmpty(
23119 Environment.getDataAppDirectory(volumeUuid));
23120 for (File file : files) {
23121 final boolean isPackage = (isApkFile(file) || file.isDirectory())
23122 && !PackageInstallerService.isStageName(file.getName());
23124 // Ignore entries which are not packages
23128 String absolutePath = file.getAbsolutePath();
23130 boolean pathValid = false;
23131 final int absoluteCodePathCount = absoluteCodePaths.size();
23132 for (int i = 0; i < absoluteCodePathCount; i++) {
23133 String absoluteCodePath = absoluteCodePaths.get(i);
23134 if (absolutePath.startsWith(absoluteCodePath)) {
23141 if (filesToDelete == null) {
23142 filesToDelete = new ArrayList<>();
23144 filesToDelete.add(file);
23148 if (filesToDelete != null) {
23149 final int fileToDeleteCount = filesToDelete.size();
23150 for (int i = 0; i < fileToDeleteCount; i++) {
23151 File fileToDelete = filesToDelete.get(i);
23152 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23153 synchronized (mInstallLock) {
23154 removeCodePathLI(fileToDelete);
23161 * Reconcile all app data for the given user.
23163 * Verifies that directories exist and that ownership and labeling is
23164 * correct for all installed apps on all mounted volumes.
23166 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23167 final StorageManager storage = mContext.getSystemService(StorageManager.class);
23168 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23169 final String volumeUuid = vol.getFsUuid();
23170 synchronized (mInstallLock) {
23171 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23176 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23177 boolean migrateAppData) {
23178 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23182 * Reconcile all app data on given mounted volume.
23184 * Destroys app data that isn't expected, either due to uninstallation or
23185 * reinstallation on another volume.
23187 * Verifies that directories exist and that ownership and labeling is
23188 * correct for all installed apps.
23189 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23191 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23192 boolean migrateAppData, boolean onlyCoreApps) {
23193 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23194 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23195 List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23197 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23198 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23200 // First look for stale data that doesn't belong, and check if things
23201 // have changed since we did our last restorecon
23202 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23203 if (StorageManager.isFileEncryptedNativeOrEmulated()
23204 && !StorageManager.isUserKeyUnlocked(userId)) {
23205 throw new RuntimeException(
23206 "Yikes, someone asked us to reconcile CE storage while " + userId
23207 + " was still locked; this would have caused massive data loss!");
23210 final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23211 for (File file : files) {
23212 final String packageName = file.getName();
23214 assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23215 } catch (PackageManagerException e) {
23216 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23218 mInstaller.destroyAppData(volumeUuid, packageName, userId,
23219 StorageManager.FLAG_STORAGE_CE, 0);
23220 } catch (InstallerException e2) {
23221 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23226 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23227 final File[] files = FileUtils.listFilesOrEmpty(deDir);
23228 for (File file : files) {
23229 final String packageName = file.getName();
23231 assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23232 } catch (PackageManagerException e) {
23233 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23235 mInstaller.destroyAppData(volumeUuid, packageName, userId,
23236 StorageManager.FLAG_STORAGE_DE, 0);
23237 } catch (InstallerException e2) {
23238 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23244 // Ensure that data directories are ready to roll for all packages
23245 // installed for this volume and user
23246 final List<PackageSetting> packages;
23247 synchronized (mPackages) {
23248 packages = mSettings.getVolumePackagesLPr(volumeUuid);
23250 int preparedCount = 0;
23251 for (PackageSetting ps : packages) {
23252 final String packageName = ps.name;
23253 if (ps.pkg == null) {
23254 Slog.w(TAG, "Odd, missing scanned package " + packageName);
23255 // TODO: might be due to legacy ASEC apps; we should circle back
23256 // and reconcile again once they're scanned
23259 // Skip non-core apps if requested
23260 if (onlyCoreApps && !ps.pkg.coreApp) {
23261 result.add(packageName);
23265 if (ps.getInstalled(userId)) {
23266 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23271 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23276 * Prepare app data for the given app just after it was installed or
23277 * upgraded. This method carefully only touches users that it's installed
23278 * for, and it forces a restorecon to handle any seinfo changes.
23280 * Verifies that directories exist and that ownership and labeling is
23281 * correct for all installed apps. If there is an ownership mismatch, it
23282 * will try recovering system apps by wiping data; third-party app data is
23285 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23287 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23288 final PackageSetting ps;
23289 synchronized (mPackages) {
23290 ps = mSettings.mPackages.get(pkg.packageName);
23291 mSettings.writeKernelMappingLPr(ps);
23294 final UserManager um = mContext.getSystemService(UserManager.class);
23295 UserManagerInternal umInternal = getUserManagerInternal();
23296 for (UserInfo user : um.getUsers()) {
23298 if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23299 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23300 } else if (umInternal.isUserRunning(user.id)) {
23301 flags = StorageManager.FLAG_STORAGE_DE;
23306 if (ps.getInstalled(user.id)) {
23307 // TODO: when user data is locked, mark that we're still dirty
23308 prepareAppDataLIF(pkg, user.id, flags);
23314 * Prepare app data for the given app.
23316 * Verifies that directories exist and that ownership and labeling is
23317 * correct for all installed apps. If there is an ownership mismatch, this
23318 * will try recovering system apps by wiping data; third-party app data is
23321 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23323 Slog.wtf(TAG, "Package was null!", new Throwable());
23326 prepareAppDataLeafLIF(pkg, userId, flags);
23327 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23328 for (int i = 0; i < childCount; i++) {
23329 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23333 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23334 boolean maybeMigrateAppData) {
23335 prepareAppDataLIF(pkg, userId, flags);
23337 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23338 // We may have just shuffled around app data directories, so
23339 // prepare them one more time
23340 prepareAppDataLIF(pkg, userId, flags);
23344 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23345 if (DEBUG_APP_DATA) {
23346 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23347 + Integer.toHexString(flags));
23350 final String volumeUuid = pkg.volumeUuid;
23351 final String packageName = pkg.packageName;
23352 final ApplicationInfo app = pkg.applicationInfo;
23353 final int appId = UserHandle.getAppId(app.uid);
23355 Preconditions.checkNotNull(app.seInfo);
23357 long ceDataInode = -1;
23359 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23360 appId, app.seInfo, app.targetSdkVersion);
23361 } catch (InstallerException e) {
23362 if (app.isSystemApp()) {
23363 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23364 + ", but trying to recover: " + e);
23365 destroyAppDataLeafLIF(pkg, userId, flags);
23367 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23368 appId, app.seInfo, app.targetSdkVersion);
23369 logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23370 } catch (InstallerException e2) {
23371 logCriticalInfo(Log.DEBUG, "Recovery failed!");
23374 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23378 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23379 // TODO: mark this structure as dirty so we persist it!
23380 synchronized (mPackages) {
23381 final PackageSetting ps = mSettings.mPackages.get(packageName);
23383 ps.setCeDataInode(ceDataInode, userId);
23388 prepareAppDataContentsLeafLIF(pkg, userId, flags);
23391 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23393 Slog.wtf(TAG, "Package was null!", new Throwable());
23396 prepareAppDataContentsLeafLIF(pkg, userId, flags);
23397 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23398 for (int i = 0; i < childCount; i++) {
23399 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23403 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23404 final String volumeUuid = pkg.volumeUuid;
23405 final String packageName = pkg.packageName;
23406 final ApplicationInfo app = pkg.applicationInfo;
23408 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23409 // Create a native library symlink only if we have native libraries
23410 // and if the native libraries are 32 bit libraries. We do not provide
23411 // this symlink for 64 bit libraries.
23412 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23413 final String nativeLibPath = app.nativeLibraryDir;
23415 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23416 nativeLibPath, userId);
23417 } catch (InstallerException e) {
23418 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23425 * For system apps on non-FBE devices, this method migrates any existing
23426 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23427 * requested by the app.
23429 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23430 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23431 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23432 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23433 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23435 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23437 } catch (InstallerException e) {
23438 logCriticalInfo(Log.WARN,
23439 "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23447 public PackageFreezer freezePackage(String packageName, String killReason) {
23448 return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23451 public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23452 return new PackageFreezer(packageName, userId, killReason);
23455 public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23456 String killReason) {
23457 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23460 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23461 String killReason) {
23462 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23463 return new PackageFreezer();
23465 return freezePackage(packageName, userId, killReason);
23469 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23470 String killReason) {
23471 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23474 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23475 String killReason) {
23476 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23477 return new PackageFreezer();
23479 return freezePackage(packageName, userId, killReason);
23484 * Class that freezes and kills the given package upon creation, and
23485 * unfreezes it upon closing. This is typically used when doing surgery on
23486 * app code/data to prevent the app from running while you're working.
23488 private class PackageFreezer implements AutoCloseable {
23489 private final String mPackageName;
23490 private final PackageFreezer[] mChildren;
23492 private final boolean mWeFroze;
23494 private final AtomicBoolean mClosed = new AtomicBoolean();
23495 private final CloseGuard mCloseGuard = CloseGuard.get();
23498 * Create and return a stub freezer that doesn't actually do anything,
23499 * typically used when someone requested
23500 * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23501 * {@link PackageManager#DELETE_DONT_KILL_APP}.
23503 public PackageFreezer() {
23504 mPackageName = null;
23507 mCloseGuard.open("close");
23510 public PackageFreezer(String packageName, int userId, String killReason) {
23511 synchronized (mPackages) {
23512 mPackageName = packageName;
23513 mWeFroze = mFrozenPackages.add(mPackageName);
23515 final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23517 killApplication(ps.name, ps.appId, userId, killReason);
23520 final PackageParser.Package p = mPackages.get(packageName);
23521 if (p != null && p.childPackages != null) {
23522 final int N = p.childPackages.size();
23523 mChildren = new PackageFreezer[N];
23524 for (int i = 0; i < N; i++) {
23525 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23526 userId, killReason);
23532 mCloseGuard.open("close");
23536 protected void finalize() throws Throwable {
23538 mCloseGuard.warnIfOpen();
23546 public void close() {
23547 mCloseGuard.close();
23548 if (mClosed.compareAndSet(false, true)) {
23549 synchronized (mPackages) {
23551 mFrozenPackages.remove(mPackageName);
23554 if (mChildren != null) {
23555 for (PackageFreezer freezer : mChildren) {
23565 * Verify that given package is currently frozen.
23567 private void checkPackageFrozen(String packageName) {
23568 synchronized (mPackages) {
23569 if (!mFrozenPackages.contains(packageName)) {
23570 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23576 public int movePackage(final String packageName, final String volumeUuid) {
23577 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23579 final int callingUid = Binder.getCallingUid();
23580 final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23581 final int moveId = mNextMoveId.getAndIncrement();
23582 mHandler.post(new Runnable() {
23584 public void run() {
23586 movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23587 } catch (PackageManagerException e) {
23588 Slog.w(TAG, "Failed to move " + packageName, e);
23589 mMoveCallbacks.notifyStatusChanged(moveId,
23590 PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23597 private void movePackageInternal(final String packageName, final String volumeUuid,
23598 final int moveId, final int callingUid, UserHandle user)
23599 throws PackageManagerException {
23600 final StorageManager storage = mContext.getSystemService(StorageManager.class);
23601 final PackageManager pm = mContext.getPackageManager();
23603 final boolean currentAsec;
23604 final String currentVolumeUuid;
23605 final File codeFile;
23606 final String installerPackageName;
23607 final String packageAbiOverride;
23609 final String seinfo;
23610 final String label;
23611 final int targetSdkVersion;
23612 final PackageFreezer freezer;
23613 final int[] installedUserIds;
23616 synchronized (mPackages) {
23617 final PackageParser.Package pkg = mPackages.get(packageName);
23618 final PackageSetting ps = mSettings.mPackages.get(packageName);
23621 || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23622 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23624 if (pkg.applicationInfo.isSystemApp()) {
23625 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23626 "Cannot move system application");
23629 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23630 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23631 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23632 if (isInternalStorage && !allow3rdPartyOnInternal) {
23633 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23634 "3rd party apps are not allowed on internal storage");
23637 if (pkg.applicationInfo.isExternalAsec()) {
23638 currentAsec = true;
23639 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23640 } else if (pkg.applicationInfo.isForwardLocked()) {
23641 currentAsec = true;
23642 currentVolumeUuid = "forward_locked";
23644 currentAsec = false;
23645 currentVolumeUuid = ps.volumeUuid;
23647 final File probe = new File(pkg.codePath);
23648 final File probeOat = new File(probe, "oat");
23649 if (!probe.isDirectory() || !probeOat.isDirectory()) {
23650 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23651 "Move only supported for modern cluster style installs");
23655 if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23656 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23657 "Package already moved to " + volumeUuid);
23659 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23660 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23661 "Device admin cannot be moved");
23664 if (mFrozenPackages.contains(packageName)) {
23665 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23666 "Failed to move already frozen package");
23669 codeFile = new File(pkg.codePath);
23670 installerPackageName = ps.installerPackageName;
23671 packageAbiOverride = ps.cpuAbiOverrideString;
23672 appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23673 seinfo = pkg.applicationInfo.seInfo;
23674 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23675 targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23676 freezer = freezePackage(packageName, "movePackageInternal");
23677 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23680 final Bundle extras = new Bundle();
23681 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23682 extras.putString(Intent.EXTRA_TITLE, label);
23683 mMoveCallbacks.notifyCreated(moveId, extras);
23686 final boolean moveCompleteApp;
23687 final File measurePath;
23689 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23690 installFlags = INSTALL_INTERNAL;
23691 moveCompleteApp = !currentAsec;
23692 measurePath = Environment.getDataAppDirectory(volumeUuid);
23693 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23694 installFlags = INSTALL_EXTERNAL;
23695 moveCompleteApp = false;
23696 measurePath = storage.getPrimaryPhysicalVolume().getPath();
23698 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23699 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23700 || !volume.isMountedWritable()) {
23702 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23703 "Move location not mounted private volume");
23706 Preconditions.checkState(!currentAsec);
23708 installFlags = INSTALL_INTERNAL;
23709 moveCompleteApp = true;
23710 measurePath = Environment.getDataAppDirectory(volumeUuid);
23713 final PackageStats stats = new PackageStats(null, -1);
23714 synchronized (mInstaller) {
23715 for (int userId : installedUserIds) {
23716 if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23718 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23719 "Failed to measure package size");
23724 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23727 final long startFreeBytes = measurePath.getUsableSpace();
23728 final long sizeBytes;
23729 if (moveCompleteApp) {
23730 sizeBytes = stats.codeSize + stats.dataSize;
23732 sizeBytes = stats.codeSize;
23735 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23737 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23738 "Not enough free space to move");
23741 mMoveCallbacks.notifyStatusChanged(moveId, 10);
23743 final CountDownLatch installedLatch = new CountDownLatch(1);
23744 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23746 public void onUserActionRequired(Intent intent) throws RemoteException {
23747 throw new IllegalStateException();
23751 public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23752 Bundle extras) throws RemoteException {
23753 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23754 + PackageManager.installStatusToString(returnCode, msg));
23756 installedLatch.countDown();
23759 final int status = PackageManager.installStatusToPublicStatus(returnCode);
23761 case PackageInstaller.STATUS_SUCCESS:
23762 mMoveCallbacks.notifyStatusChanged(moveId,
23763 PackageManager.MOVE_SUCCEEDED);
23765 case PackageInstaller.STATUS_FAILURE_STORAGE:
23766 mMoveCallbacks.notifyStatusChanged(moveId,
23767 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23770 mMoveCallbacks.notifyStatusChanged(moveId,
23771 PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23777 final MoveInfo move;
23778 if (moveCompleteApp) {
23779 // Kick off a thread to report progress estimates
23782 public void run() {
23785 if (installedLatch.await(1, TimeUnit.SECONDS)) {
23788 } catch (InterruptedException ignored) {
23791 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23792 final int progress = 10 + (int) MathUtils.constrain(
23793 ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23794 mMoveCallbacks.notifyStatusChanged(moveId, progress);
23799 final String dataAppName = codeFile.getName();
23800 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23801 dataAppName, appId, seinfo, targetSdkVersion);
23806 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23808 final Message msg = mHandler.obtainMessage(INIT_COPY);
23809 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23810 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23811 installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23812 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23813 PackageManager.INSTALL_REASON_UNKNOWN);
23814 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23817 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23818 System.identityHashCode(msg.obj));
23819 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23820 System.identityHashCode(msg.obj));
23822 mHandler.sendMessage(msg);
23826 public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23827 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23829 final int realMoveId = mNextMoveId.getAndIncrement();
23830 final Bundle extras = new Bundle();
23831 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23832 mMoveCallbacks.notifyCreated(realMoveId, extras);
23834 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23836 public void onCreated(int moveId, Bundle extras) {
23841 public void onStatusChanged(int moveId, int status, long estMillis) {
23842 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23846 final StorageManager storage = mContext.getSystemService(StorageManager.class);
23847 storage.setPrimaryStorageUuid(volumeUuid, callback);
23852 public int getMoveStatus(int moveId) {
23853 mContext.enforceCallingOrSelfPermission(
23854 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23855 return mMoveCallbacks.mLastStatus.get(moveId);
23859 public void registerMoveCallback(IPackageMoveObserver callback) {
23860 mContext.enforceCallingOrSelfPermission(
23861 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23862 mMoveCallbacks.register(callback);
23866 public void unregisterMoveCallback(IPackageMoveObserver callback) {
23867 mContext.enforceCallingOrSelfPermission(
23868 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23869 mMoveCallbacks.unregister(callback);
23873 public boolean setInstallLocation(int loc) {
23874 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23876 if (getInstallLocation() == loc) {
23879 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23880 || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23881 android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23882 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23889 public int getInstallLocation() {
23890 // allow instant app access
23891 return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23892 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23893 PackageHelper.APP_INSTALL_AUTO);
23896 /** Called by UserManagerService */
23897 void cleanUpUser(UserManagerService userManager, int userHandle) {
23898 synchronized (mPackages) {
23899 mDirtyUsers.remove(userHandle);
23900 mUserNeedsBadging.delete(userHandle);
23901 mSettings.removeUserLPw(userHandle);
23902 mPendingBroadcasts.remove(userHandle);
23903 mInstantAppRegistry.onUserRemovedLPw(userHandle);
23904 removeUnusedPackagesLPw(userManager, userHandle);
23909 * We're removing userHandle and would like to remove any downloaded packages
23910 * that are no longer in use by any other user.
23911 * @param userHandle the user being removed
23913 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23914 final boolean DEBUG_CLEAN_APKS = false;
23915 int [] users = userManager.getUserIds();
23916 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23917 while (psit.hasNext()) {
23918 PackageSetting ps = psit.next();
23919 if (ps.pkg == null) {
23922 final String packageName = ps.pkg.packageName;
23923 // Skip over if system app
23924 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23927 if (DEBUG_CLEAN_APKS) {
23928 Slog.i(TAG, "Checking package " + packageName);
23930 boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23932 if (DEBUG_CLEAN_APKS) {
23933 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO");
23936 for (int i = 0; i < users.length; i++) {
23937 if (users[i] != userHandle && ps.getInstalled(users[i])) {
23939 if (DEBUG_CLEAN_APKS) {
23940 Slog.i(TAG, " Keeping package " + packageName + " for user "
23948 if (DEBUG_CLEAN_APKS) {
23949 Slog.i(TAG, " Removing package " + packageName);
23951 mHandler.post(new Runnable() {
23952 public void run() {
23953 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23961 /** Called by UserManagerService */
23962 void createNewUser(int userId, String[] disallowedPackages) {
23963 synchronized (mInstallLock) {
23964 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23966 synchronized (mPackages) {
23967 scheduleWritePackageRestrictionsLocked(userId);
23968 scheduleWritePackageListLocked(userId);
23969 applyFactoryDefaultBrowserLPw(userId);
23970 primeDomainVerificationsLPw(userId);
23974 void onNewUserCreated(final int userId) {
23975 mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23976 // If permission review for legacy apps is required, we represent
23977 // dagerous permissions for such apps as always granted runtime
23978 // permissions to keep per user flag state whether review is needed.
23979 // Hence, if a new user is added we have to propagate dangerous
23980 // permission grants for these legacy apps.
23981 if (mPermissionReviewRequired) {
23982 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
23983 | UPDATE_PERMISSIONS_REPLACE_ALL);
23988 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23989 mContext.enforceCallingOrSelfPermission(
23990 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23991 "Only package verification agents can read the verifier device identity");
23993 synchronized (mPackages) {
23994 return mSettings.getVerifierDeviceIdentityLPw();
23999 public void setPermissionEnforced(String permission, boolean enforced) {
24000 // TODO: Now that we no longer change GID for storage, this should to away.
24001 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24002 "setPermissionEnforced");
24003 if (READ_EXTERNAL_STORAGE.equals(permission)) {
24004 synchronized (mPackages) {
24005 if (mSettings.mReadExternalStorageEnforced == null
24006 || mSettings.mReadExternalStorageEnforced != enforced) {
24007 mSettings.mReadExternalStorageEnforced = enforced;
24008 mSettings.writeLPr();
24011 // kill any non-foreground processes so we restart them and
24012 // grant/revoke the GID.
24013 final IActivityManager am = ActivityManager.getService();
24015 final long token = Binder.clearCallingIdentity();
24017 am.killProcessesBelowForeground("setPermissionEnforcement");
24018 } catch (RemoteException e) {
24020 Binder.restoreCallingIdentity(token);
24024 throw new IllegalArgumentException("No selective enforcement for " + permission);
24030 public boolean isPermissionEnforced(String permission) {
24031 // allow instant applications
24036 public boolean isStorageLow() {
24037 // allow instant applications
24038 final long token = Binder.clearCallingIdentity();
24040 final DeviceStorageMonitorInternal
24041 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24043 return dsm.isMemoryLow();
24048 Binder.restoreCallingIdentity(token);
24053 public IPackageInstaller getPackageInstaller() {
24054 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24057 return mInstallerService;
24060 private boolean userNeedsBadging(int userId) {
24061 int index = mUserNeedsBadging.indexOfKey(userId);
24063 final UserInfo userInfo;
24064 final long token = Binder.clearCallingIdentity();
24066 userInfo = sUserManager.getUserInfo(userId);
24068 Binder.restoreCallingIdentity(token);
24071 if (userInfo != null && userInfo.isManagedProfile()) {
24076 mUserNeedsBadging.put(userId, b);
24079 return mUserNeedsBadging.valueAt(index);
24083 public KeySet getKeySetByAlias(String packageName, String alias) {
24084 if (packageName == null || alias == null) {
24087 synchronized(mPackages) {
24088 final PackageParser.Package pkg = mPackages.get(packageName);
24090 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24091 throw new IllegalArgumentException("Unknown package: " + packageName);
24093 final PackageSetting ps = (PackageSetting) pkg.mExtras;
24094 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24095 Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24096 throw new IllegalArgumentException("Unknown package: " + packageName);
24098 KeySetManagerService ksms = mSettings.mKeySetManagerService;
24099 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24104 public KeySet getSigningKeySet(String packageName) {
24105 if (packageName == null) {
24108 synchronized(mPackages) {
24109 final int callingUid = Binder.getCallingUid();
24110 final int callingUserId = UserHandle.getUserId(callingUid);
24111 final PackageParser.Package pkg = mPackages.get(packageName);
24113 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24114 throw new IllegalArgumentException("Unknown package: " + packageName);
24116 final PackageSetting ps = (PackageSetting) pkg.mExtras;
24117 if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24118 // filter and pretend the package doesn't exist
24119 Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24120 + ", uid:" + callingUid);
24121 throw new IllegalArgumentException("Unknown package: " + packageName);
24123 if (pkg.applicationInfo.uid != callingUid
24124 && Process.SYSTEM_UID != callingUid) {
24125 throw new SecurityException("May not access signing KeySet of other apps.");
24127 KeySetManagerService ksms = mSettings.mKeySetManagerService;
24128 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24133 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24134 final int callingUid = Binder.getCallingUid();
24135 if (getInstantAppPackageName(callingUid) != null) {
24138 if (packageName == null || ks == null) {
24141 synchronized(mPackages) {
24142 final PackageParser.Package pkg = mPackages.get(packageName);
24144 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24145 UserHandle.getUserId(callingUid))) {
24146 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24147 throw new IllegalArgumentException("Unknown package: " + packageName);
24149 IBinder ksh = ks.getToken();
24150 if (ksh instanceof KeySetHandle) {
24151 KeySetManagerService ksms = mSettings.mKeySetManagerService;
24152 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24159 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24160 final int callingUid = Binder.getCallingUid();
24161 if (getInstantAppPackageName(callingUid) != null) {
24164 if (packageName == null || ks == null) {
24167 synchronized(mPackages) {
24168 final PackageParser.Package pkg = mPackages.get(packageName);
24170 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24171 UserHandle.getUserId(callingUid))) {
24172 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24173 throw new IllegalArgumentException("Unknown package: " + packageName);
24175 IBinder ksh = ks.getToken();
24176 if (ksh instanceof KeySetHandle) {
24177 KeySetManagerService ksms = mSettings.mKeySetManagerService;
24178 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24184 private void deletePackageIfUnusedLPr(final String packageName) {
24185 PackageSetting ps = mSettings.mPackages.get(packageName);
24189 if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24190 // TODO Implement atomic delete if package is unused
24191 // It is currently possible that the package will be deleted even if it is installed
24192 // after this method returns.
24193 mHandler.post(new Runnable() {
24194 public void run() {
24195 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24196 0, PackageManager.DELETE_ALL_USERS);
24203 * Check and throw if the given before/after packages would be considered a
24206 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24207 throws PackageManagerException {
24208 if (after.versionCode < before.mVersionCode) {
24209 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24210 "Update version code " + after.versionCode + " is older than current "
24211 + before.mVersionCode);
24212 } else if (after.versionCode == before.mVersionCode) {
24213 if (after.baseRevisionCode < before.baseRevisionCode) {
24214 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24215 "Update base revision code " + after.baseRevisionCode
24216 + " is older than current " + before.baseRevisionCode);
24219 if (!ArrayUtils.isEmpty(after.splitNames)) {
24220 for (int i = 0; i < after.splitNames.length; i++) {
24221 final String splitName = after.splitNames[i];
24222 final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24224 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24225 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24226 "Update split " + splitName + " revision code "
24227 + after.splitRevisionCodes[i] + " is older than current "
24228 + before.splitRevisionCodes[j]);
24236 private static class MoveCallbacks extends Handler {
24237 private static final int MSG_CREATED = 1;
24238 private static final int MSG_STATUS_CHANGED = 2;
24240 private final RemoteCallbackList<IPackageMoveObserver>
24241 mCallbacks = new RemoteCallbackList<>();
24243 private final SparseIntArray mLastStatus = new SparseIntArray();
24245 public MoveCallbacks(Looper looper) {
24249 public void register(IPackageMoveObserver callback) {
24250 mCallbacks.register(callback);
24253 public void unregister(IPackageMoveObserver callback) {
24254 mCallbacks.unregister(callback);
24258 public void handleMessage(Message msg) {
24259 final SomeArgs args = (SomeArgs) msg.obj;
24260 final int n = mCallbacks.beginBroadcast();
24261 for (int i = 0; i < n; i++) {
24262 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24264 invokeCallback(callback, msg.what, args);
24265 } catch (RemoteException ignored) {
24268 mCallbacks.finishBroadcast();
24272 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24273 throws RemoteException {
24275 case MSG_CREATED: {
24276 callback.onCreated(args.argi1, (Bundle) args.arg2);
24279 case MSG_STATUS_CHANGED: {
24280 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24286 private void notifyCreated(int moveId, Bundle extras) {
24287 Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24289 final SomeArgs args = SomeArgs.obtain();
24290 args.argi1 = moveId;
24291 args.arg2 = extras;
24292 obtainMessage(MSG_CREATED, args).sendToTarget();
24295 private void notifyStatusChanged(int moveId, int status) {
24296 notifyStatusChanged(moveId, status, -1);
24299 private void notifyStatusChanged(int moveId, int status, long estMillis) {
24300 Slog.v(TAG, "Move " + moveId + " status " + status);
24302 final SomeArgs args = SomeArgs.obtain();
24303 args.argi1 = moveId;
24304 args.argi2 = status;
24305 args.arg3 = estMillis;
24306 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24308 synchronized (mLastStatus) {
24309 mLastStatus.put(moveId, status);
24314 private final static class OnPermissionChangeListeners extends Handler {
24315 private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24317 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24318 new RemoteCallbackList<>();
24320 public OnPermissionChangeListeners(Looper looper) {
24325 public void handleMessage(Message msg) {
24326 switch (msg.what) {
24327 case MSG_ON_PERMISSIONS_CHANGED: {
24328 final int uid = msg.arg1;
24329 handleOnPermissionsChanged(uid);
24334 public void addListenerLocked(IOnPermissionsChangeListener listener) {
24335 mPermissionListeners.register(listener);
24339 public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24340 mPermissionListeners.unregister(listener);
24343 public void onPermissionsChanged(int uid) {
24344 if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24345 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24349 private void handleOnPermissionsChanged(int uid) {
24350 final int count = mPermissionListeners.beginBroadcast();
24352 for (int i = 0; i < count; i++) {
24353 IOnPermissionsChangeListener callback = mPermissionListeners
24354 .getBroadcastItem(i);
24356 callback.onPermissionsChanged(uid);
24357 } catch (RemoteException e) {
24358 Log.e(TAG, "Permission listener is dead", e);
24362 mPermissionListeners.finishBroadcast();
24367 private class PackageManagerInternalImpl extends PackageManagerInternal {
24369 public void setLocationPackagesProvider(PackagesProvider provider) {
24370 synchronized (mPackages) {
24371 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24376 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24377 synchronized (mPackages) {
24378 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24383 public void setSmsAppPackagesProvider(PackagesProvider provider) {
24384 synchronized (mPackages) {
24385 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24390 public void setDialerAppPackagesProvider(PackagesProvider provider) {
24391 synchronized (mPackages) {
24392 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24397 public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24398 synchronized (mPackages) {
24399 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24404 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24405 synchronized (mPackages) {
24406 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24411 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24412 synchronized (mPackages) {
24413 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24414 packageName, userId);
24419 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24420 synchronized (mPackages) {
24421 mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24422 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24423 packageName, userId);
24428 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24429 synchronized (mPackages) {
24430 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24431 packageName, userId);
24436 public void setKeepUninstalledPackages(final List<String> packageList) {
24437 Preconditions.checkNotNull(packageList);
24438 List<String> removedFromList = null;
24439 synchronized (mPackages) {
24440 if (mKeepUninstalledPackages != null) {
24441 final int packagesCount = mKeepUninstalledPackages.size();
24442 for (int i = 0; i < packagesCount; i++) {
24443 String oldPackage = mKeepUninstalledPackages.get(i);
24444 if (packageList != null && packageList.contains(oldPackage)) {
24447 if (removedFromList == null) {
24448 removedFromList = new ArrayList<>();
24450 removedFromList.add(oldPackage);
24453 mKeepUninstalledPackages = new ArrayList<>(packageList);
24454 if (removedFromList != null) {
24455 final int removedCount = removedFromList.size();
24456 for (int i = 0; i < removedCount; i++) {
24457 deletePackageIfUnusedLPr(removedFromList.get(i));
24464 public boolean isPermissionsReviewRequired(String packageName, int userId) {
24465 synchronized (mPackages) {
24466 // If we do not support permission review, done.
24467 if (!mPermissionReviewRequired) {
24471 PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24472 if (packageSetting == null) {
24476 // Permission review applies only to apps not supporting the new permission model.
24477 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24481 // Legacy apps have the permission and get user consent on launch.
24482 PermissionsState permissionsState = packageSetting.getPermissionsState();
24483 return permissionsState.isPermissionReviewRequired(userId);
24488 public PackageInfo getPackageInfo(
24489 String packageName, int flags, int filterCallingUid, int userId) {
24490 return PackageManagerService.this
24491 .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24492 flags, filterCallingUid, userId);
24496 public ApplicationInfo getApplicationInfo(
24497 String packageName, int flags, int filterCallingUid, int userId) {
24498 return PackageManagerService.this
24499 .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24503 public ActivityInfo getActivityInfo(
24504 ComponentName component, int flags, int filterCallingUid, int userId) {
24505 return PackageManagerService.this
24506 .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24510 public List<ResolveInfo> queryIntentActivities(
24511 Intent intent, int flags, int filterCallingUid, int userId) {
24512 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24513 return PackageManagerService.this
24514 .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24515 userId, false /*resolveForStart*/);
24519 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24521 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24525 public void setDeviceAndProfileOwnerPackages(
24526 int deviceOwnerUserId, String deviceOwnerPackage,
24527 SparseArray<String> profileOwnerPackages) {
24528 mProtectedPackages.setDeviceAndProfileOwnerPackages(
24529 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24533 public boolean isPackageDataProtected(int userId, String packageName) {
24534 return mProtectedPackages.isPackageDataProtected(userId, packageName);
24538 public boolean isPackageEphemeral(int userId, String packageName) {
24539 synchronized (mPackages) {
24540 final PackageSetting ps = mSettings.mPackages.get(packageName);
24541 return ps != null ? ps.getInstantApp(userId) : false;
24546 public boolean wasPackageEverLaunched(String packageName, int userId) {
24547 synchronized (mPackages) {
24548 return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24553 public void grantRuntimePermission(String packageName, String name, int userId,
24554 boolean overridePolicy) {
24555 PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24560 public void revokeRuntimePermission(String packageName, String name, int userId,
24561 boolean overridePolicy) {
24562 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24567 public String getNameForUid(int uid) {
24568 return PackageManagerService.this.getNameForUid(uid);
24572 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24573 Intent origIntent, String resolvedType, String callingPackage,
24574 Bundle verificationBundle, int userId) {
24575 PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24576 responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24581 public void grantEphemeralAccess(int userId, Intent intent,
24582 int targetAppId, int ephemeralAppId) {
24583 synchronized (mPackages) {
24584 mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24585 targetAppId, ephemeralAppId);
24590 public boolean isInstantAppInstallerComponent(ComponentName component) {
24591 synchronized (mPackages) {
24592 return mInstantAppInstallerActivity != null
24593 && mInstantAppInstallerActivity.getComponentName().equals(component);
24598 public void pruneInstantApps() {
24599 mInstantAppRegistry.pruneInstantApps();
24603 public String getSetupWizardPackageName() {
24604 return mSetupWizardPackage;
24607 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24608 if (policy != null) {
24609 mExternalSourcesPolicy = policy;
24614 public boolean isPackagePersistent(String packageName) {
24615 synchronized (mPackages) {
24616 PackageParser.Package pkg = mPackages.get(packageName);
24618 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24619 | ApplicationInfo.FLAG_PERSISTENT)) ==
24620 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24626 public List<PackageInfo> getOverlayPackages(int userId) {
24627 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24628 synchronized (mPackages) {
24629 for (PackageParser.Package p : mPackages.values()) {
24630 if (p.mOverlayTarget != null) {
24631 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24633 overlayPackages.add(pkg);
24638 return overlayPackages;
24642 public List<String> getTargetPackageNames(int userId) {
24643 List<String> targetPackages = new ArrayList<>();
24644 synchronized (mPackages) {
24645 for (PackageParser.Package p : mPackages.values()) {
24646 if (p.mOverlayTarget == null) {
24647 targetPackages.add(p.packageName);
24651 return targetPackages;
24655 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24656 @Nullable List<String> overlayPackageNames) {
24657 synchronized (mPackages) {
24658 if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24659 Slog.e(TAG, "failed to find package " + targetPackageName);
24662 ArrayList<String> overlayPaths = null;
24663 if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24664 final int N = overlayPackageNames.size();
24665 overlayPaths = new ArrayList<>(N);
24666 for (int i = 0; i < N; i++) {
24667 final String packageName = overlayPackageNames.get(i);
24668 final PackageParser.Package pkg = mPackages.get(packageName);
24670 Slog.e(TAG, "failed to find package " + packageName);
24673 overlayPaths.add(pkg.baseCodePath);
24677 final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24678 ps.setOverlayPaths(overlayPaths, userId);
24684 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24685 int flags, int userId) {
24686 return resolveIntentInternal(
24687 intent, resolvedType, flags, userId, true /*resolveForStart*/);
24691 public ResolveInfo resolveService(Intent intent, String resolvedType,
24692 int flags, int userId, int callingUid) {
24693 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24697 public void addIsolatedUid(int isolatedUid, int ownerUid) {
24698 synchronized (mPackages) {
24699 mIsolatedOwners.put(isolatedUid, ownerUid);
24704 public void removeIsolatedUid(int isolatedUid) {
24705 synchronized (mPackages) {
24706 mIsolatedOwners.delete(isolatedUid);
24711 public int getUidTargetSdkVersion(int uid) {
24712 synchronized (mPackages) {
24713 return getUidTargetSdkVersionLockedLPr(uid);
24718 public boolean canAccessInstantApps(int callingUid, int userId) {
24719 return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24724 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24725 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24726 synchronized (mPackages) {
24727 final long identity = Binder.clearCallingIdentity();
24729 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24730 packageNames, userId);
24732 Binder.restoreCallingIdentity(identity);
24738 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24739 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24740 synchronized (mPackages) {
24741 final long identity = Binder.clearCallingIdentity();
24743 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24744 packageNames, userId);
24746 Binder.restoreCallingIdentity(identity);
24751 private static void enforceSystemOrPhoneCaller(String tag) {
24752 int callingUid = Binder.getCallingUid();
24753 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24754 throw new SecurityException(
24755 "Cannot call " + tag + " from UID " + callingUid);
24759 boolean isHistoricalPackageUsageAvailable() {
24760 return mPackageUsage.isHistoricalPackageUsageAvailable();
24764 * Return a <b>copy</b> of the collection of packages known to the package manager.
24765 * @return A copy of the values of mPackages.
24767 Collection<PackageParser.Package> getPackages() {
24768 synchronized (mPackages) {
24769 return new ArrayList<>(mPackages.values());
24774 * Logs process start information (including base APK hash) to the security log.
24778 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24779 String apkFile, int pid) {
24780 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24783 if (!SecurityLog.isLoggingEnabled()) {
24786 Bundle data = new Bundle();
24787 data.putLong("startTimestamp", System.currentTimeMillis());
24788 data.putString("processName", processName);
24789 data.putInt("uid", uid);
24790 data.putString("seinfo", seinfo);
24791 data.putString("apkFile", apkFile);
24792 data.putInt("pid", pid);
24793 Message msg = mProcessLoggingHandler.obtainMessage(
24794 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24796 mProcessLoggingHandler.sendMessage(msg);
24799 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24800 return mCompilerStats.getPackageStats(pkgName);
24803 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24804 return getOrCreateCompilerPackageStats(pkg.packageName);
24807 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24808 return mCompilerStats.getOrCreatePackageStats(pkgName);
24811 public void deleteCompilerPackageStats(String pkgName) {
24812 mCompilerStats.deletePackageStats(pkgName);
24816 public int getInstallReason(String packageName, int userId) {
24817 final int callingUid = Binder.getCallingUid();
24818 enforceCrossUserPermission(callingUid, userId,
24819 true /* requireFullPermission */, false /* checkShell */,
24820 "get install reason");
24821 synchronized (mPackages) {
24822 final PackageSetting ps = mSettings.mPackages.get(packageName);
24823 if (filterAppAccessLPr(ps, callingUid, userId)) {
24824 return PackageManager.INSTALL_REASON_UNKNOWN;
24827 return ps.getInstallReason(userId);
24830 return PackageManager.INSTALL_REASON_UNKNOWN;
24834 public boolean canRequestPackageInstalls(String packageName, int userId) {
24835 return canRequestPackageInstallsInternal(packageName, 0, userId,
24836 true /* throwIfPermNotDeclared*/);
24839 private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24840 boolean throwIfPermNotDeclared) {
24841 int callingUid = Binder.getCallingUid();
24842 int uid = getPackageUid(packageName, 0, userId);
24843 if (callingUid != uid && callingUid != Process.ROOT_UID
24844 && callingUid != Process.SYSTEM_UID) {
24845 throw new SecurityException(
24846 "Caller uid " + callingUid + " does not own package " + packageName);
24848 ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24849 if (info == null) {
24852 if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24855 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24856 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24857 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24858 if (throwIfPermNotDeclared) {
24859 throw new SecurityException("Need to declare " + appOpPermission
24860 + " to call this api");
24862 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24866 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24869 if (mExternalSourcesPolicy != null) {
24870 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24871 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24872 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24875 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24879 public ComponentName getInstantAppResolverSettingsComponent() {
24880 return mInstantAppResolverSettingsComponent;
24884 public ComponentName getInstantAppInstallerComponent() {
24885 if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24888 return mInstantAppInstallerActivity == null
24889 ? null : mInstantAppInstallerActivity.getComponentName();
24893 public String getInstantAppAndroidId(String packageName, int userId) {
24894 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24895 "getInstantAppAndroidId");
24896 enforceCrossUserPermission(Binder.getCallingUid(), userId,
24897 true /* requireFullPermission */, false /* checkShell */,
24898 "getInstantAppAndroidId");
24899 // Make sure the target is an Instant App.
24900 if (!isInstantApp(packageName, userId)) {
24903 synchronized (mPackages) {
24904 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24909 interface PackageSender {
24910 void sendPackageBroadcast(final String action, final String pkg,
24911 final Bundle extras, final int flags, final String targetPkg,
24912 final IIntentReceiver finishedReceiver, final int[] userIds);
24913 void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
24914 int appId, int... userIds);